Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): managed writer guard resolves tags/timeline/takes source through their page (#5983)
garrytanea0a7895974d
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex b5d014ca8a..e082884888 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.37.0",+ "version": "0.60.38.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex a789917002..c53d1ffe8c 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.60.37.0",+ "version": "0.60.38.0","description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan",diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex ffbcad7368..4be8b13ccb 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.60.37.0 -->+<!-- gbrain-runbook-stamp: 0.60.38.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8642e139b6..88755852d3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,47 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.38.0] - 2026-10-03++**On a managed brain whose `tags`, `timeline_entries` or `takes` table carries a `source_id` column gbrain never created, every tag, timeline and take write was refused, even coordinated ones. Managed sync stalled at the first tagged page, `facts relink` aborted, autopilot dropped timeline rows every cycle, and `remember`, `add_timeline_entry` and maintenance-page writes failed. Those writes commit again (#5983).**++The managed writer guard (`gbrain_require_managed_writer`) decides which source a row belongs to before it lets a write through. It took the row's `source_id` whenever the column existed, even when the value was NULL. gbrain's schema has no such column on those three tables, so on a canonical brain the guard looked up the parent page instead. A brain where something else had added a nullable `source_id` column to them sent every insert and update to the "no source" branch and refused it as `writer_coordinator_required`. Deletes passed through the NULL-source cascade exemption, so delete-only work kept succeeding. The client saw `storage_error: Publication failed (P0001). Inspect owner diagnostics.`++Tags, timeline entries and takes now always take their source from their page. A `source_id` column on them is ignored whatever it holds, so it can neither block a write nor let one through for another source. On such a brain, an uncoordinated delete of a tag, timeline or take row on a live page now needs the coordinator, as it always did on a canonical brain. Deleting a page still removes its children. Migration v197 replaces the guard function only; it re-creates no trigger.++## To take advantage of v0.60.38.0++`gbrain upgrade` installs the binary and runs schema migration v197. Run the upgrade on the brain host (a thin client cannot run it; hand the owner these steps). Pause autopilot during the upgrade: as on every upgrade, the schema replay re-creates the guard triggers.++1. **Keep the failed writes' content while you recover.** Failed write requests keep their original content for 30 days (`persistence.receipt_retention_days`). Brains hit by this bug since activation should keep them longer until the replay tool lands:+ ```bash+ gbrain config set persistence.receipt_retention_days 90+ ```+2. **Run the migration if the upgrade did not, then verify:**+ ```bash+ gbrain apply-migrations --yes --no-autopilot-install+ gbrain doctor --json # the schema_version check reports 197 or later+ ```+3. **Unstick each managed sync.** Re-run the original sync invocation for each affected source unchanged (same brain, source, `--working-tree` and other options), adding `--no-pull --retry-failed --json`. A different sync can succeed while the original failed run stays unresolved.+ ```bash+ gbrain sync --source <id> --no-pull --retry-failed --json+ ```+ Check that the source's `last_commit` advances (`gbrain sources status <id>`).+4. **Rebuild the timeline rows autopilot dropped:**+ ```bash+ gbrain extract --stale --source-id <id> --json+ gbrain extract timeline --source db --source-id <id> --json # rows the page text has but the table lacks+ ```+ Run the second command until it reports no new rows.+5. **Re-link facts. Preview first; the model tier costs money, so ask the user before it:**+ ```bash+ gbrain facts relink --source <id> --dry-run+ gbrain facts relink --source <id> --no-llm+ gbrain facts relink --source <id> --max-usd <n> # only after the user agrees+ ```+ Follow the printed `next_command` until `has_more` is false. Exit 0 alone does not mean the backlog is done.+6. **Writes that failed outright are not replayed by the upgrade.** A `remember`, `add_timeline_entry` or maintenance-page write refused by this bug keeps its failed receipt; resubmitting the same request id returns that failure. Re-issue the ones you have a record of with a new request id, and tell the user which writes from the incident window could not be recovered.+## [0.60.37.0] - 2026-10-03**Foundations 1: a 10,000-page PGLite brain answers health and orphan checks in well under a second instead of 12 to 15 seconds, imports in about a third less time, records who wrote each page version, fact, take and timeline entry, lets several agents share one brain without losing track of whose session produced what, and gives every legacy token the same grant shape as an OAuth client.**diff --git a/VERSION b/VERSIONindex da2b97e132..403e6a4253 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.60.37.0+0.60.38.0diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex b1339cb4a0..0912692c18 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -676,6 +676,7 @@ walk me through it before changing anything."*| Symptom or error text | Issue | Preview | Apply | Verify || --- | --- | --- | --- | --- |+| Tag, timeline or take writes fail with `writer_coordinator_required` or `storage_error: Publication failed (P0001)` on a managed brain; sync ends `PARTIAL` at a tagged page | #5983 | `gbrain doctor --json` (`schema_version` is 197 or later) | the original `gbrain sync --source <source> … --no-pull --retry-failed --json`, then `gbrain extract --stale --source-id <source>` and `gbrain extract timeline --source db --source-id <source>`, then `gbrain facts relink --source <source> --dry-run` (paid tier only after the user agrees) | `gbrain sources status` shows the new `last_commit`; a second `gbrain extract timeline --source db` run adds no rows || Sync `BLOCKED` with `checkpoint_validation_timeout` | #5762 | `gbrain doctor` (`persistence_request_indexes`) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <source> --no-pull --retry-failed …` | `gbrain doctor` shows `persistence_request_indexes` ok; `gbrain sources status` shows the new `last_commit` || Doctor `persistence_request_indexes` warns | #5762 | `gbrain repair request-indexes` | `gbrain repair request-indexes --apply` | `gbrain doctor` || Doctor `persistence_request_growth` warns | #5751, #5762 | `gbrain doctor --json` | the printed `gbrain config set persistence.limits.<limit> <value>` | `gbrain doctor --json` (check `persistence_request_growth`) |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 9b382d4db4..3ad5c04cc0 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -97,6 +97,7 @@ a receipt can report has a row here.| `writer_registration_required` | `writer_registration_required` | The source needs an active canonical owner before this operation, for example activation. | Claim the source on its owner host (`gbrain sources writer status <source>` names the next step). || `writer_identity_invalid` | `writer_identity_invalid` | This host's local writer identity file is unreadable or has an unknown format. | Run `gbrain doctor` on the host; it names the identity file to repair. || `writer_not_initialized` | `writer_not_initialized` | The brain has no persistence identity yet, usually because migrations have not run. | Run `gbrain apply-migrations --yes` on the brain host. |+| <a id="managed-guard-page-children"></a>`writer_coordinator_required: canonical writer must use the persistence coordinator` on a tag, timeline or take write; on the client `storage_error: Publication failed (P0001)` | `writer_coordinator_required` (`storage_error` on the stored receipt) | Before v0.60.38.0, on a managed brain whose `tags`, `timeline_entries` or `takes` table had a `source_id` column gbrain does not create, the managed writer guard refused every insert and update of those rows, including coordinated ones (#5983). From v0.60.38.0 those rows always take their source from their page and the column is ignored. An uncoordinated delete of such a row on a live page is now refused there too, as on every other brain. | Upgrade to v0.60.38.0 or later on the brain host, then follow its recovery steps in the [CHANGELOG](../../CHANGELOG.md) (or [repair](repair.md#recover-after-upgrading-to-this-release)): `gbrain sync … --no-pull --retry-failed`, `gbrain extract --stale`, `gbrain extract timeline --source db`, then a previewed `gbrain facts relink`. || `writer_coordinator_required` | `writer_coordinator_required` | The operation needs managed persistence (the write coordinator) and this brain or call path does not use it. A file write refused because the path sits in a managed canonical worktree names that worktree in the message, and its `detail` reads `root=<directory> source=<id or unknown> evidence=<marker file, managed-root registry or source binding>`. | Run the operation through the command the message names, on a managed brain. When the brain is not managed and the evidence is an ownership file (`.gbrain-owner.json`, `.gbrain-owner-<hash>.json`, `.gbrain-managed`), check it with `gbrain sources writer status` before removing anything: a half-finished claim is finished or rolled back through writer administration. || `fact_already_expired` | `fact_already_expired` | The fact the write targets is already expired or withdrawn. | Nothing to do; list active facts to find the current one. || `source_writeback_required` | `source_writeback_required` | The write needs a correction to the source's repository files, and this caller or profile never writes them. | Make the correction in the source repository, then sync. |diff --git a/llms-full.txt b/llms-full.txtindex 76896d82a4..196585c26f 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -9574,6 +9574,7 @@ walk me through it before changing anything."*| Symptom or error text | Issue | Preview | Apply | Verify || --- | --- | --- | --- | --- |+| Tag, timeline or take writes fail with `writer_coordinator_required` or `storage_error: Publication failed (P0001)` on a managed brain; sync ends `PARTIAL` at a tagged page | #5983 | `gbrain doctor --json` (`schema_version` is 197 or later) | the original `gbrain sync --source <source> … --no-pull --retry-failed --json`, then `gbrain extract --stale --source-id <source>` and `gbrain extract timeline --source db --source-id <source>`, then `gbrain facts relink --source <source> --dry-run` (paid tier only after the user agrees) | `gbrain sources status` shows the new `last_commit`; a second `gbrain extract timeline --source db` run adds no rows || Sync `BLOCKED` with `checkpoint_validation_timeout` | #5762 | `gbrain doctor` (`persistence_request_indexes`) | `gbrain repair request-indexes --apply` when an index is missing or INVALID, then the printed `gbrain sync --source <source> --no-pull --retry-failed …` | `gbrain doctor` shows `persistence_request_indexes` ok; `gbrain sources status` shows the new `last_commit` || Doctor `persistence_request_indexes` warns | #5762 | `gbrain repair request-indexes` | `gbrain repair request-indexes --apply` | `gbrain doctor` || Doctor `persistence_request_growth` warns | #5751, #5762 | `gbrain doctor --json` | the printed `gbrain config set persistence.limits.<limit> <value>` | `gbrain doctor --json` (check `persistence_request_growth`) |@@ -9990,6 +9991,7 @@ a receipt can report has a row here.| `writer_registration_required` | `writer_registration_required` | The source needs an active canonical owner before this operation, for example activation. | Claim the source on its owner host (`gbrain sources writer status <source>` names the next step). || `writer_identity_invalid` | `writer_identity_invalid` | This host's local writer identity file is unreadable or has an unknown format. | Run `gbrain doctor` on the host; it names the identity file to repair. || `writer_not_initialized` | `writer_not_initialized` | The brain has no persistence identity yet, usually because migrations have not run. | Run `gbrain apply-migrations --yes` on the brain host. |+| <a id="managed-guard-page-children"></a>`writer_coordinator_required: canonical writer must use the persistence coordinator` on a tag, timeline or take write; on the client `storage_error: Publication failed (P0001)` | `writer_coordinator_required` (`storage_error` on the stored receipt) | Before v0.60.38.0, on a managed brain whose `tags`, `timeline_entries` or `takes` table had a `source_id` column gbrain does not create, the managed writer guard refused every insert and update of those rows, including coordinated ones (#5983). From v0.60.38.0 those rows always take their source from their page and the column is ignored. An uncoordinated delete of such a row on a live page is now refused there too, as on every other brain. | Upgrade to v0.60.38.0 or later on the brain host, then follow its recovery steps in the [CHANGELOG](../../CHANGELOG.md) (or [repair](repair.md#recover-after-upgrading-to-this-release)): `gbrain sync … --no-pull --retry-failed`, `gbrain extract --stale`, `gbrain extract timeline --source db`, then a previewed `gbrain facts relink`. || `writer_coordinator_required` | `writer_coordinator_required` | The operation needs managed persistence (the write coordinator) and this brain or call path does not use it. A file write refused because the path sits in a managed canonical worktree names that worktree in the message, and its `detail` reads `root=<directory> source=<id or unknown> evidence=<marker file, managed-root registry or source binding>`. | Run the operation through the command the message names, on a managed brain. When the brain is not managed and the evidence is an ownership file (`.gbrain-owner.json`, `.gbrain-owner-<hash>.json`, `.gbrain-managed`), check it with `gbrain sources writer status` before removing anything: a half-finished claim is finished or rolled back through writer administration. || `fact_already_expired` | `fact_already_expired` | The fact the write targets is already expired or withdrawn. | Nothing to do; list active facts to find the current one. || `source_writeback_required` | `source_writeback_required` | The write needs a correction to the source's repository files, and this caller or profile never writes them. | Make the correction in the source repository, then sync. |diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex d350f981d3..fd6523249b 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.60.37.0",+ "version": "0.60.38.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","kind": "context-engine",diff --git a/package.json b/package.jsonindex 682c56ce12..2802979c87 100644--- a/package.json+++ b/package.json@@ -207,7 +207,7 @@"bun": ">=1.4.0"},"license": "MIT",- "version": "0.60.37.0",+ "version": "0.60.38.0","overrides": {"@ai-sdk/provider-utils": "4.0.56","@hono/node-server": "^2.0.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 95970d5537..ccac395ad3 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.37.0",+ "version": "0.60.38.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 8f0139692e..78f43e1338 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.60.37.0",+ "version": "0.60.38.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex fd6cce50f0..4df2184dfe 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.37.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.38.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 1dff32bab5..b07cbb6b7c 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.37.0",+ "version": "0.60.38.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex 96bd91d926..328fe99fc2 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.60.37.0",+ "version": "0.60.38.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 64a28cb4da..b5336ae6c6 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.37.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.38.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex 5b51f6a44e..d4e6aa3fa7 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.60.37.0 -->+<!-- gbrain-plugin-tree-stamp: 0.60.38.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 8cc8f5aa77..4b1515d14c 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -505,6 +505,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/schema-migrations/v188-facts-ontology-stint-dedup.ts": ["test/e2e/ontology-merge-parity.test.ts", "test/e2e/schema-drift.test.ts"],"src/core/persistence/memory-mutations.ts": ["test/e2e/withdrawal-followup-writes-postgres.test.ts"],"src/core/persistence/coordinator.ts": ["test/e2e/withdrawal-followup-writes-postgres.test.ts"],+ "src/core/persistence/writer-guard-schema.ts": ["test/e2e/managed-writer-guard-null-source-5983-postgres.test.ts", "test/e2e/schema-drift.test.ts", "test/e2e/schema-catalog-golden.test.ts"],+ "src/core/schema-migrations/v197-managed-guard-null-source-fallback.ts": ["test/e2e/managed-writer-guard-null-source-5983-postgres.test.ts", "test/e2e/schema-drift.test.ts", "test/e2e/schema-catalog-golden.test.ts"],"src/core/facts/meta-hook.ts": ["test/e2e/capture-dedup-postgres.test.ts", "test/e2e/hot-memory-invalidation-postgres.test.ts", "test/e2e/facts-context-injection-postgres.test.ts", "test/e2e/serve-http-meta.test.ts"],"src/mcp/dispatch.ts": ["test/e2e/hot-memory-invalidation-postgres.test.ts", "test/e2e/write-contract-conformance.test.ts"],// Foundations 1 F4b: PGLite-only planner-stats accounting; Postgres must gain no object, doctor/repair read pg_stat_user_tables.diff --git a/src/core/persistence/writer-guard-schema.ts b/src/core/persistence/writer-guard-schema.tsindex 574de90dcc..b43decd8e5 100644--- a/src/core/persistence/writer-guard-schema.ts+++ b/src/core/persistence/writer-guard-schema.ts@@ -1,7 +1,11 @@import { ROW_ATTRIBUTION_COLUMNS } from './attribution-schema.ts';const ROW_ATTRIBUTION_KEYS = `ARRAY[${ROW_ATTRIBUTION_COLUMNS.map(column => `'${column}'`).join(',')}]`;-/** Defense in depth for inventoried legacy writers. Manual SQL is outside the protocol. */-export const MANAGED_WRITER_GUARD_SQL = `+/** Guarded tables with no canonical source_id: their source is always their page's (#5983). */+const PAGE_CHILD_TABLES = ['tags', 'timeline_entries', 'takes'];+const GUARDED_TABLES = ['pages', 'tags', 'slug_aliases', 'page_aliases', 'facts', 'takes', 'timeline_entries', 'sources'];+const sqlList = (names: string[]) => names.map(name => `'${name}'`).join(',');+/** The guard function alone: replacing it takes no table lock (v197). */+export const MANAGED_WRITER_GUARD_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION gbrain_require_managed_writer() RETURNS trigger LANGUAGE plpgsql AS $fn$DECLARE target_source text; old_source text; row_data jsonb; old_data jsonb; allowed jsonb;BEGIN@@ -37,11 +41,12 @@ BEGINIF (row_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at'])= (old_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at']) THEN RETURN NEW; END IF;END IF;- IF row_data ? 'source_id' THEN target_source := row_data->>'source_id';- ELSE SELECT source_id INTO target_source FROM pages WHERE id=(row_data->>'page_id')::integer; END IF;- IF TG_OP='UPDATE' THEN- IF old_data ? 'source_id' THEN old_source := old_data->>'source_id';- ELSE SELECT source_id INTO old_source FROM pages WHERE id=(old_data->>'page_id')::integer; END IF;+ IF TG_TABLE_NAME NOT IN (${sqlList(PAGE_CHILD_TABLES)}) THEN+ target_source := row_data->>'source_id'; old_source := old_data->>'source_id';+ END IF;+ IF target_source IS NULL THEN SELECT source_id INTO target_source FROM pages WHERE id=(row_data->>'page_id')::integer; END IF;+ IF TG_OP='UPDATE' AND old_source IS NULL THEN+ SELECT source_id INTO old_source FROM pages WHERE id=(old_data->>'page_id')::integer;END IF;-- Cascaded projection removal after the already-guarded parent deletion.IF target_source IS NULL AND TG_OP='DELETE' THEN RETURN OLD; END IF;@@ -51,10 +56,13 @@ BEGINEND IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END $fn$;+`;+/** Defense in depth for inventoried legacy writers. Manual SQL is outside the protocol. */+export const MANAGED_WRITER_GUARD_SQL = `${MANAGED_WRITER_GUARD_FUNCTION_SQL}DO $body$DECLARE target text;BEGIN- FOREACH target IN ARRAY ARRAY['pages','tags','slug_aliases','page_aliases','facts','takes','timeline_entries','sources'] LOOP+ FOREACH target IN ARRAY ARRAY[${sqlList(GUARDED_TABLES)}] LOOPIF to_regclass(target) IS NOT NULL THENEXECUTE format('DROP TRIGGER IF EXISTS managed_writer_guard ON %I',target);EXECUTE format('CREATE TRIGGER managed_writer_guard BEFORE INSERT OR UPDATE OR DELETE ON %I FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()',target);diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 568c882b54..c45db3493f 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1236,11 +1236,12 @@ BEGINIF (row_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at'])= (old_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at']) THEN RETURN NEW; END IF;END IF;- IF row_data ? 'source_id' THEN target_source := row_data->>'source_id';- ELSE SELECT source_id INTO target_source FROM pages WHERE id=(row_data->>'page_id')::integer; END IF;- IF TG_OP='UPDATE' THEN- IF old_data ? 'source_id' THEN old_source := old_data->>'source_id';- ELSE SELECT source_id INTO old_source FROM pages WHERE id=(old_data->>'page_id')::integer; END IF;+ IF TG_TABLE_NAME NOT IN ('tags','timeline_entries','takes') THEN+ target_source := row_data->>'source_id'; old_source := old_data->>'source_id';+ END IF;+ IF target_source IS NULL THEN SELECT source_id INTO target_source FROM pages WHERE id=(row_data->>'page_id')::integer; END IF;+ IF TG_OP='UPDATE' AND old_source IS NULL THEN+ SELECT source_id INTO old_source FROM pages WHERE id=(old_data->>'page_id')::integer;END IF;-- Cascaded projection removal after the already-guarded parent deletion.IF target_source IS NULL AND TG_OP='DELETE' THEN RETURN OLD; END IF;@@ -1250,6 +1251,7 @@ BEGINEND IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END \$fn\$;+DO \$body\$DECLARE target text;BEGINdiff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 1466eae354..bbd0aa5aa3 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -1939,11 +1939,12 @@ BEGINIF (row_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at'])= (old_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at']) THEN RETURN NEW; END IF;END IF;- IF row_data ? 'source_id' THEN target_source := row_data->>'source_id';- ELSE SELECT source_id INTO target_source FROM pages WHERE id=(row_data->>'page_id')::integer; END IF;- IF TG_OP='UPDATE' THEN- IF old_data ? 'source_id' THEN old_source := old_data->>'source_id';- ELSE SELECT source_id INTO old_source FROM pages WHERE id=(old_data->>'page_id')::integer; END IF;+ IF TG_TABLE_NAME NOT IN ('tags','timeline_entries','takes') THEN+ target_source := row_data->>'source_id'; old_source := old_data->>'source_id';+ END IF;+ IF target_source IS NULL THEN SELECT source_id INTO target_source FROM pages WHERE id=(row_data->>'page_id')::integer; END IF;+ IF TG_OP='UPDATE' AND old_source IS NULL THEN+ SELECT source_id INTO old_source FROM pages WHERE id=(old_data->>'page_id')::integer;END IF;-- Cascaded projection removal after the already-guarded parent deletion.IF target_source IS NULL AND TG_OP='DELETE' THEN RETURN OLD; END IF;@@ -1953,6 +1954,7 @@ BEGINEND IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END \$fn\$;+DO \$body\$DECLARE target text;BEGINdiff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex ebc2c73baa..e75bc6a321 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -197,6 +197,7 @@ import { v193 } from './v193-f1-write-attribution.ts';import { v194 } from './v194-f0-worktree-refreshes.ts';import { v195 } from './v195-f3-access-token-grants.ts';import { v196 } from './v196-f4-planner-stats.ts';+import { v197 } from './v197-managed-guard-null-source-fallback.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -392,4 +393,5 @@ export const MIGRATIONS: Migration[] = [v194,v195,v196,+ v197,];diff --git a/src/core/schema-migrations/v197-managed-guard-null-source-fallback.ts b/src/core/schema-migrations/v197-managed-guard-null-source-fallback.tsnew file mode 100644index 0000000000..b81cf28217--- /dev/null+++ b/src/core/schema-migrations/v197-managed-guard-null-source-fallback.ts@@ -0,0 +1,20 @@+import type { Migration } from './types.ts';+import { MANAGED_WRITER_GUARD_FUNCTION_SQL } from '../persistence/writer-guard-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.+//+// #5983: the managed writer guard read a row's source from its source_id key+// whenever the key existed. A brain whose tags / timeline_entries / takes carry+// a nullable source_id column (not created by gbrain; every value NULL) had+// every coordinated INSERT/UPDATE there refused as writer_coordinator_required.+// Page children now always resolve their source through pages, so a column+// gbrain does not own can neither block nor authorize a write. Replaces only+// the function: the triggers already call it, and re-creating them would take+// ACCESS EXCLUSIVE locks on the largest tables of a live brain.+export const v197: Migration = {+ version: 197,+ name: 'managed_guard_null_source_fallback',+ idempotent: true,+ sql: MANAGED_WRITER_GUARD_FUNCTION_SQL,+};diff --git a/src/schema.sql b/src/schema.sqlindex 6b0ecdbe51..7e242b2782 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -1935,11 +1935,12 @@ BEGINIF (row_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at'])= (old_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at']) THEN RETURN NEW; END IF;END IF;- IF row_data ? 'source_id' THEN target_source := row_data->>'source_id';- ELSE SELECT source_id INTO target_source FROM pages WHERE id=(row_data->>'page_id')::integer; END IF;- IF TG_OP='UPDATE' THEN- IF old_data ? 'source_id' THEN old_source := old_data->>'source_id';- ELSE SELECT source_id INTO old_source FROM pages WHERE id=(old_data->>'page_id')::integer; END IF;+ IF TG_TABLE_NAME NOT IN ('tags','timeline_entries','takes') THEN+ target_source := row_data->>'source_id'; old_source := old_data->>'source_id';+ END IF;+ IF target_source IS NULL THEN SELECT source_id INTO target_source FROM pages WHERE id=(row_data->>'page_id')::integer; END IF;+ IF TG_OP='UPDATE' AND old_source IS NULL THEN+ SELECT source_id INTO old_source FROM pages WHERE id=(old_data->>'page_id')::integer;END IF;-- Cascaded projection removal after the already-guarded parent deletion.IF target_source IS NULL AND TG_OP='DELETE' THEN RETURN OLD; END IF;@@ -1949,6 +1950,7 @@ BEGINEND IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END $fn$;+DO $body$DECLARE target text;BEGINdiff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 448935d487..1c5ec6eab1 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.60.37.0 -->+<!-- gbrain-template-stamp: 0.60.38.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/e2e/managed-writer-guard-null-source-5983-postgres.test.ts b/test/e2e/managed-writer-guard-null-source-5983-postgres.test.tsnew file mode 100644index 0000000000..32989a520c--- /dev/null+++ b/test/e2e/managed-writer-guard-null-source-5983-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../managed-writer-guard-null-source-5983.test.ts'));diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.jsonindex 18914d970d..05b9aa898c 100644--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json@@ -251,7 +251,7 @@"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=763764b9806792f869d68bb422dcdc0ad3498f975799c55e3823123c5f1fb9a5",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=1ba3002d6485edf4f92ea4d380299b2f0872f49ad827e7e76381f9a75efaa404","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d6d7b39b09838a1f5aaf343b766f21d2cd36f9d552a72b757266c779467f9647",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 136686a8f2..89df97d14c 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -314,7 +314,7 @@"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=763764b9806792f869d68bb422dcdc0ad3498f975799c55e3823123c5f1fb9a5",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=1ba3002d6485edf4f92ea4d380299b2f0872f49ad827e7e76381f9a75efaa404","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex dbc02c5885..bcdf3cadc6 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -314,7 +314,7 @@"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=763764b9806792f869d68bb422dcdc0ad3498f975799c55e3823123c5f1fb9a5",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=1ba3002d6485edf4f92ea4d380299b2f0872f49ad827e7e76381f9a75efaa404","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex b466796cc2..e8393fc246 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -314,7 +314,7 @@"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=763764b9806792f869d68bb422dcdc0ad3498f975799c55e3823123c5f1fb9a5",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=1ba3002d6485edf4f92ea4d380299b2f0872f49ad827e7e76381f9a75efaa404","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex 71798886e9..54d1aba780 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -311,7 +311,7 @@"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=763764b9806792f869d68bb422dcdc0ad3498f975799c55e3823123c5f1fb9a5",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=1ba3002d6485edf4f92ea4d380299b2f0872f49ad827e7e76381f9a75efaa404","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",diff --git a/test/managed-writer-guard-null-source-5983.test.ts b/test/managed-writer-guard-null-source-5983.test.tsnew file mode 100644index 0000000000..8b5c103033--- /dev/null+++ b/test/managed-writer-guard-null-source-5983.test.ts@@ -0,0 +1,218 @@+/**+ * #5983: on a managed brain whose tags / timeline_entries / takes carry a+ * nullable source_id column (not created by gbrain; every value NULL), the+ * managed writer guard read the NULL column instead of the parent page and+ * refused every coordinated INSERT/UPDATE as writer_coordinator_required.+ *+ * Contract: page children resolve their source through pages, so any+ * source_id column on them is ignored, NULL or not. Coordinated writes commit,+ * and everything the canonical schema refuses (no coordinator, another source,+ * a drifted value naming the allowed source) is still refused. Runs on PGLite+ * and, through test/e2e, Postgres.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MIGRATIONS, runMigrations } from '../src/core/migrate.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-5983-db-'));+let closePostgres: (() => Promise<void>) | undefined;+const CHILDREN = ['tags', 'timeline_entries', 'takes'] as const;+const REFUSED = /writer_coordinator_required: canonical writer must use the persistence coordinator/;++beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+ for (const engine of engines) {+ for (const table of CHILDREN) await engine.executeRaw(`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS source_id TEXT`);+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });+});++async function pageIn(engine: BrainEngine, sourceId: string): Promise<number> {+ await engine.executeRaw(`INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT (id) DO NOTHING`, [sourceId]);+ const slug = `notes/p-${randomUUID().slice(0, 8)}`;+ const [row] = await engine.executeRaw<{ id: number }>(+ `INSERT INTO pages(source_id,slug,type,title,compiled_truth) VALUES($1,$2,'note','P','body') RETURNING id`, [sourceId, slug]);+ return row.id;+}++/** Runs `sql` with the guard on and `writeSources` as the coordinator's allowed set (undefined: no coordinator). */+async function guarded(engine: BrainEngine, writeSources: string[] | undefined, sql: string, params: unknown[]) {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ await engine.transaction(async tx => {+ if (writeSources) await tx.executeRaw(`SELECT set_config('gbrain.write_sources',$1,true)`, [JSON.stringify(writeSources)]);+ await tx.executeRaw(sql, params);+ });+ } finally {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+}++const INSERTS: Record<(typeof CHILDREN)[number], string> = {+ tags: `INSERT INTO tags(page_id,tag,tag_source) VALUES($1,'probe','added')`,+ timeline_entries: `INSERT INTO timeline_entries(page_id,date,source,summary) VALUES($1,'2026-10-01','test','probe')`,+ takes: `INSERT INTO takes(page_id,row_num,claim,kind,holder) VALUES($1,1,'probe','take','alice-example')`,+};+/** A drifted source_id naming the allowed source on a child of a page in another source. */+const CLAIMING_INSERTS: Record<(typeof CHILDREN)[number], string> = {+ tags: `INSERT INTO tags(page_id,tag,tag_source,source_id) VALUES($1,'probe','added','default')`,+ timeline_entries: `INSERT INTO timeline_entries(page_id,date,source,summary,source_id) VALUES($1,'2026-10-01','test','probe','default')`,+ takes: `INSERT INTO takes(page_id,row_num,claim,kind,holder,source_id) VALUES($1,1,'probe','take','alice-example','default')`,+};+const UPDATES: Record<(typeof CHILDREN)[number], string> = {+ tags: `UPDATE tags SET tag=tag||'x' WHERE page_id=$1`,+ timeline_entries: `UPDATE timeline_entries SET detail=COALESCE(detail,'')||'x' WHERE page_id=$1`,+ takes: `UPDATE takes SET claim=claim||'x' WHERE page_id=$1`,+};+const DELETES: Record<(typeof CHILDREN)[number], string> = {+ tags: `DELETE FROM tags WHERE page_id=$1`,+ timeline_entries: `DELETE FROM timeline_entries WHERE page_id=$1`,+ takes: `DELETE FROM takes WHERE page_id=$1`,+};+const count = async (engine: BrainEngine, table: string, pageId: number) =>+ Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM ${table} WHERE page_id=$1`, [pageId]))[0].n);++test('coordinated INSERT, UPDATE and DELETE on NULL-source_id children of a page in the allowed source commit', async () => {+ for (const engine of engines) {+ for (const table of CHILDREN) {+ const pageId = await pageIn(engine, 'default');+ await guarded(engine, ['default'], INSERTS[table], [pageId]);+ expect(await count(engine, table, pageId)).toBe(1);+ await guarded(engine, ['default'], UPDATES[table], [pageId]);+ await guarded(engine, ['default'], DELETES[table], [pageId]);+ expect(await count(engine, table, pageId)).toBe(0);+ }+ }+});++test('the guard still refuses NULL-source_id child writes without the coordinator or for another source', async () => {+ for (const engine of engines) {+ for (const table of CHILDREN) {+ const pageId = await pageIn(engine, 'default');+ await expect(guarded(engine, undefined, INSERTS[table], [pageId])).rejects.toThrow(REFUSED);+ await expect(guarded(engine, ['other-source'], INSERTS[table], [pageId])).rejects.toThrow(REFUSED);+ await engine.executeRaw(INSERTS[table], [pageId]);+ await expect(guarded(engine, undefined, UPDATES[table], [pageId])).rejects.toThrow(REFUSED);+ await expect(guarded(engine, ['other-source'], UPDATES[table], [pageId])).rejects.toThrow(REFUSED);+ await expect(guarded(engine, undefined, DELETES[table], [pageId])).rejects.toThrow(REFUSED);+ await expect(guarded(engine, ['other-source'], DELETES[table], [pageId])).rejects.toThrow(REFUSED);+ expect(await count(engine, table, pageId)).toBe(1);+ }+ }+});++test('a populated drifted source_id is ignored: the parent page decides the source', async () => {+ for (const engine of engines) {+ for (const table of CHILDREN) {+ const pageId = await pageIn(engine, 'default');+ await engine.executeRaw(INSERTS[table], [pageId]);+ await engine.executeRaw(`UPDATE ${table} SET source_id='elsewhere' WHERE page_id=$1`, [pageId]);+ await guarded(engine, ['default'], UPDATES[table], [pageId]);+ await expect(guarded(engine, ['elsewhere'], UPDATES[table], [pageId])).rejects.toThrow(REFUSED);+ const foreignPage = await pageIn(engine, 'elsewhere');+ await expect(guarded(engine, ['default'], CLAIMING_INSERTS[table], [foreignPage])).rejects.toThrow(REFUSED);+ const moveTo = `UPDATE ${table} SET page_id=$2 WHERE page_id=$1`;+ await expect(guarded(engine, ['elsewhere'], moveTo, [pageId, foreignPage])).rejects.toThrow(REFUSED);+ await guarded(engine, ['default', 'elsewhere'], moveTo, [pageId, foreignPage]);+ expect(await count(engine, table, foreignPage)).toBe(1);+ }+ }+});++test('deleting a page still cascades its NULL-source_id children', async () => {+ for (const engine of engines) {+ const pageId = await pageIn(engine, 'default');+ for (const table of CHILDREN) await engine.executeRaw(INSERTS[table], [pageId]);+ await guarded(engine, ['default'], 'DELETE FROM pages WHERE id=$1', [pageId]);+ for (const table of CHILDREN) expect(await count(engine, table, pageId)).toBe(0);+ }+});++test('a managed put_page of a tagged page with timeline lines commits on a brain with the drifted columns', async () => {+ const logger = { info() {}, warn() {}, error() {} };+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-5983-'));+ const root = join(dir, 'brain'); mkdirSync(root);+ const sourceId = `s5983-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ const slug = 'people/alice-example';+ const content = '---\ntitle: Alice Example\ntype: person\ntags: [founder, example]\n---\nAlice builds things.\n\n---\n\n- **2026-09-30** | Met at demo day';+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID() } });+ const [request] = await engine.executeRaw<{ state: string; error_message: string | null }>(+ `SELECT state,error_message FROM persistence_requests WHERE source_id=$1 AND slug=$2 ORDER BY sequence DESC LIMIT 1`, [sourceId, slug]);+ expect(request).toEqual({ state: 'committed', error_message: null });+ expect((await engine.getTags(slug, { sourceId })).sort()).toEqual(['example', 'founder']);+ expect((await engine.getTimeline(slug, { sourceId })).map(entry => entry.summary)).toEqual(['Met at demo day']);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}, 120_000);++/** gbrain_require_managed_writer() as shipped through 0.60.37.0 (schema v196): source_id read whenever the key exists. */+const PRE_5983_SOURCE_LOOKUP = `IF row_data ? 'source_id' THEN target_source := row_data->>'source_id';+ ELSE SELECT source_id INTO target_source FROM pages WHERE id=(row_data->>'page_id')::integer; END IF;+ IF TG_OP='UPDATE' THEN+ IF old_data ? 'source_id' THEN old_source := old_data->>'source_id';+ ELSE SELECT source_id INTO old_source FROM pages WHERE id=(old_data->>'page_id')::integer; END IF;+ END IF;`;++test('upgrading a v196 brain with the pre-fix guard: v197 unblocks the refused write and is idempotent', async () => {+ const v197 = MIGRATIONS.find(migration => migration.version === 197)!;+ for (const engine of engines) {+ const [{ src }] = await engine.executeRaw<{ src: string }>(+ `SELECT pg_get_functiondef('gbrain_require_managed_writer'::regproc) AS src`);+ const current = src.slice(src.indexOf("IF TG_TABLE_NAME NOT IN ('tags','timeline_entries','takes')"), src.indexOf('-- Cascaded projection removal'));+ expect(current.length).toBeGreaterThan(0);+ await engine.executeRaw(src.replace(current, `${PRE_5983_SOURCE_LOOKUP}\n `));+ const pageId = await pageIn(engine, 'default');+ await expect(guarded(engine, ['default'], INSERTS.tags, [pageId])).rejects.toThrow(REFUSED);+ const triggers = `SELECT tgrelid::regclass::text AS tbl, oid FROM pg_trigger WHERE tgname='managed_writer_guard' ORDER BY 1`;+ const before = await engine.executeRaw(triggers);+ for (let run = 0; run < 2; run++) {+ await engine.setConfig('version', '196');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ expect((await runMigrations(engine)).current).toBeGreaterThanOrEqual(197);+ await guarded(engine, ['default'], INSERTS.tags.replace("'probe'", `'probe-${run}'`), [pageId]);+ expect(await count(engine, 'tags', pageId)).toBe(run + 1);+ await expect(guarded(engine, undefined, INSERTS.tags.replace("'probe'", "'uncoordinated'"), [pageId])).rejects.toThrow(REFUSED);+ }+ expect(v197.sql).not.toMatch(/\b(TRIGGER|ALTER TABLE|LOCK)\b/);+ expect(await engine.executeRaw(triggers)).toEqual(before);+ }+}, 120_000);