Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

core memory tier: render/list module, write-path guard, core_edit_notices table

garrytan25d831db2112
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 13f925c9a0..0f01a527da 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -499,6 +499,46 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| The content-sanity gate rejected the content because the operator set `content_sanity.junk_disposition` to `reject`. | A junk-pattern or operator-literal hit is refused instead of quarantined under that setting, so the page was not written. The same content refuses on every retry. | Remove the matched junk from the file, or switch `content_sanity.junk_disposition` back to `quarantine` (a user decision), then import it again. | agent | `repeat the read that failed` | 1 | no |
+### core_budget_exceeded
+
+<a id="core_budget_exceeded"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The write would push always-loaded core memory over its brain-wide character budget or page limit. | Core pages enter every session's prompt in every harness, so their total size is capped on the write path. | Correct the request using the message above, then retry. Run: gbrain core status --json | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/core-memory.md#budget](../../docs/guides/core-memory.md#budget)
+
+### core_delete_owner_only
+
+<a id="core_delete_owner_only"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A remote caller tried to delete an always-loaded core page; only the owner can remove pages from core. | The step needs the user's decision before it runs. | Stop and ask the user; re-run only with the authorization the message names. | user | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/core-memory.md#owner-only](../../docs/guides/core-memory.md#owner-only)
+
+### core_mark_owner_only
+
+<a id="core_mark_owner_only"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A remote caller tried to change always_load or core_priority; only the owner designates core pages. | The step needs the user's decision before it runs. | Stop and ask the user; re-run only with the authorization the message names. | user | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/core-memory.md#owner-only](../../docs/guides/core-memory.md#owner-only)
+
+### core_remote_edit_refused
+
+<a id="core_remote_edit_refused"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Remote edits to always-loaded core pages are refused by memory.core.remote_edit. | The step needs the user's decision before it runs. | Stop and ask the user; re-run only with the authorization the message names. | user | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/core-memory.md#remote-edits](../../docs/guides/core-memory.md#remote-edits)
+
### cost_cap_exceeded
<a id="cost_cap_exceeded"></a>
diff --git a/scripts/build-schema.ts b/scripts/build-schema.ts
index c5011158c1..2f530dd0db 100644
--- a/scripts/build-schema.ts
+++ b/scripts/build-schema.ts
@@ -39,6 +39,7 @@ import { WORKTREE_REFRESH_SCHEMA_SQL } from '../src/core/persistence/worktree-re
import { SHARED_SKILLS_SCHEMA_SQL } from '../src/core/shared-skills/schema-all.ts';
import { DECIDE_SCHEMA_SQL } from '../src/core/ai/decide/schema.ts';
import { FACT_RELINK_SCHEMA_SQL } from '../src/core/facts/relink-schema.ts';
+import { CORE_EDIT_NOTICES_SCHEMA_SQL } from '../src/core/core-memory-schema.ts';
const REPO = resolve(import.meta.dir, '..');
export const SCHEMA_SQL_PATH = 'src/schema.sql';
@@ -95,6 +96,7 @@ export const FRAGMENTS: readonly Fragment[] = [
{ source: 'src/core/shared-skills/schema-all.ts', expr: 'SHARED_SKILLS_SCHEMA_SQL', postgres: SHARED_SKILLS_SCHEMA_SQL, pglite: SHARED_SKILLS_SCHEMA_SQL },
{ source: 'src/core/ai/decide/schema.ts', expr: 'DECIDE_SCHEMA_SQL', postgres: DECIDE_SCHEMA_SQL, pglite: DECIDE_SCHEMA_SQL },
{ source: 'src/core/facts/relink-schema.ts', expr: 'FACT_RELINK_SCHEMA_SQL', postgres: FACT_RELINK_SCHEMA_SQL, pglite: FACT_RELINK_SCHEMA_SQL },
+ { source: 'src/core/core-memory-schema.ts', expr: 'CORE_EDIT_NOTICES_SCHEMA_SQL', postgres: CORE_EDIT_NOTICES_SCHEMA_SQL, pglite: CORE_EDIT_NOTICES_SCHEMA_SQL },
];
const fragmentLabel = (f: Fragment) => `${f.source} (${f.expr})`;
diff --git a/src/core/core-memory-schema.ts b/src/core/core-memory-schema.ts
new file mode 100644
index 0000000000..8241b58072
--- /dev/null
+++ b/src/core/core-memory-schema.ts
@@ -0,0 +1,31 @@
+/**
+ * Core memory storage DDL: one canonical copy used by the schema migration
+ * and, through scripts/build-schema.ts FRAGMENTS, by fresh-install DDL.
+ *
+ * core_edit_notices records each remote edit to an always-loaded core page
+ * (memory.core.remote_edit = notify). The rendered core block shows pending
+ * rows until the owner acknowledges them up to a reviewed revision with
+ * `gbrain core ack <slug> --revision <token>`. No foreign key to pages: a
+ * notice outlives a rename (page_id) and is closed when the page is
+ * un-cored or deleted.
+ */
+
+export const CORE_EDIT_NOTICES_SCHEMA_SQL = `
+CREATE TABLE IF NOT EXISTS core_edit_notices (
+ id BIGSERIAL PRIMARY KEY,
+ source_id TEXT NOT NULL,
+ slug TEXT NOT NULL,
+ page_id BIGINT,
+ revision TEXT,
+ base_revision TEXT,
+ actor TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ acked_at TIMESTAMPTZ
+);
+CREATE INDEX IF NOT EXISTS core_edit_notices_pending_idx ON core_edit_notices (source_id, slug, id) WHERE acked_at IS NULL;
+DO $rls$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ ALTER TABLE core_edit_notices ENABLE ROW LEVEL SECURITY;
+ END IF;
+END $rls$;
+`;
diff --git a/src/core/core-memory.ts b/src/core/core-memory.ts
new file mode 100644
index 0000000000..88b112cdda
--- /dev/null
+++ b/src/core/core-memory.ts
@@ -0,0 +1,288 @@
+/**
+ * Always-loaded core memory tier.
+ *
+ * The owner designates a few pages as core with frontmatter
+ * `always_load: true` (optional `core_priority`, lower renders first). Core
+ * pages are rendered into every session's prompt through the lanes gbrain
+ * already reaches (session-start hooks, the OpenClaw assemble block,
+ * compiled instruction files, and the `context_pack` verb), under one
+ * brain-wide character budget that the write path enforces
+ * (src/core/persistence/core-guard.ts).
+ *
+ * Everything here is deterministic and zero-LLM. The rendered unit is the
+ * page title plus its compiled truth (never the timeline), in the same
+ * remote-safe view `get_page` gives an untrusted caller, so budget
+ * accounting and delivery always agree.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from './engine.ts';
+import { sanitizeRemoteBody } from './remote-body.ts';
+import { privatePagesFilterFragment } from './search/private-visibility.ts';
+
+export const CORE_DEFAULT_MAX_CHARS = 4000;
+export const CORE_MIN_MAX_CHARS = 500;
+export const CORE_MAX_MAX_CHARS = 6000;
+export const CORE_MAX_PAGES = 50;
+export const CORE_DEFAULT_PRIORITY = 100;
+/** Bumped whenever the rendered shape of a core page changes. */
+export const CORE_RENDER_VERSION = 1;
+export const CORE_DOCS = 'docs/guides/core-memory.md';
+
+export const CORE_CONFIG_KEYS = {
+ enabled: 'memory.core.enabled',
+ maxChars: 'memory.core.max_chars',
+ remoteEdit: 'memory.core.remote_edit',
+} as const;
+
+export type CoreRemoteEditMode = 'allow' | 'notify' | 'refuse';
+
+/** `always_load: true` is the on-disk spelling of "core"; every other value is not core. */
+export function isCoreFrontmatter(frontmatter: unknown): boolean {
+ return !!frontmatter && typeof frontmatter === 'object' && (frontmatter as Record<string, unknown>).always_load === true;
+}
+
+/** `core_priority` when it is a positive integer, else the default. */
+export function corePriority(frontmatter: unknown): number {
+ const raw = frontmatter && typeof frontmatter === 'object' ? (frontmatter as Record<string, unknown>).core_priority : undefined;
+ const n = typeof raw === 'string' && /^\d+$/.test(raw.trim()) ? Number(raw.trim()) : raw;
+ return typeof n === 'number' && Number.isInteger(n) && n > 0 ? n : CORE_DEFAULT_PRIORITY;
+}
+
+/** The two owner-only keys, normalized, for change detection. */
+export function coreMarking(frontmatter: unknown): { core: boolean; priority: number | null } {
+ const fm = frontmatter && typeof frontmatter === 'object' ? frontmatter as Record<string, unknown> : {};
+ return { core: isCoreFrontmatter(fm), priority: fm.core_priority === undefined ? null : corePriority(fm) };
+}
+
+export function parseCoreMaxChars(raw: string | null | undefined): number | null {
+ if (raw === null || raw === undefined || raw.trim() === '') return null;
+ const n = Number(raw.trim());
+ return Number.isInteger(n) && n >= CORE_MIN_MAX_CHARS && n <= CORE_MAX_MAX_CHARS ? n : null;
+}
+
+export function parseCoreRemoteEdit(raw: string | null | undefined): CoreRemoteEditMode | null {
+ const v = raw?.trim().toLowerCase();
+ return v === 'allow' || v === 'notify' || v === 'refuse' ? v : null;
+}
+
+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;
+}
+
+/** Validation for `gbrain config set` on the core keys; null when valid. */
+export function validateCoreConfigValue(key: string, value: string): string | null {
+ if (key === CORE_CONFIG_KEYS.maxChars && parseCoreMaxChars(value) === null) {
+ return `${key} must be an integer from ${CORE_MIN_MAX_CHARS} to ${CORE_MAX_MAX_CHARS} (default ${CORE_DEFAULT_MAX_CHARS}).`;
+ }
+ if (key === CORE_CONFIG_KEYS.remoteEdit && parseCoreRemoteEdit(value) === null) return `${key} must be allow, notify or refuse (default notify).`;
+ if (key === CORE_CONFIG_KEYS.enabled && parseBool(value) === null) return `${key} must be true or false (default true).`;
+ return null;
+}
+
+export interface CoreSettings { enabled: boolean; maxChars: number; remoteEdit: CoreRemoteEditMode }
+
+/** DB-plane settings; an out-of-range stored value falls back to the default (doctor names it). */
+export async function readCoreSettings(engine: Pick<BrainEngine, 'getConfig'>): Promise<CoreSettings> {
+ const [enabled, max, remote] = await Promise.all([
+ engine.getConfig(CORE_CONFIG_KEYS.enabled).catch(() => null),
+ engine.getConfig(CORE_CONFIG_KEYS.maxChars).catch(() => null),
+ engine.getConfig(CORE_CONFIG_KEYS.remoteEdit).catch(() => null),
+ ]);
+ return {
+ enabled: parseBool(enabled) ?? true,
+ maxChars: parseCoreMaxChars(max) ?? CORE_DEFAULT_MAX_CHARS,
+ remoteEdit: parseCoreRemoteEdit(remote) ?? 'notify',
+ };
+}
+
+export interface CorePageInput {
+ source_id: string;
+ slug: string;
+ title: string;
+ compiled_truth: string;
+ frontmatter?: unknown;
+ revision?: string | null;
+}
+
+export interface CorePage extends CorePageInput { priority: number; rendered: string; chars: number }
+
+/** The rendered unit: title header plus the remote-safe compiled truth. */
+export function renderCorePage(page: CorePageInput): string {
+ const body = sanitizeRemoteBody(page.compiled_truth ?? '').trim();
+ const title = (page.title || page.slug).replace(/\s+/g, ' ').trim();
+ return `### ${title} (${page.source_id}:${page.slug})${body ? `\n${body}` : ''}`;
+}
+
+export function toCorePage(page: CorePageInput): CorePage {
+ const rendered = renderCorePage(page);
+ return { ...page, priority: corePriority(page.frontmatter), rendered, chars: rendered.length };
+}
+
+/** Total budgeted characters: rendered pages joined by blank lines. */
+export function coreChars(pages: readonly Pick<CorePage, 'chars'>[]): number {
+ return pages.reduce((sum, p, i) => sum + p.chars + (i > 0 ? 2 : 0), 0);
+}
+
+/** Session order: `default` first, then other sources; within a source by priority then slug. */
+export function orderCorePages<T extends Pick<CorePage, 'source_id' | 'slug' | 'priority'>>(pages: readonly T[]): T[] {
+ return [...pages].sort((a, b) => (a.source_id === 'default' ? 0 : 1) - (b.source_id === 'default' ? 0 : 1)
+ || a.source_id.localeCompare(b.source_id) || a.priority - b.priority || a.slug.localeCompare(b.slug));
+}
+
+export interface CoreBlock {
+ text: string;
+ chars_used: number;
+ chars_limit: number;
+ pages: Array<{ source_id: string; slug: string; title: string; chars: number }>;
+ truncated: boolean;
+ omitted: Array<{ source_id: string; slug: string; reason: 'budget' | 'page_limit' | 'withheld' }>;
+ revision: string;
+}
+
+export const CORE_BLOCK_FOOTER = 'Owner-designated pages, loaded in every session. Edit with edit_page (exact text, expected_revision) and keep them lean: detail belongs in linked pages. Only the owner adds or removes core pages (gbrain core add|remove).';
+
+/** sha256 over the rendered pages and the limit, so any visible change moves it. */
+export function coreRevision(pages: readonly Pick<CorePage, 'source_id' | 'slug' | 'rendered' | 'priority'>[], maxChars: number): string {
+ const h = createHash('sha256');
+ h.update(`v${CORE_RENDER_VERSION}|${maxChars}`);
+ for (const p of orderCorePages(pages)) h.update(`\n${p.source_id}\u0000${p.slug}\u0000${p.priority}\u0000${p.rendered}`);
+ return h.digest('hex').slice(0, 16);
+}
+
+export interface RenderCoreBlockOpts {
+ maxChars: number;
+ /** Extra lines shown under the header (remote-edit notices); not budgeted, capped at 5 + a count. */
+ notices?: string[];
+ /** Pages withheld by the delivery lane's sensitivity policy (slug + family; never text). */
+ withheld?: Array<{ source_id: string; slug: string; family: string }>;
+}
+
+const MAX_NOTICE_LINES = 5;
+
+/**
+ * Render the injected block. Pages past the budget or the page cap are cut
+ * whole, lowest priority first, with a visible truncation line; a page is
+ * never sliced mid-text. Empty input renders as the empty string.
+ */
+export function renderCoreBlock(input: readonly CorePage[], opts: RenderCoreBlockOpts): CoreBlock {
+ const ordered = orderCorePages(input);
+ const kept: CorePage[] = [];
+ const omitted: CoreBlock['omitted'] = [];
+ let used = 0;
+ for (const page of ordered) {
+ if (kept.length >= CORE_MAX_PAGES) { omitted.push({ source_id: page.source_id, slug: page.slug, reason: 'page_limit' }); continue; }
+ const next = used + page.chars + (kept.length ? 2 : 0);
+ if (next > opts.maxChars) { omitted.push({ source_id: page.source_id, slug: page.slug, reason: 'budget' }); continue; }
+ kept.push(page);
+ used = next;
+ }
+ for (const w of opts.withheld ?? []) omitted.push({ source_id: w.source_id, slug: w.slug, reason: 'withheld' });
+ const revision = coreRevision(ordered, opts.maxChars);
+ if (kept.length === 0 && omitted.length === 0) {
+ return { text: '', chars_used: 0, chars_limit: opts.maxChars, pages: [], truncated: false, omitted, revision };
+ }
+ const lines: string[] = [`## Core memory (always loaded) — ${used.toLocaleString('en-US')}/${opts.maxChars.toLocaleString('en-US')} chars`];
+ const notices = opts.notices ?? [];
+ for (const n of notices.slice(0, MAX_NOTICE_LINES)) lines.push(`> ${n}`);
+ if (notices.length > MAX_NOTICE_LINES) lines.push(`> +${notices.length - MAX_NOTICE_LINES} more remote edits; review with gbrain core diff`);
+ for (const w of opts.withheld ?? []) lines.push(`[core page ${w.source_id}:${w.slug} withheld: ${w.family}; run gbrain core status]`);
+ const overBudget = omitted.filter(o => o.reason !== 'withheld');
+ if (overBudget.length) {
+ lines.push(`[core truncated: ${overBudget.length} page(s) over the ${opts.maxChars}-char budget or page cap left out; run gbrain core status]`);
+ }
+ const body = kept.map(p => p.rendered).join('\n\n');
+ const text = `${lines.join('\n')}\n\n${body}${body ? '\n\n' : ''}${CORE_BLOCK_FOOTER}`;
+ return {
+ text, chars_used: used, chars_limit: opts.maxChars,
+ pages: kept.map(p => ({ source_id: p.source_id, slug: p.slug, title: p.title, chars: p.chars })),
+ truncated: overBudget.length > 0, omitted, revision,
+ };
+}
+
+type RawExec = Pick<BrainEngine, 'executeRaw' | 'readPageSnapshot'>;
+
+export interface ListCorePagesOpts {
+ /** Restrict to these sources; omitted = every source in the brain. */
+ sourceIds?: readonly string[];
+ excludePrivate?: boolean;
+ /** Exclude one page (the page being written, measured separately). */
+ exclude?: { sourceId: string; slug: string };
+}
+
+interface CoreRow { source_id: string; slug: string; title: string | null; compiled_truth: string | null; frontmatter: unknown; withdrawn: boolean }
+
+/**
+ * Live core pages. Bounded: the partial index `idx_pages_always_load`
+ * serves the filter, and the cap leaves headroom over CORE_MAX_PAGES so the
+ * renderer can still report what it left out.
+ */
+export async function listCorePages(exec: RawExec, opts: ListCorePagesOpts = {}): Promise<CorePage[]> {
+ const params: unknown[] = [];
+ const where = [`p.deleted_at IS NULL`, `p.frontmatter @> '{"always_load": true}'::jsonb`];
+ if (opts.sourceIds) {
+ params.push([...opts.sourceIds]);
+ where.push(`p.source_id = ANY($${params.length}::text[])`);
+ }
+ if (opts.exclude) {
+ params.push(opts.exclude.sourceId, opts.exclude.slug);
+ where.push(`NOT (p.source_id = $${params.length - 1} AND p.slug = $${params.length})`);
+ }
+ if (opts.excludePrivate) where.push(privatePagesFilterFragment('p'));
+ const rows = await exec.executeRaw<CoreRow>(
+ `SELECT p.source_id, p.slug, p.title, p.compiled_truth, p.frontmatter,
+ EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id = p.source_id AND (w.subject = '*' OR w.subject = p.slug)) AS withdrawn
+ FROM pages p WHERE ${where.join(' AND ')} ORDER BY p.source_id, p.slug LIMIT ${CORE_MAX_PAGES * 4}`, params);
+ const pages: CorePage[] = [];
+ for (const r of rows) {
+ let compiled = r.compiled_truth ?? '';
+ // Withdrawn facts (forget) are applied by the canonical snapshot read,
+ // not by the stored body, so core never shows text get_page withholds.
+ if (r.withdrawn) {
+ const snap = await exec.readPageSnapshot(r.slug, { sourceId: r.source_id, ...(opts.excludePrivate ? { excludePrivate: true } : {}) });
+ if (!snap) continue;
+ compiled = snap.page.compiled_truth ?? '';
+ }
+ pages.push(toCorePage({
+ source_id: r.source_id, slug: r.slug, title: r.title ?? r.slug, compiled_truth: compiled,
+ frontmatter: typeof r.frontmatter === 'string' ? JSON.parse(r.frontmatter) : r.frontmatter,
+ }));
+ }
+ return pages;
+}
+
+/** The sources a session sees: `default` plus the session source. */
+export function sessionCoreSources(sessionSourceId: string | null | undefined, allowed?: readonly string[] | null): string[] {
+ const wanted = [...new Set(['default', sessionSourceId || 'default'])];
+ return allowed ? wanted.filter(s => allowed.includes(s)) : wanted;
+}
+
+export interface LoadCoreBlockOpts {
+ sessionSourceId?: string | null;
+ /** Federated grant; when set, only these sources render. */
+ allowedSources?: readonly string[] | null;
+ excludePrivate?: boolean;
+ notices?: string[];
+ settings?: CoreSettings;
+}
+
+/** The block a session receives; empty text when core is disabled or empty. */
+export async function loadCoreBlock(engine: Pick<BrainEngine, 'executeRaw' | 'readPageSnapshot' | 'getConfig'>, opts: LoadCoreBlockOpts = {}): Promise<CoreBlock & { enabled: boolean }> {
+ const settings = opts.settings ?? await readCoreSettings(engine);
+ if (!settings.enabled) {
+ return { text: '', chars_used: 0, chars_limit: settings.maxChars, pages: [], truncated: false, omitted: [], revision: 'disabled', enabled: false };
+ }
+ const pages = await listCorePages(engine, {
+ sourceIds: sessionCoreSources(opts.sessionSourceId, opts.allowedSources ?? null),
+ excludePrivate: opts.excludePrivate ?? true,
+ });
+ return { ...renderCoreBlock(pages, { maxChars: settings.maxChars, notices: opts.notices }), enabled: true };
+}
+
+/** Brain-wide accounting used by the write-path guard and `gbrain core status`. */
+export async function coreUsage(exec: RawExec, opts: { exclude?: { sourceId: string; slug: string } } = {}): Promise<{ pages: CorePage[]; chars: number }> {
+ const pages = orderCorePages(await listCorePages(exec, { exclude: opts.exclude }));
+ return { pages, chars: coreChars(pages) };
+}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 1ff419a60e..b3a52a9d00 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -101,6 +101,10 @@ export const CODES = {
connector_intent_outdated: { class: 'caller', summary: "The connector request no longer matches the stored connector intent." },
consent_timeout: { class: 'consent', summary: "Google connect credential error: consent timeout.", docs: 'docs/guides/google-connect.md#troubleshooting' },
content_rejected: { class: 'caller', summary: "The content-sanity gate rejected the content because the operator set `content_sanity.junk_disposition` to `reject`.", why: "A junk-pattern or operator-literal hit is refused instead of quarantined under that setting, so the page was not written. The same content refuses on every retry.", suggestion: 'Remove the matched junk from the file, or switch `content_sanity.junk_disposition` back to `quarantine` (a user decision), then import it again.' },
+ core_budget_exceeded: { class: 'caller', summary: "The write would push always-loaded core memory over its brain-wide character budget or page limit.", why: "Core pages enter every session's prompt in every harness, so their total size is capped on the write path.", docs: 'docs/guides/core-memory.md#budget', fix: { argv: ['gbrain', 'core', 'status', '--json'], consent: [], actor: 'agent', why: "Shows core usage against the budget and the largest core pages, read-only.", requires_exclusive: false } },
+ core_delete_owner_only: { class: 'consent', summary: "A remote caller tried to delete an always-loaded core page; only the owner can remove pages from core.", docs: 'docs/guides/core-memory.md#owner-only', actor: 'user' },
+ core_mark_owner_only: { class: 'consent', summary: "A remote caller tried to change always_load or core_priority; only the owner designates core pages.", docs: 'docs/guides/core-memory.md#owner-only', actor: 'user' },
+ core_remote_edit_refused: { class: 'consent', summary: "Remote edits to always-loaded core pages are refused by memory.core.remote_edit.", docs: 'docs/guides/core-memory.md#remote-edits', actor: 'user' },
cost_cap_exceeded: { class: 'server', summary: "The run reached its cost cap before finishing." },
cost_preview_requires_yes: { class: 'consent', summary: "Cost preview requires yes." },
cycle_failed: { class: 'server', summary: "The maintenance (dream) cycle failed, or a phase threw and was contained so later phases could run." },
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 930258c21e..a10e4ff1a4 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -16,6 +16,7 @@ import { clearResolvedRecovery, completeWrite, getWriteRequestById, lockCounters
import { isTerminal, principalKey, requestPrincipal, recoveryFiles, type RecoveryRecord, type WriteRequest } from './model.ts';
import type { NativeLockHandle } from './native-lock.ts';
import { withCoordinatedWrite } from './context.ts';
+import { lockCoreSources } from './core-guard.ts';
import { requestAttribution } from './attribution.ts';
import { withFilesystemPublication } from './filesystem-guard.ts';
import { mayReprepare } from './semantic.ts';
@@ -33,6 +34,8 @@ import { databaseRefusal, withAttempt, type PublicationFailure, type Publication
interface PreparedMutationBase {
sourceExclusive?: boolean;
+ /** Always-loaded core writes: source rows locked FOR UPDATE in id order (core-guard.ts lockCoreSources). */
+ exclusiveSources?: readonly string[];
observedRevision: string | null;
additionalPageKeys?: readonly {sourceId:string;slug:string}[];
noop?: boolean;
@@ -242,7 +245,8 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
await declarePersistenceProtocol(tx);
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
const liveBinding = await guardOwnership(tx, row, hostId);
- if (prepared.sourceExclusive) await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [row.source_id]);
+ if (prepared.sourceExclusive && !prepared.exclusiveSources?.length) await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [row.source_id]);
+ if (prepared.exclusiveSources?.length) await lockCoreSources(tx, prepared.sourceExclusive ? [row.source_id, ...prepared.exclusiveSources] : prepared.exclusiveSources);
if (binding && String(liveBinding?.owner_epoch) !== String(binding.owner_epoch)) throw opError('owner_unavailable', 'Owner epoch changed before publication.',
`Source ${row.source_id}'s canonical owner changed (a transfer or re-claim) after request ${row.request_id} was prepared, so this host published nothing for it. Inspect the owner and the request before resubmitting; do not claim or transfer the source to push this write through.`,
{ fix: ownerStatusFix(row.source_id) });
diff --git a/src/core/persistence/core-guard.ts b/src/core/persistence/core-guard.ts
new file mode 100644
index 0000000000..5af2ce402c
--- /dev/null
+++ b/src/core/persistence/core-guard.ts
@@ -0,0 +1,179 @@
+/**
+ * Write-path guard for the always-loaded core tier (src/core/core-memory.ts).
+ *
+ * Every page mutation that touches a core page (before or after the write)
+ * passes through here: owner-only marking, the brain-wide character budget,
+ * the remote-edit policy and its notices. Zero LLM.
+ *
+ * Two steps:
+ * - `prepareCoreGuard` runs at prepare time against the snapshot and the
+ * parsed incoming page. It refuses deterministic violations early and
+ * returns a plan (or null when no core page is involved).
+ * - The plan's `validate` re-runs the budget inside the publish transaction,
+ * after `lockCoreSources` serialized every core writer, so concurrent core
+ * writes can never pass the limit together.
+ *
+ * Lock order (`lockCoreSources`): the coordinator calls it in its
+ * source-exclusive slot, which runs after the worktree native lock and the
+ * `persistence_worktrees` FOR SHARE ownership check, and before
+ * `authorizeStoredRequest` (source FOR SHARE) and `lockCounters`. Rows are
+ * locked FOR UPDATE in id order, the same order topology and deactivation
+ * locks use, so every path takes worktree row → source rows (id order) →
+ * counters, and no core write holds a counter while waiting on a source.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Page } from '../types.ts';
+import type { Action } from '../agent-output.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import {
+ CORE_DOCS, CORE_MAX_PAGES, coreChars, coreMarking, coreUsage, listCorePages, readCoreSettings, renderCorePage, type CoreSettings,
+} from '../core-memory.ts';
+import type { WriteRequest } from './model.ts';
+
+/** Source rows a core-touching write locks: its own source and `default` (the brain-wide core lock). */
+export function coreLockSources(sourceId: string): string[] {
+ return [...new Set([sourceId, 'default'])].sort();
+}
+
+/**
+ * The one lock function for core writers. Takes the listed `sources` rows
+ * FOR UPDATE in id order inside the publish transaction (transaction-scoped,
+ * PgBouncer-safe). See the module comment for the global order.
+ */
+export async function lockCoreSources(tx: Pick<BrainEngine, 'executeRaw'>, sourceIds: readonly string[]): Promise<void> {
+ const ids = [...new Set(sourceIds)].sort();
+ if (!ids.length) return;
+ await tx.executeRaw('SELECT id FROM sources WHERE id = ANY($1::text[]) ORDER BY id FOR UPDATE', [ids]);
+}
+
+function ownerFix(row: WriteRequest, argv: string[], why: string): Action {
+ return row.authority.remote
+ ? { argv, consent: [], actor: 'user', why, requires_exclusive: false, docs: `${CORE_DOCS}#owner-only`,
+ user_message: 'Only the brain owner can change which pages are always loaded. Please run the command shown in a terminal on the brain host.' }
+ : { argv, consent: [], actor: 'agent', why, requires_exclusive: false, docs: `${CORE_DOCS}#owner-only` };
+}
+
+const statusFix = (): Action => readFix('Shows core usage against the budget, the largest core pages and what each lane delivers, read-only.',
+ { argv: ['gbrain', 'core', 'status', '--json'] });
+
+export interface CoreGuardInput {
+ row: WriteRequest;
+ snapshot: PageSnapshot | null;
+ /** Parsed incoming page (title, compiled_truth, frontmatter); null when the write deletes the page. */
+ incoming: Pick<Page, 'title' | 'compiled_truth' | 'frontmatter'> | null;
+ settings?: CoreSettings;
+}
+
+export interface CoreGuardPlan {
+ exclusiveSources: string[];
+ afterChars: number;
+ beforeChars: number;
+ /** Brain-wide core chars after this write, from the latest check. */
+ usage(): { chars_used: number; chars_limit: number; page_chars: number } | null;
+ /** Re-checks the budget against in-transaction state; call after `lockCoreSources`. */
+ validate(tx: BrainEngine): Promise<void>;
+ /** Records a remote-edit notice in the publish transaction when the policy is `notify`. */
+ record(tx: Pick<BrainEngine, 'executeRaw'>, revision: string | null): Promise<void>;
+}
+
+/** The incoming core marking for a remote write that omitted the keys: carried from the snapshot. */
+export function carryCoreMarking(snapshotFrontmatter: unknown, incoming: Record<string, unknown>): Record<string, unknown> {
+ const before = (snapshotFrontmatter && typeof snapshotFrontmatter === 'object' ? snapshotFrontmatter : {}) as Record<string, unknown>;
+ const out = { ...incoming };
+ if (out.always_load === undefined && before.always_load !== undefined) out.always_load = before.always_load;
+ if (out.core_priority === undefined && before.core_priority !== undefined) out.core_priority = before.core_priority;
+ return out;
+}
+
+function budgetError(row: WriteRequest, used: number, limit: number, pageChars: number, others: Array<{ source_id: string; slug: string; chars: number }>, hiddenChars: number): Error {
+ const over = used - limit;
+ const largest = others.slice().sort((a, b) => b.chars - a.chars).slice(0, 3).map(p => `${p.source_id}:${p.slug} (${p.chars})`);
+ const otherLine = largest.length ? ` Largest other core pages you can see: ${largest.join(', ')}.` : '';
+ const hiddenLine = hiddenChars > 0 ? ` Core pages in sources you cannot read use ${hiddenChars} chars.` : '';
+ // The write journal keeps only code + message for asynchronous refusals, so the message carries every number.
+ const e = opError('core_budget_exceeded',
+ `This write would make always-loaded core memory ${used} chars, over the ${limit}-char budget by ${over} (page ${row.source_id}:${row.slug} renders at ${pageChars}). Shorten it by at least ${over} chars: move detail into a linked non-core page and keep a one-line pointer.${otherLine}${hiddenLine}`,
+ `Page ${row.source_id}:${row.slug} would render at ${pageChars} chars. Nothing was written. Shorten it by at least ${over} chars: move detail into a linked non-core page and keep a one-line pointer here, then submit the shorter content with a new request_id.${otherLine}${hiddenLine} Shrinking writes always pass; the owner can raise memory.core.max_chars (up to 6000).`,
+ { fix: statusFix(), docs: `${CORE_DOCS}#budget` });
+ e.detail = `chars_used=${used} chars_limit=${limit} page_chars=${pageChars} over_by=${over}`;
+ return e;
+}
+
+/**
+ * Prepare-time guard. Returns null when neither the stored nor the incoming
+ * page is core. Throws the owner-only, remote-edit and budget refusals.
+ */
+export async function prepareCoreGuard(engine: BrainEngine, input: CoreGuardInput): Promise<CoreGuardPlan | null> {
+ const { row, snapshot, incoming } = input;
+ const live = snapshot && !snapshot.page.deleted_at ? snapshot : null;
+ const before = live ? coreMarking(live.page.frontmatter) : { core: false, priority: null };
+ const after = incoming ? coreMarking(incoming.frontmatter) : { core: false, priority: null };
+ if (!before.core && !after.core) return null;
+ const remote = row.authority.remote;
+
+ if (remote && (before.core !== after.core || before.priority !== after.priority)) {
+ if (!incoming && before.core) {
+ throw opError('core_delete_owner_only', `Page ${row.source_id}:${row.slug} is always-loaded core memory, so a remote caller cannot delete it. Ask the user to run: gbrain core remove --source ${row.source_id} ${row.slug}`,
+ 'Nothing was deleted. Ask the user to remove it from core first (command in fix), then delete it.',
+ { fix: ownerFix(row, ['gbrain', 'core', 'remove', '--source', row.source_id, row.slug], 'Removes the page from always-loaded core memory on the brain host.') });
+ }
+ const argv = after.core && !before.core
+ ? ['gbrain', 'core', 'add', '--source', row.source_id, row.slug]
+ : before.core && !after.core ? ['gbrain', 'core', 'remove', '--source', row.source_id, row.slug]
+ : ['gbrain', 'core', 'add', '--source', row.source_id, row.slug, '--priority', String(after.priority ?? before.priority ?? 100)];
+ throw opError('core_mark_owner_only', `Only the brain owner can change always_load or core_priority on ${row.source_id}:${row.slug}. Resubmit without changing them (omitted keys keep their stored values); if the core marking should change, ask the user to run: ${argv.join(' ')}`,
+ 'Nothing was written. Submit the content without changing always_load or core_priority (omitted keys keep their stored values), and ask the user to run the command in fix if the core marking itself should change.',
+ { fix: ownerFix(row, argv, 'Changes which pages are always loaded, from the trusted local CLI.') });
+ }
+
+ const settings = input.settings ?? await readCoreSettings(engine);
+ const afterRendered = incoming && after.core ? renderCorePage({ source_id: row.source_id, slug: row.slug, title: incoming.title, compiled_truth: incoming.compiled_truth }) : '';
+ const beforeRendered = live && before.core ? renderCorePage({ source_id: row.source_id, slug: row.slug, title: live.page.title, compiled_truth: live.page.compiled_truth }) : '';
+ const contentChanged = afterRendered !== beforeRendered;
+
+ if (remote && before.core && contentChanged && settings.remoteEdit === 'refuse') {
+ throw opError('core_remote_edit_refused', `Page ${row.source_id}:${row.slug} is always-loaded core memory and memory.core.remote_edit is refuse. Ask the user to make this edit on the brain host, or to run: gbrain config set memory.core.remote_edit notify`,
+ 'Nothing was written. Ask the user to make this edit from the brain host, or to allow remote edits with notices (command in fix).',
+ { fix: ownerFix(row, ['gbrain', 'config', 'set', 'memory.core.remote_edit', 'notify'], 'Lets agents edit core pages; each remote edit then shows a review notice in the core block.') });
+ }
+
+ const afterChars = afterRendered.length;
+ const beforeChars = beforeRendered.length;
+ let lastTotal: number | null = null;
+ const check = async (exec: BrainEngine) => {
+ if (!after.core) return;
+ const { pages } = await coreUsage(exec, { exclude: { sourceId: row.source_id, slug: row.slug } });
+ if (pages.length + 1 > CORE_MAX_PAGES && !before.core) {
+ throw opError('core_budget_exceeded', `Always-loaded core memory already has ${pages.length} pages; the limit is ${CORE_MAX_PAGES}. Remove a core page first (gbrain core remove) or keep ${row.source_id}:${row.slug} out of core.`,
+ `Nothing was written. Remove a core page first (gbrain core remove), or keep ${row.source_id}:${row.slug} out of core.`,
+ { fix: statusFix(), docs: `${CORE_DOCS}#budget` });
+ }
+ const total = coreChars([...pages, { chars: afterChars }]);
+ lastTotal = total;
+ const grew = !before.core || afterChars > beforeChars;
+ if (total > settings.maxChars && grew) {
+ // Remote diagnostics never name pages outside the write's own source or private pages.
+ const seen = remote
+ ? await listCorePages(exec, { sourceIds: [row.source_id], excludePrivate: true, exclude: { sourceId: row.source_id, slug: row.slug } })
+ : pages;
+ const hidden = pages.reduce((n, p) => n + p.chars, 0) - seen.reduce((n, p) => n + p.chars, 0);
+ throw budgetError(row, total, settings.maxChars, afterChars, seen, hidden);
+ }
+ };
+ await check(engine);
+
+ return {
+ exclusiveSources: coreLockSources(row.source_id),
+ afterChars, beforeChars,
+ usage: () => lastTotal === null ? null : { chars_used: lastTotal, chars_limit: settings.maxChars, page_chars: afterChars },
+ validate: tx => check(tx),
+ record: async (tx, revision) => {
+ if (!remote || !before.core || !contentChanged || settings.remoteEdit !== 'notify') return;
+ const actor = `${row.authority.principal.kind}:${row.authority.principal.id}`;
+ await tx.executeRaw(`INSERT INTO core_edit_notices (source_id, slug, page_id, revision, base_revision, actor) VALUES ($1, $2, $3, $4, $5, $6)`,
+ [row.source_id, row.slug, live?.page.id ?? null, revision, live?.revision ?? null, actor]);
+ },
+ };
+}
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 6a511010d1..8508156d91 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -39,7 +39,7 @@ import { decoratePublicationOutcome, finishUnpublishedFailure, publishMutation,
/** Whether a prepared member can share a group transaction. */
export function groupable(row: WriteRequest, prepared: PreparedMutation): boolean {
return row.operation === 'submit_job' && (row.intent?.kind === 'managed_sync_import' || row.intent?.kind === 'managed_sync_delete')
- && (row.target_kind ?? 'page') === 'page' && prepared.target !== 'skill_bundle' && !prepared.file && !prepared.sourceExclusive && typeof prepared.validate === 'function';
+ && (row.target_kind ?? 'page') === 'page' && prepared.target !== 'skill_bundle' && !prepared.file && !prepared.sourceExclusive && !prepared.exclusiveSources?.length && typeof prepared.validate === 'function';
}
/** Publishes the whole group or nothing; null means the transaction did not commit and the claims are untouched. */
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index 458dd9b5d9..921fccd370 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -107,7 +107,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
page = await preparePageMutation(engine, { ...row, intent: { ...p, content, expected_revision: observedRevision, force: false } }, config, undefined, signal);
if (page.observedRevision !== observedRevision) conflict(row);
}
- return { observedRevision, file: page?.file, validate: async tx => { await validate(tx); await page?.validate?.(tx); }, apply: async tx => {
+ return { observedRevision, file: page?.file, ...(page?.exclusiveSources ? { exclusiveSources: page.exclusiveSources } : {}), validate: async tx => { await validate(tx); await page?.validate?.(tx); }, apply: async tx => {
await page?.apply(tx);
let id: number;
if (rowNum !== undefined) {
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 3cdda8e792..017b02e4e6 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -45,6 +45,7 @@ import { DERIVE_PHASE_DB_ONLY_DEFAULTS } from '../storage-config.ts';
import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';
import { readSlugRootMode } from '../sync-anchor.ts';
import { applyPageEdits, editDiff, parsePageEdits } from './page-edit.ts';
+import { carryCoreMarking, prepareCoreGuard } from './core-guard.ts';
const PURGE_RESIDUALS = 'Brain-repo git history, synced working-tree copies, exports, compiled context files and slug-keyed derived rows (takes, open loops, file records) may still hold the content — rotate the credential and rewrite or regenerate those copies.';
@@ -255,6 +256,8 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
`Page ${row.slug} does not exist in source ${row.source_id}, so nothing was deleted. Check the slug and the source.`, pageFix(row.source_id, row.slug));
const purge = p.purge === true;
const noop = !purge && snapshot.page.deleted_at != null;
+ // Always-loaded core pages: a remote caller cannot delete one (owner-only).
+ if (!noop) await prepareCoreGuard(engine, { row, snapshot, incoming: null });
// Tombstones still own their recorded artifact. Purge always attempts its
// removal before the guarded hard-delete and receipt commit; failure rolls
// back to the prior row, and replay survives the eventual absence of that row.
@@ -304,6 +307,16 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
if (compiled_truth!==parsed.compiled_truth || timeline!==(parsed.timeline??'')) content=serializePageToMarkdown({
...(snapshot?.page??{id:0,source_id:row.source_id,created_at:new Date(),updated_at:new Date()}),...parsed,compiled_truth,timeline},parsed.tags);
}
+ // Core marking is owner-only: a remote write that omits always_load or
+ // core_priority keeps the stored values instead of silently un-coring the page.
+ if (row.authority.remote && snapshot && !snapshot.page.deleted_at && typeof content === 'string'
+ && (snapshot.page.frontmatter?.always_load !== undefined || snapshot.page.frontmatter?.core_priority !== undefined)) {
+ const parsed = parseMarkdown(content, row.slug, { activePack });
+ const carried = carryCoreMarking(snapshot.page.frontmatter, parsed.frontmatter ?? {});
+ if (carried.always_load !== parsed.frontmatter?.always_load || carried.core_priority !== parsed.frontmatter?.core_priority) {
+ content = serializePageToMarkdown({ ...snapshot.page, ...parsed, frontmatter: carried }, parsed.tags);
+ }
+ }
const projected = !(row.operation === 'remember' || row.operation.startsWith('takes_') || (row.operation === 'extract_facts' && p.kind === 'managed_facts_entity'));
const writer = (row.operation === 'put_page' || row.operation === 'edit_page') && p.kind !== 'managed_maintenance_page'
&& (preparedIntent !== undefined || typeof p.expected_revision === 'string') ? 'editing' : 'preserving';
@@ -391,7 +404,11 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
const sourcePath = file && mintMode ? scannerSourcePath(file.root, file.path, mintMode) : undefined;
// An inferred mode is pinned with the first origin it mints, so later pages cannot flip the inference (#5610).
const pinMode = sourcePath && mintMode && scannerSourcePath(file!.root, file!.root) && !await readSlugRootMode(engine, row.source_id) ? mintMode : undefined;
- return { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, ...await pageDatabaseOnlyPublication(engine, row, file), validate: ready.validate, apply: async tx => {
+ // Always-loaded core tier: owner-only marking, brain-wide budget, remote-edit policy (core-guard.ts).
+ const core = noop ? null : await prepareCoreGuard(engine, { row, snapshot, incoming: targetDeleted ? null : ready.parsedPage });
+ return { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, ...await pageDatabaseOnlyPublication(engine, row, file),
+ ...(core ? { exclusiveSources: core.exclusiveSources } : {}),
+ validate: core ? async tx => { await ready.validate?.(tx); await core.validate(tx); } : ready.validate, apply: async tx => {
let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;
if (!noop) {
await ready.apply(tx);
@@ -417,8 +434,10 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
if (targetDeleted) await tx.softDeletePage(row.slug, source);
// Index installation and terminal receipt share this transaction.
await sealPageTextProjection(tx, row.slug, row.source_id);
+ if (core) await core.record(tx, (await tx.readPageSnapshot(row.slug, source))?.revision ?? null);
}
- return { ...advisories, ...(autoLinks ? {auto_links:autoLinks} : {}),
+ const coreUsage = core?.usage();
+ return { ...advisories, ...(autoLinks ? {auto_links:autoLinks} : {}), ...(coreUsage ? { core: coreUsage } : {}),
status: noop ? 'skipped' : row.operation === 'restore_page' ? 'restored' : row.operation === 'revert_version' ? 'reverted' : 'created_or_updated',
slug: row.slug, source_id: row.source_id, chunks: ready.result.chunks, noop,
...(ready.result.chunks === 0 ? {chunk_skip_reason: noop ? 'write_skipped'
diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.ts
index aa7c89d416..6bbfa27df1 100644
--- a/src/core/persistence/types.ts
+++ b/src/core/persistence/types.ts
@@ -17,6 +17,7 @@ export const WRITE_ERROR_CODES = [
'skill_bundle_required', 'take_row_collision', 'invalid_source_uri', 'writer_admin_locked',
'connector_account_changed', 'connector_intent_outdated', 'checkpoint_validation_timeout',
'invalid_connector_text', 'connector_holds_exhausted', 'connector_fence_below_timeline',
+ 'core_budget_exceeded', 'core_mark_owner_only', 'core_remote_edit_refused', 'core_delete_owner_only',
] as const;
export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index e584e40a08..9994fee487 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -34,6 +34,9 @@ export function heldFileDiagnostic(message: string | null | undefined, sourceId
export function writeFailureDiagnostic(code: string, message?: string | null): { reason: string; message: string; suggestion: string } {
const held = code === 'source_changed' ? heldFileDiagnostic(message) : null;
if (held) return held;
+ // Always-loaded core refusals carry their numbers and the owner command in the message.
+ if (code.startsWith('core_') && message) return { reason: code, message,
+ suggestion: 'Change the content as the message says, or ask the user for the owner step it names (docs/guides/core-memory.md).' };
if (code === 'source_changed') {
if (message === 'The canonical file contains an uncoordinated local edit.') return {
reason: 'file_database_drift', message: 'The canonical file and database disagree. Neither copy was overwritten.',
@@ -113,7 +116,7 @@ export function frozenVerbWriteError(receipt: WriteReceipt, reason?: WriteErrorC
: receipt.state === 'conflict' ? 'revision_conflict'
: receipt.state === 'cancelled' ? 'cancelled' : 'storage_error');
const code = ['source_changed','permission_denied','scope_denied','writer_registration_required'].includes(writeError) ? 'scope_denied'
- : ['revision_required', 'revision_conflict', 'idempotency_conflict','invalid_params','page_identity_changed'].includes(writeError)
+ : ['revision_required', 'revision_conflict', 'idempotency_conflict','invalid_params','page_identity_changed'].includes(writeError) || writeError.startsWith('core_')
? 'invalid_params' : 'unavailable';
const diagnostic = writeFailureDiagnostic(writeError, message);
const suggestion = pending
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index f9af4910a2..56a2f756c1 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1826,6 +1826,25 @@ DO \$rls\$ BEGIN
END IF;
END \$rls\$;
+-- Always-loaded core memory: remote-edit notices.
+CREATE TABLE IF NOT EXISTS core_edit_notices (
+ id BIGSERIAL PRIMARY KEY,
+ source_id TEXT NOT NULL,
+ slug TEXT NOT NULL,
+ page_id BIGINT,
+ revision TEXT,
+ base_revision TEXT,
+ actor TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ acked_at TIMESTAMPTZ
+);
+CREATE INDEX IF NOT EXISTS core_edit_notices_pending_idx ON core_edit_notices (source_id, slug, id) WHERE acked_at IS NULL;
+DO \$rls\$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ ALTER TABLE core_edit_notices ENABLE ROW LEVEL SECURITY;
+ END IF;
+END \$rls\$;
+
`;
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 01044b0e99..ef1c12b97f 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -2547,6 +2547,27 @@ DO \$rls\$ BEGIN
END \$rls\$;
-- END GENERATED from src/core/facts/relink-schema.ts (FACT_RELINK_SCHEMA_SQL)
+-- Always-loaded core memory: remote-edit notices.
+-- BEGIN GENERATED from src/core/core-memory-schema.ts (CORE_EDIT_NOTICES_SCHEMA_SQL). Edit that file, then run: bun run build:schema
+CREATE TABLE IF NOT EXISTS core_edit_notices (
+ id BIGSERIAL PRIMARY KEY,
+ source_id TEXT NOT NULL,
+ slug TEXT NOT NULL,
+ page_id BIGINT,
+ revision TEXT,
+ base_revision TEXT,
+ actor TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ acked_at TIMESTAMPTZ
+);
+CREATE INDEX IF NOT EXISTS core_edit_notices_pending_idx ON core_edit_notices (source_id, slug, id) WHERE acked_at IS NULL;
+DO \$rls\$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ ALTER TABLE core_edit_notices ENABLE ROW LEVEL SECURITY;
+ END IF;
+END \$rls\$;
+-- END GENERATED from src/core/core-memory-schema.ts (CORE_EDIT_NOTICES_SCHEMA_SQL)
+
-- #5255/#5176 (O-DX-8): last upstream observation per source, recorded by sync
-- from the checkout's Git state (upstream ref, its last fetch/push time, commits
-- the synced commit lacks); doctor sync_freshness reads it with no subprocess.
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 16ef4d9ecc..2e45ce6a87 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -201,6 +201,7 @@ import { v197 } from './v197-managed-guard-null-source-fallback.ts';
import { v198 } from './v198-publication-failure-detail.ts';
import { v199 } from './v199-chronicle-page-state.ts';
import { v200 } from './v200-sync-hold-page-index.ts';
+import { v201 } from './v201-core-edit-notices.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -400,4 +401,5 @@ export const MIGRATIONS: Migration[] = [
v198,
v199,
v200,
+ v201,
];
diff --git a/src/core/schema-migrations/v201-core-edit-notices.ts b/src/core/schema-migrations/v201-core-edit-notices.ts
new file mode 100644
index 0000000000..4e225ebd91
--- /dev/null
+++ b/src/core/schema-migrations/v201-core-edit-notices.ts
@@ -0,0 +1,15 @@
+import type { Migration } from './types.ts';
+import { CORE_EDIT_NOTICES_SCHEMA_SQL } from '../core-memory-schema.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// Always-loaded core memory: remote edits to core pages are recorded here so
+// the owner sees and acknowledges them (src/core/persistence/core-guard.ts).
+// New empty table, so its index builds inline on both engines.
+export const v201: Migration = {
+ version: 201,
+ name: 'core_edit_notices',
+ idempotent: true,
+ sql: CORE_EDIT_NOTICES_SCHEMA_SQL,
+};
diff --git a/src/schema.sql b/src/schema.sql
index 43fed65c5e..353985ec4c 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -2543,6 +2543,27 @@ DO $rls$ BEGIN
END $rls$;
-- END GENERATED from src/core/facts/relink-schema.ts (FACT_RELINK_SCHEMA_SQL)
+-- Always-loaded core memory: remote-edit notices.
+-- BEGIN GENERATED from src/core/core-memory-schema.ts (CORE_EDIT_NOTICES_SCHEMA_SQL). Edit that file, then run: bun run build:schema
+CREATE TABLE IF NOT EXISTS core_edit_notices (
+ id BIGSERIAL PRIMARY KEY,
+ source_id TEXT NOT NULL,
+ slug TEXT NOT NULL,
+ page_id BIGINT,
+ revision TEXT,
+ base_revision TEXT,
+ actor TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ acked_at TIMESTAMPTZ
+);
+CREATE INDEX IF NOT EXISTS core_edit_notices_pending_idx ON core_edit_notices (source_id, slug, id) WHERE acked_at IS NULL;
+DO $rls$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
+ ALTER TABLE core_edit_notices ENABLE ROW LEVEL SECURITY;
+ END IF;
+END $rls$;
+-- END GENERATED from src/core/core-memory-schema.ts (CORE_EDIT_NOTICES_SCHEMA_SQL)
+
-- #5255/#5176 (O-DX-8): last upstream observation per source, recorded by sync
-- from the checkout's Git state (upstream ref, its last fetch/push time, commits
-- the synced commit lacks); doctor sync_freshness reads it with no subprocess.
diff --git a/test/core-guard.test.ts b/test/core-guard.test.ts
new file mode 100644
index 0000000000..a98fbb4b51
--- /dev/null
+++ b/test/core-guard.test.ts
@@ -0,0 +1,191 @@
+/**
+ * Always-loaded core tier write-path guard (src/core/persistence/core-guard.ts)
+ * through the coordinated write path: owner-only marking, brain-wide budget,
+ * remote-edit policy and notices, remote delete. PGLite in-memory ($0).
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test as bunTest } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
+import { coreLockSources, lockCoreSources } from '../src/core/persistence/core-guard.ts';
+import { listCorePages } from '../src/core/core-memory.ts';
+
+let engine: PGLiteEngine;
+let fixture: string;
+let remoteRegistration: LocalRegistration;
+let cliRegistration: LocalRegistration;
+const remoteAuth = { token: 'fixture', clientId: 'fixture-client', scopes: ['read', 'write'], sourceId: 'default' };
+
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => {
+ await disposePersistenceConsumer(engine);
+ await resetPgliteState(engine);
+ _resetWriteThroughCacheForTest();
+ fixture = mkdtempSync(join(tmpdir(), 'gb-core-guard-'));
+ mkdirSync(join(fixture, 'brain'));
+ await engine.setConfig('sync.repo_path', join(fixture, 'brain'));
+});
+afterEach(async () => { await disposePersistenceConsumer(engine); rmSync(fixture, { recursive: true, force: true }); });
+
+function test(name: string, run: () => Promise<void>, timeout = 30_000) {
+ bunTest(name, () => withEnv({ GBRAIN_HOME: join(fixture, 'home') }, async () => {
+ remoteRegistration = await registerLocalWriter(engine, 'stdio', { sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: null });
+ cliRegistration = await registerLocalWriter(engine, 'cli');
+ try { await run(); } finally { await disposePersistenceConsumer(engine); }
+ }), timeout);
+}
+
+async function call(name: string, params: Record<string, unknown>, remote = true) {
+ const response = await withVerifiedLocalRegistration(engine, remote ? remoteRegistration : cliRegistration, () => dispatchToolCall(engine, name, params, {
+ remote, config: { engine: 'pglite' }, sourceId: 'default', ...(remote ? { auth: remoteAuth } : {}),
+ logger: { info() {}, warn() {}, error() {} },
+ }));
+ const text = (response.content[0] as { text: string }).text;
+ return { isError: response.isError === true, body: JSON.parse(text), text };
+}
+const page = (title: string, body: string, fm: Record<string, unknown> = {}) =>
+ `---\ntitle: ${title}\ntype: note\n${Object.entries(fm).map(([k, v]) => `${k}: ${v}`).join('\n')}${Object.keys(fm).length ? '\n' : ''}---\n\n${body}\n`;
+async function put(slug: string, content: string, remote: boolean, extra: Record<string, unknown> = {}) {
+ return call('put_page', { slug, content, request_id: randomUUID(), ...extra }, remote);
+}
+async function revision(slug: string) {
+ const r = await call('get_page', { slug, include_content: true }, false);
+ return r.body.revision as string;
+}
+const corePages = async () => (await listCorePages(engine)).map(p => p.slug).sort();
+
+describe('owner-only marking', () => {
+ test('the owner (local CLI) designates a page; a remote caller cannot add or remove always_load', async () => {
+ const owner = await put('people/alice-example', page('Alice Example', 'Prefers tea.', { always_load: true }), false);
+ expect({ isError: owner.isError, text: owner.text }).toMatchObject({ isError: false });
+ expect(await corePages()).toEqual(['people/alice-example']);
+ expect(owner.body.core).toMatchObject({ chars_limit: 4000 });
+
+ const add = await put('notes/remote', page('Remote', 'x', { always_load: true }), true);
+ expect(add.body).toMatchObject({ error: 'core_mark_owner_only' });
+ expect(add.body.message).toContain('gbrain core add --source default notes/remote');
+
+ const rev = await revision('people/alice-example');
+ const flip = await put('people/alice-example', page('Alice Example', 'Prefers tea.', { always_load: false }), true, { expected_revision: rev });
+ expect(flip.body).toMatchObject({ error: 'core_mark_owner_only' });
+ const prio = await put('people/alice-example', page('Alice Example', 'Prefers tea.', { always_load: true, core_priority: 1 }), true, { expected_revision: rev });
+ expect(prio.body).toMatchObject({ error: 'core_mark_owner_only' });
+ expect(await corePages()).toEqual(['people/alice-example']);
+ });
+
+ test('a remote rewrite that omits always_load keeps the page in core', async () => {
+ await put('people/alice-example', page('Alice Example', 'Prefers tea.', { always_load: true, core_priority: 3 }), false);
+ const rev = await revision('people/alice-example');
+ const rewrite = await put('people/alice-example', page('Alice Example', 'Prefers green tea.'), true, { expected_revision: rev });
+ expect({ isError: rewrite.isError, text: rewrite.text }).toMatchObject({ isError: false });
+ const [row] = await engine.executeRaw<{ frontmatter: Record<string, unknown>; compiled_truth: string }>(
+ `SELECT frontmatter, compiled_truth FROM pages WHERE slug='people/alice-example'`);
+ expect(row.frontmatter.always_load).toBe(true);
+ expect(Number(row.frontmatter.core_priority)).toBe(3);
+ expect(row.compiled_truth).toContain('green tea');
+ });
+
+ test('a remote always_load: false on a non-core page is a no-op, not a refusal', async () => {
+ const r = await put('notes/plain', page('Plain', 'x', { always_load: false }), true);
+ expect({ isError: r.isError, text: r.text }).toMatchObject({ isError: false });
+ });
+
+ test('a remote caller cannot delete a core page', async () => {
+ await put('people/alice-example', page('Alice Example', 'Prefers tea.', { always_load: true }), false);
+ const del = await call('delete_page', { slug: 'people/alice-example', expected_revision: await revision('people/alice-example'), request_id: randomUUID() }, true);
+ expect(del.body).toMatchObject({ error: 'core_delete_owner_only' });
+ expect(await corePages()).toEqual(['people/alice-example']);
+ });
+});
+
+describe('budget', () => {
+ test('growth past the brain-wide budget is refused; shrinking passes; timeline never counts', async () => {
+ await engine.setConfig('memory.core.max_chars', '600');
+ const ok = await put('people/alice-example', page('Alice Example', 'a'.repeat(300), { always_load: true }), false);
+ expect(ok.isError).toBe(false);
+ const big = await put('notes/big', page('Big', 'b'.repeat(400), { always_load: true }), false);
+ expect(big.body).toMatchObject({ error: 'core_budget_exceeded' });
+ expect(big.body.message).toContain('over the 600-char budget');
+ expect(big.body.fix?.argv).toEqual(['gbrain', 'core', 'status', '--json']);
+ expect(await corePages()).toEqual(['people/alice-example']);
+
+ // Lower the limit below current usage: growth refused, shrinking passes.
+ await engine.setConfig('memory.core.max_chars', '500');
+ let rev = await revision('people/alice-example');
+ const grow = await put('people/alice-example', page('Alice Example', 'a'.repeat(600), { always_load: true }), true, { expected_revision: rev });
+ expect(grow.body).toMatchObject({ error: 'core_budget_exceeded' });
+ const shrink = await put('people/alice-example', page('Alice Example', 'a'.repeat(100), { always_load: true }), true, { expected_revision: rev });
+ expect({ isError: shrink.isError, text: shrink.text }).toMatchObject({ isError: false });
+
+ rev = await revision('people/alice-example');
+ const tl = await call('add_timeline_entry', { slug: 'people/alice-example', date: '2026-10-04', summary: 'x'.repeat(280), request_id: randomUUID() }, true);
+ expect({ isError: tl.isError, text: tl.text }).toMatchObject({ isError: false });
+ });
+
+ test('remote budget diagnostics never name pages in other sources', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('wiki', 'wiki') ON CONFLICT DO NOTHING`);
+ await engine.putPage('projects/secret-wiki-core', { type: 'project', title: 'Secret wiki core', compiled_truth: 'w'.repeat(300), frontmatter: { always_load: true } }, { sourceId: 'wiki' });
+ await engine.setConfig('memory.core.max_chars', '500');
+ await put('people/alice-example', page('Alice Example', 'a', { always_load: true }), false);
+ const rev = await revision('people/alice-example');
+ const grow = await put('people/alice-example', page('Alice Example', 'a'.repeat(400), { always_load: true }), true, { expected_revision: rev });
+ expect(grow.body).toMatchObject({ error: 'core_budget_exceeded' });
+ expect(grow.text).not.toContain('secret-wiki-core');
+ expect(grow.text).toContain('sources you cannot read');
+ });
+});
+
+describe('remote-edit policy', () => {
+ test('notify records a notice; refuse rejects the edit', async () => {
+ await put('people/alice-example', page('Alice Example', 'Prefers tea.', { always_load: true }), false);
+ let rev = await revision('people/alice-example');
+ const edit = await call('edit_page', { slug: 'people/alice-example', expected_revision: rev, edits: [{ old_text: 'Prefers tea.', new_text: 'Prefers coffee.' }], request_id: randomUUID() }, true);
+ expect({ isError: edit.isError, text: edit.text }).toMatchObject({ isError: false });
+ const notices = await engine.executeRaw<{ slug: string; actor: string; revision: string | null }>(`SELECT slug, actor, revision FROM core_edit_notices`);
+ expect(notices).toHaveLength(1);
+ expect(notices[0].slug).toBe('people/alice-example');
+ expect(notices[0].revision).toBe(edit.body.revision);
+
+ await engine.setConfig('memory.core.remote_edit', 'refuse');
+ rev = await revision('people/alice-example');
+ const refused = await call('edit_page', { slug: 'people/alice-example', expected_revision: rev, edits: [{ old_text: 'Prefers coffee.', new_text: 'Prefers water.' }], request_id: randomUUID() }, true);
+ expect(refused.body).toMatchObject({ error: 'core_remote_edit_refused' });
+ // The owner still edits freely.
+ const owner = await call('edit_page', { slug: 'people/alice-example', expected_revision: rev, edits: [{ old_text: 'Prefers coffee.', new_text: 'Prefers water.' }], request_id: randomUUID() }, false);
+ expect({ isError: owner.isError, text: owner.text }).toMatchObject({ isError: false });
+ expect((await engine.executeRaw(`SELECT 1 FROM core_edit_notices`)).length).toBe(1);
+ });
+
+ test('remember writing a facts row into a core page is budget-checked and noticed', async () => {
+ await put('people/alice-example', page('Alice Example', 'Prefers tea.', { always_load: true }), false);
+ const r = await call('remember', { fact: 'Alice prefers oolong over green tea', provenance: 'user told me, 2026-10-04', entity: 'people/alice-example', request_id: randomUUID() }, true);
+ expect({ isError: r.isError, text: r.text }).toMatchObject({ isError: false });
+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM core_edit_notices`);
+ expect(row.n).toBe(1);
+ await engine.setConfig('memory.core.max_chars', '500');
+ const before = await engine.executeRaw<{ compiled_truth: string }>(`SELECT compiled_truth FROM pages WHERE slug='people/alice-example'`);
+ const over = await call('remember', { fact: 'z'.repeat(400), provenance: 'user told me, 2026-10-04', entity: 'people/alice-example', request_id: randomUUID() }, true);
+ // The frozen verb contract keeps its code; the core refusal rides detail + write_error.
+ expect(over.body).toMatchObject({ error: 'invalid_params', detail: 'core_budget_exceeded', write_error: 'core_budget_exceeded' });
+ expect(over.body.message).toContain('over the 500-char budget');
+ const after = await engine.executeRaw<{ compiled_truth: string }>(`SELECT compiled_truth FROM pages WHERE slug='people/alice-example'`);
+ expect(after[0].compiled_truth).toBe(before[0].compiled_truth);
+ });
+});
+
+describe('lock function', () => {
+ bunTest('locks own source and default, deduplicated, in id order', async () => {
+ expect(coreLockSources('wiki')).toEqual(['default', 'wiki']);
+ expect(coreLockSources('default')).toEqual(['default']);
+ await engine.transaction(async tx => { await lockCoreSources(tx, ['wiki', 'default', 'wiki']); });
+ });
+});
diff --git a/test/core-memory.test.ts b/test/core-memory.test.ts
new file mode 100644
index 0000000000..e11174fdb3
--- /dev/null
+++ b/test/core-memory.test.ts
@@ -0,0 +1,133 @@
+/**
+ * Always-loaded core memory: normalization, rendering, budget truncation,
+ * ordering, revision and the brain-wide listing. PGLite in-memory ($0).
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ CORE_DEFAULT_MAX_CHARS, coreChars, corePriority, coreRevision, coreUsage, isCoreFrontmatter, listCorePages,
+ loadCoreBlock, orderCorePages, parseCoreMaxChars, renderCoreBlock, renderCorePage, toCorePage, validateCoreConfigValue,
+} from '../src/core/core-memory.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../src/core/takes-fence.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('wiki', 'wiki') ON CONFLICT DO NOTHING`);
+}, 60_000);
+afterAll(async () => { if (engine) await engine.disconnect(); }, 60_000);
+
+describe('core marking normalization', () => {
+ test('only always_load: true is core', () => {
+ expect(isCoreFrontmatter({ always_load: true })).toBe(true);
+ for (const v of [false, 'true', 1, 0, null, undefined, 'yes']) expect(isCoreFrontmatter({ always_load: v })).toBe(false);
+ expect(isCoreFrontmatter(null)).toBe(false);
+ });
+ test('core_priority is a positive integer, else 100', () => {
+ expect(corePriority({ core_priority: 3 })).toBe(3);
+ expect(corePriority({ core_priority: '7' })).toBe(7);
+ for (const v of [0, -1, 1.5, 'x', null, undefined]) expect(corePriority({ core_priority: v })).toBe(100);
+ });
+ test('config validation names the range', () => {
+ expect(parseCoreMaxChars('4000')).toBe(4000);
+ expect(parseCoreMaxChars('499')).toBeNull();
+ expect(parseCoreMaxChars('6001')).toBeNull();
+ expect(validateCoreConfigValue('memory.core.max_chars', '7000')).toContain('500 to 6000');
+ expect(validateCoreConfigValue('memory.core.remote_edit', 'maybe')).toContain('allow, notify or refuse');
+ expect(validateCoreConfigValue('memory.core.max_chars', '4000')).toBeNull();
+ });
+});
+
+describe('rendering', () => {
+ test('renders title and compiled truth in the remote-safe view (takes dropped, timeline never included)', () => {
+ const body = `I prefer short answers.\n\n${TAKES_FENCE_BEGIN}\n| secret take |\n${TAKES_FENCE_END}\nEnd.`;
+ const out = renderCorePage({ source_id: 'default', slug: 'people/alice-example', title: 'Alice Example', compiled_truth: body });
+ expect(out.startsWith('### Alice Example (default:people/alice-example)\n')).toBe(true);
+ expect(out).toContain('I prefer short answers.');
+ expect(out).not.toContain('secret take');
+ expect(out).not.toContain(TAKES_FENCE_BEGIN);
+ });
+ test('facts fences render world rows only', () => {
+ const fence = renderFactsTable([
+ { rowNum: 1, claim: 'likes tea', kind: 'preference', confidence: 1, visibility: 'world', notability: 'medium', active: true },
+ { rowNum: 2, claim: 'private thing', kind: 'fact', confidence: 1, visibility: 'private', notability: 'medium', active: true },
+ ]);
+ const out = renderCorePage({ source_id: 'default', slug: 'me', title: 'Me', compiled_truth: fence });
+ expect(out).toContain('likes tea');
+ expect(out).not.toContain('private thing');
+ });
+ test('block cuts whole pages past the budget, lowest priority first, with a visible line', () => {
+ const pages = [
+ toCorePage({ source_id: 'default', slug: 'a', title: 'A', compiled_truth: 'x'.repeat(300), frontmatter: { always_load: true, core_priority: 1 } }),
+ toCorePage({ source_id: 'default', slug: 'b', title: 'B', compiled_truth: 'y'.repeat(300), frontmatter: { always_load: true, core_priority: 2 } }),
+ ];
+ const full = renderCoreBlock(pages, { maxChars: 5000 });
+ expect(full.pages.map(p => p.slug)).toEqual(['a', 'b']);
+ expect(full.truncated).toBe(false);
+ expect(full.chars_used).toBe(coreChars(pages));
+ const cut = renderCoreBlock(pages, { maxChars: pages[0].chars + 10 });
+ expect(cut.pages.map(p => p.slug)).toEqual(['a']);
+ expect(cut.truncated).toBe(true);
+ expect(cut.text).toContain('[core truncated: 1 page(s)');
+ expect(cut.text).not.toContain('yyyy');
+ });
+ test('empty core renders nothing', () => {
+ expect(renderCoreBlock([], { maxChars: 4000 }).text).toBe('');
+ });
+ test('notices are capped at five lines plus a count', () => {
+ const page = toCorePage({ source_id: 'default', slug: 'a', title: 'A', compiled_truth: 'x' });
+ const block = renderCoreBlock([page], { maxChars: 4000, notices: Array.from({ length: 8 }, (_, i) => `edit ${i}`) });
+ expect(block.text).toContain('> edit 4');
+ expect(block.text).not.toContain('> edit 5');
+ expect(block.text).toContain('+3 more remote edits');
+ });
+ test('ordering: default source first, then priority, then slug', () => {
+ const mk = (source_id: string, slug: string, p?: number) => toCorePage({ source_id, slug, title: slug, compiled_truth: '', frontmatter: { always_load: true, ...(p ? { core_priority: p } : {}) } });
+ const ordered = orderCorePages([mk('wiki', 'z', 1), mk('default', 'b'), mk('default', 'a', 5)]).map(p => `${p.source_id}:${p.slug}`);
+ expect(ordered).toEqual(['default:a', 'default:b', 'wiki:z']);
+ });
+ test('revision moves when rendered text, priority or the limit changes', () => {
+ const a = toCorePage({ source_id: 'default', slug: 'a', title: 'A', compiled_truth: 'one' });
+ const r1 = coreRevision([a], 4000);
+ expect(coreRevision([a], 4000)).toBe(r1);
+ expect(coreRevision([toCorePage({ ...a, compiled_truth: 'two' })], 4000)).not.toBe(r1);
+ expect(coreRevision([a], 3000)).not.toBe(r1);
+ expect(coreRevision([toCorePage({ ...a, frontmatter: { core_priority: 2 } })], 4000)).not.toBe(r1);
+ });
+});
+
+describe('listing (PGLite)', () => {
+ test('lists live always_load pages across sources, honoring source scope and deletion', async () => {
+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Prefers tea.', frontmatter: { always_load: true } });
+ await engine.putPage('notes/not-core', { type: 'note', title: 'Not core', compiled_truth: 'x', frontmatter: { always_load: false } });
+ await engine.putPage('notes/string-true', { type: 'note', title: 'String', compiled_truth: 'x', frontmatter: { always_load: 'true' } });
+ await engine.putPage('projects/wiki-core', { type: 'project', title: 'Wiki core', compiled_truth: 'Wiki standing rule.', frontmatter: { always_load: true } }, { sourceId: 'wiki' });
+ const all = await listCorePages(engine);
+ expect(all.map(p => `${p.source_id}:${p.slug}`).sort()).toEqual(['default:people/alice-example', 'wiki:projects/wiki-core']);
+ const scoped = await listCorePages(engine, { sourceIds: ['default'] });
+ expect(scoped.map(p => p.slug)).toEqual(['people/alice-example']);
+ const excluded = await coreUsage(engine, { exclude: { sourceId: 'wiki', slug: 'projects/wiki-core' } });
+ expect(excluded.pages.map(p => p.slug)).toEqual(['people/alice-example']);
+ await engine.softDeletePage('projects/wiki-core', { sourceId: 'wiki' });
+ expect((await listCorePages(engine)).map(p => p.slug)).toEqual(['people/alice-example']);
+ });
+ test('session block shows default plus the session source; disabled renders nothing', async () => {
+ await engine.putPage('projects/wiki-two', { type: 'project', title: 'Wiki two', compiled_truth: 'Second.', frontmatter: { always_load: true } }, { sourceId: 'wiki' });
+ const block = await loadCoreBlock(engine, { sessionSourceId: 'wiki' });
+ expect(block.pages.map(p => `${p.source_id}:${p.slug}`)).toEqual(['default:people/alice-example', 'wiki:projects/wiki-two']);
+ expect(block.text).toContain(`/${CORE_DEFAULT_MAX_CHARS.toLocaleString('en-US')} chars`);
+ const defaultOnly = await loadCoreBlock(engine, { sessionSourceId: 'default' });
+ expect(defaultOnly.pages.map(p => p.source_id)).toEqual(['default']);
+ const granted = await loadCoreBlock(engine, { sessionSourceId: 'wiki', allowedSources: ['wiki'] });
+ expect(granted.pages.map(p => p.source_id)).toEqual(['wiki']);
+ await engine.setConfig('memory.core.enabled', 'false');
+ const off = await loadCoreBlock(engine, { sessionSourceId: 'wiki' });
+ expect(off.enabled).toBe(false);
+ expect(off.text).toBe('');
+ await engine.setConfig('memory.core.enabled', 'true');
+ });
+});
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 99a6d7000e..a64d38b44d 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -32,6 +32,7 @@
"context_volunteer_events.context_volunteer_events_pkey": "p PRIMARY KEY (id)",
"conversation_parser_llm_cache.conversation_parser_llm_cache_call_shape_check": "c CHECK ((call_shape = ANY (ARRAY['polish'::text, 'fallback'::text])))",
"conversation_parser_llm_cache.conversation_parser_llm_cache_pkey": "p PRIMARY KEY (content_sha256, model_id, call_shape)",
+ "core_edit_notices.core_edit_notices_pkey": "p PRIMARY KEY (id)",
"decide_calibrations.decide_calibrations_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_sweep_id_pair_index_key": "u UNIQUE (sweep_id, pair_index)",
@@ -369,6 +370,9 @@
"conversation_parser_llm_cache": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "core_edit_notices": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"decide_calibrations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -672,6 +676,8 @@
"context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",
"context_volunteer_events_src_time_idx": "CREATE INDEX context_volunteer_events_src_time_idx ON public.context_volunteer_events USING btree (source_id, volunteered_at DESC)",
"conversation_parser_llm_cache_pkey": "CREATE UNIQUE INDEX conversation_parser_llm_cache_pkey ON public.conversation_parser_llm_cache USING btree (content_sha256, model_id, call_shape)",
+ "core_edit_notices_pending_idx": "CREATE INDEX core_edit_notices_pending_idx ON public.core_edit_notices USING btree (source_id, slug, id) WHERE (acked_at IS NULL)",
+ "core_edit_notices_pkey": "CREATE UNIQUE INDEX core_edit_notices_pkey ON public.core_edit_notices USING btree (id)",
"decide_calibrations_lookup_idx": "CREATE INDEX decide_calibrations_lookup_idx ON public.decide_calibrations USING btree (slot, provider, model_resolved, created_at DESC)",
"decide_calibrations_pkey": "CREATE UNIQUE INDEX decide_calibrations_pkey ON public.decide_calibrations USING btree (id)",
"decide_proposals_pkey": "CREATE UNIQUE INDEX decide_proposals_pkey ON public.decide_proposals USING btree (id)",
@@ -989,6 +995,7 @@
"code_traversal_cache_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=code_traversal_cache.id",
"content_chunks_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=content_chunks.id",
"context_volunteer_events_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=context_volunteer_events.id",
+ "core_edit_notices_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=core_edit_notices.id",
"decide_calibrations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_calibrations.id",
"decide_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_proposals.id",
"decision_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decision_receipts.id",
@@ -1255,6 +1262,20 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "core_edit_notices": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('core_edit_notices_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 slug text/text NOT NULL",
+ "4 page_id bigint/int8 NULL",
+ "5 revision text/text NULL",
+ "6 base_revision text/text NULL",
+ "7 actor text/text NOT NULL",
+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "9 acked_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"decide_calibrations": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('decide_calibrations_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index db8a7c1b35..35fa3949c2 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -32,6 +32,7 @@
"context_volunteer_events.context_volunteer_events_pkey": "p PRIMARY KEY (id)",
"conversation_parser_llm_cache.conversation_parser_llm_cache_call_shape_check": "c CHECK ((call_shape = ANY (ARRAY['polish'::text, 'fallback'::text])))",
"conversation_parser_llm_cache.conversation_parser_llm_cache_pkey": "p PRIMARY KEY (content_sha256, model_id, call_shape)",
+ "core_edit_notices.core_edit_notices_pkey": "p PRIMARY KEY (id)",
"decide_calibrations.decide_calibrations_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_sweep_id_pair_index_key": "u UNIQUE (sweep_id, pair_index)",
@@ -369,6 +370,9 @@
"conversation_parser_llm_cache": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "core_edit_notices": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"decide_calibrations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -672,6 +676,8 @@
"context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",
"context_volunteer_events_src_time_idx": "CREATE INDEX context_volunteer_events_src_time_idx ON public.context_volunteer_events USING btree (source_id, volunteered_at DESC)",
"conversation_parser_llm_cache_pkey": "CREATE UNIQUE INDEX conversation_parser_llm_cache_pkey ON public.conversation_parser_llm_cache USING btree (content_sha256, model_id, call_shape)",
+ "core_edit_notices_pending_idx": "CREATE INDEX core_edit_notices_pending_idx ON public.core_edit_notices USING btree (source_id, slug, id) WHERE (acked_at IS NULL)",
+ "core_edit_notices_pkey": "CREATE UNIQUE INDEX core_edit_notices_pkey ON public.core_edit_notices USING btree (id)",
"decide_calibrations_lookup_idx": "CREATE INDEX decide_calibrations_lookup_idx ON public.decide_calibrations USING btree (slot, provider, model_resolved, created_at DESC)",
"decide_calibrations_pkey": "CREATE UNIQUE INDEX decide_calibrations_pkey ON public.decide_calibrations USING btree (id)",
"decide_proposals_pkey": "CREATE UNIQUE INDEX decide_proposals_pkey ON public.decide_proposals USING btree (id)",
@@ -989,6 +995,7 @@
"code_traversal_cache_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=code_traversal_cache.id",
"content_chunks_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=content_chunks.id",
"context_volunteer_events_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=context_volunteer_events.id",
+ "core_edit_notices_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=core_edit_notices.id",
"decide_calibrations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_calibrations.id",
"decide_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_proposals.id",
"decision_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decision_receipts.id",
@@ -1255,6 +1262,20 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "core_edit_notices": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('core_edit_notices_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 slug text/text NOT NULL",
+ "4 page_id bigint/int8 NULL",
+ "5 revision text/text NULL",
+ "6 base_revision text/text NULL",
+ "7 actor text/text NOT NULL",
+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "9 acked_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"decide_calibrations": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('decide_calibrations_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 796685335b..42e0af5401 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -32,6 +32,7 @@
"context_volunteer_events.context_volunteer_events_pkey": "p PRIMARY KEY (id)",
"conversation_parser_llm_cache.conversation_parser_llm_cache_call_shape_check": "c CHECK ((call_shape = ANY (ARRAY['polish'::text, 'fallback'::text])))",
"conversation_parser_llm_cache.conversation_parser_llm_cache_pkey": "p PRIMARY KEY (content_sha256, model_id, call_shape)",
+ "core_edit_notices.core_edit_notices_pkey": "p PRIMARY KEY (id)",
"decide_calibrations.decide_calibrations_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_sweep_id_pair_index_key": "u UNIQUE (sweep_id, pair_index)",
@@ -369,6 +370,9 @@
"conversation_parser_llm_cache": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "core_edit_notices": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"decide_calibrations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -672,6 +676,8 @@
"context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",
"context_volunteer_events_src_time_idx": "CREATE INDEX context_volunteer_events_src_time_idx ON public.context_volunteer_events USING btree (source_id, volunteered_at DESC)",
"conversation_parser_llm_cache_pkey": "CREATE UNIQUE INDEX conversation_parser_llm_cache_pkey ON public.conversation_parser_llm_cache USING btree (content_sha256, model_id, call_shape)",
+ "core_edit_notices_pending_idx": "CREATE INDEX core_edit_notices_pending_idx ON public.core_edit_notices USING btree (source_id, slug, id) WHERE (acked_at IS NULL)",
+ "core_edit_notices_pkey": "CREATE UNIQUE INDEX core_edit_notices_pkey ON public.core_edit_notices USING btree (id)",
"decide_calibrations_lookup_idx": "CREATE INDEX decide_calibrations_lookup_idx ON public.decide_calibrations USING btree (slot, provider, model_resolved, created_at DESC)",
"decide_calibrations_pkey": "CREATE UNIQUE INDEX decide_calibrations_pkey ON public.decide_calibrations USING btree (id)",
"decide_proposals_pkey": "CREATE UNIQUE INDEX decide_proposals_pkey ON public.decide_proposals USING btree (id)",
@@ -985,6 +991,7 @@
"code_traversal_cache_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=code_traversal_cache.id",
"content_chunks_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=content_chunks.id",
"context_volunteer_events_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=context_volunteer_events.id",
+ "core_edit_notices_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=core_edit_notices.id",
"decide_calibrations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_calibrations.id",
"decide_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_proposals.id",
"decision_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decision_receipts.id",
@@ -1251,6 +1258,20 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "core_edit_notices": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('core_edit_notices_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 slug text/text NOT NULL",
+ "4 page_id bigint/int8 NULL",
+ "5 revision text/text NULL",
+ "6 base_revision text/text NULL",
+ "7 actor text/text NOT NULL",
+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "9 acked_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"decide_calibrations": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('decide_calibrations_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index 3a33f51e94..54aced48de 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -17,6 +17,7 @@
"content_chunks.content_chunks_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"content_chunks.content_chunks_pkey": "p PRIMARY KEY (id)",
"context_volunteer_events.context_volunteer_events_pkey": "p PRIMARY KEY (id)",
+ "core_edit_notices.core_edit_notices_pkey": "p PRIMARY KEY (id)",
"decide_calibrations.decide_calibrations_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_sweep_id_pair_index_key": "u UNIQUE (sweep_id, pair_index)",
@@ -278,6 +279,9 @@
"context_volunteer_events": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "core_edit_notices": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"decide_calibrations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -520,6 +524,8 @@
"context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)",
"context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",
"context_volunteer_events_src_time_idx": "CREATE INDEX context_volunteer_events_src_time_idx ON public.context_volunteer_events USING btree (source_id, volunteered_at DESC)",
+ "core_edit_notices_pending_idx": "CREATE INDEX core_edit_notices_pending_idx ON public.core_edit_notices USING btree (source_id, slug, id) WHERE (acked_at IS NULL)",
+ "core_edit_notices_pkey": "CREATE UNIQUE INDEX core_edit_notices_pkey ON public.core_edit_notices USING btree (id)",
"decide_calibrations_lookup_idx": "CREATE INDEX decide_calibrations_lookup_idx ON public.decide_calibrations USING btree (slot, provider, model_resolved, created_at DESC)",
"decide_calibrations_pkey": "CREATE UNIQUE INDEX decide_calibrations_pkey ON public.decide_calibrations USING btree (id)",
"decide_proposals_pkey": "CREATE UNIQUE INDEX decide_proposals_pkey ON public.decide_proposals USING btree (id)",
@@ -742,6 +748,7 @@
"chronicle_judge_reservations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=chronicle_judge_reservations.id",
"content_chunks_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=content_chunks.id",
"context_volunteer_events_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=context_volunteer_events.id",
+ "core_edit_notices_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=core_edit_notices.id",
"decide_calibrations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_calibrations.id",
"decide_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_proposals.id",
"decision_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decision_receipts.id",
@@ -910,6 +917,20 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "core_edit_notices": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('core_edit_notices_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 slug text/text NOT NULL",
+ "4 page_id bigint/int8 NULL",
+ "5 revision text/text NULL",
+ "6 base_revision text/text NULL",
+ "7 actor text/text NOT NULL",
+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "9 acked_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"decide_calibrations": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('decide_calibrations_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index 358ba68154..64a94e15d3 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -17,6 +17,7 @@
"content_chunks.content_chunks_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"content_chunks.content_chunks_pkey": "p PRIMARY KEY (id)",
"context_volunteer_events.context_volunteer_events_pkey": "p PRIMARY KEY (id)",
+ "core_edit_notices.core_edit_notices_pkey": "p PRIMARY KEY (id)",
"decide_calibrations.decide_calibrations_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_sweep_id_pair_index_key": "u UNIQUE (sweep_id, pair_index)",
@@ -278,6 +279,9 @@
"context_volunteer_events": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "core_edit_notices": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"decide_calibrations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -520,6 +524,8 @@
"context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)",
"context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",
"context_volunteer_events_src_time_idx": "CREATE INDEX context_volunteer_events_src_time_idx ON public.context_volunteer_events USING btree (source_id, volunteered_at DESC)",
+ "core_edit_notices_pending_idx": "CREATE INDEX core_edit_notices_pending_idx ON public.core_edit_notices USING btree (source_id, slug, id) WHERE (acked_at IS NULL)",
+ "core_edit_notices_pkey": "CREATE UNIQUE INDEX core_edit_notices_pkey ON public.core_edit_notices USING btree (id)",
"decide_calibrations_lookup_idx": "CREATE INDEX decide_calibrations_lookup_idx ON public.decide_calibrations USING btree (slot, provider, model_resolved, created_at DESC)",
"decide_calibrations_pkey": "CREATE UNIQUE INDEX decide_calibrations_pkey ON public.decide_calibrations USING btree (id)",
"decide_proposals_pkey": "CREATE UNIQUE INDEX decide_proposals_pkey ON public.decide_proposals USING btree (id)",
@@ -742,6 +748,7 @@
"chronicle_judge_reservations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=chronicle_judge_reservations.id",
"content_chunks_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=content_chunks.id",
"context_volunteer_events_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=context_volunteer_events.id",
+ "core_edit_notices_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=core_edit_notices.id",
"decide_calibrations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_calibrations.id",
"decide_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_proposals.id",
"decision_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decision_receipts.id",
@@ -910,6 +917,20 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "core_edit_notices": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('core_edit_notices_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 slug text/text NOT NULL",
+ "4 page_id bigint/int8 NULL",
+ "5 revision text/text NULL",
+ "6 base_revision text/text NULL",
+ "7 actor text/text NOT NULL",
+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "9 acked_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"decide_calibrations": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('decide_calibrations_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index c53886296f..dd961c3b56 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -17,6 +17,7 @@
"content_chunks.content_chunks_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"content_chunks.content_chunks_pkey": "p PRIMARY KEY (id)",
"context_volunteer_events.context_volunteer_events_pkey": "p PRIMARY KEY (id)",
+ "core_edit_notices.core_edit_notices_pkey": "p PRIMARY KEY (id)",
"decide_calibrations.decide_calibrations_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_pkey": "p PRIMARY KEY (id)",
"decide_proposals.decide_proposals_sweep_id_pair_index_key": "u UNIQUE (sweep_id, pair_index)",
@@ -278,6 +279,9 @@
"context_volunteer_events": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "core_edit_notices": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"decide_calibrations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -520,6 +524,8 @@
"context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)",
"context_volunteer_events_src_slug_idx": "CREATE INDEX context_volunteer_events_src_slug_idx ON public.context_volunteer_events USING btree (source_id, slug)",
"context_volunteer_events_src_time_idx": "CREATE INDEX context_volunteer_events_src_time_idx ON public.context_volunteer_events USING btree (source_id, volunteered_at DESC)",
+ "core_edit_notices_pending_idx": "CREATE INDEX core_edit_notices_pending_idx ON public.core_edit_notices USING btree (source_id, slug, id) WHERE (acked_at IS NULL)",
+ "core_edit_notices_pkey": "CREATE UNIQUE INDEX core_edit_notices_pkey ON public.core_edit_notices USING btree (id)",
"decide_calibrations_lookup_idx": "CREATE INDEX decide_calibrations_lookup_idx ON public.decide_calibrations USING btree (slot, provider, model_resolved, created_at DESC)",
"decide_calibrations_pkey": "CREATE UNIQUE INDEX decide_calibrations_pkey ON public.decide_calibrations USING btree (id)",
"decide_proposals_pkey": "CREATE UNIQUE INDEX decide_proposals_pkey ON public.decide_proposals USING btree (id)",
@@ -741,6 +747,7 @@
"chronicle_judge_reservations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=chronicle_judge_reservations.id",
"content_chunks_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=content_chunks.id",
"context_volunteer_events_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=context_volunteer_events.id",
+ "core_edit_notices_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=core_edit_notices.id",
"decide_calibrations_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_calibrations.id",
"decide_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decide_proposals.id",
"decision_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=decision_receipts.id",
@@ -909,6 +916,20 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "core_edit_notices": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('core_edit_notices_id_seq'::regclass)",
+ "2 source_id text/text NOT NULL",
+ "3 slug text/text NOT NULL",
+ "4 page_id bigint/int8 NULL",
+ "5 revision text/text NULL",
+ "6 base_revision text/text NULL",
+ "7 actor text/text NOT NULL",
+ "8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "9 acked_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"decide_calibrations": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('decide_calibrations_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 190c942fa0..cf2a1f2cdc 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 195,
+ "count": 196,
"gaps": [
17,
18,
@@ -28,7 +28,7 @@
"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 200,
+ "latest": 201,
"records": [
{
"handler": {
@@ -2968,6 +2968,19 @@
"transaction": "absent",
"verify": "absent",
"version": 200
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "core_edit_notices",
+ "sql": {
+ "length": 697,
+ "sha256": "f58ea30f1ad5cb36a8953d7b5bde21b068e0207a3a32045a129571687ae356f9"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 201
}
],
"versions": [
@@ -3165,7 +3178,8 @@
197,
198,
199,
- 200
+ 200,
+ 201
]
},
"normalizer": "migrations-record-v1"