Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(persistence): G7a declared database-only classes of a git-canonical source (GBRA-95)
garrytan8b3cd35a9008
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4ca060e0e4..841f2d3332 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,27 @@ 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).+## [Unreleased]++**A git-canonical source now has declared database-only classes: private, alias-private and lineage-private pages, pages under a `storage.db_only` directory, never-filed derive-phase pages and paths Git ignores keep no file in Git on purpose, and any other write that would land in the database alone is refused. A page turning private is published as the Git commit that removes its file. The mode stays off by default and nothing turns it on yet.**++### What changed++| Situation | Before | Now |+|---|---|---|+| A page write on a source with `config.canonical = "git"` that belongs to a declared class (private, alias-private, lineage-private, `storage.db_only` directory, never-filed derive folder, ignored path) | a file was written and committed, or refused `git_target_ignored` | no file is written, no commit is made and no Git effect is queued; the row records its class in `database_only_reason` (`private`, `alias_private`, `lineage_private`, `git_ignored`) |+| A file-backed page of that source turning private | its file was rewritten with the private bytes | the door commits the removal of its file (also when only HEAD still has it) and the same publication clears `source_path`/`source_uri`, so a later sync keeps the page live and private |+| A publication of that source that would commit a private page's bytes (the page or its origin turned private after the write was prepared, a managed import of a private file) | committed | refused `git_private_commit_refused`, nothing written and HEAD unchanged; a group with one such member is refused whole |+| A publication of that source that would write a declared page's file, or store an undeclared page with no file | not checked | refused `git_home_required` |+| A file under a `.gitattributes` rule `filter=lfs` on that source | committed through whatever filter the checkout had | refused `git_lfs_not_enabled` unless `storage.git_lfs` is on (new key, default off) and the checkout configures the LFS filter; then the door commits the LFS pointer |+| A row write to that source by a writer that does not declare the git protocol (an older gbrain) | accepted | refused by the managed writer guard (`git_protocol_required`) |+| `gbrain sources git-gap` on a source without a checkout | its pages were counted as not compared | they are declared `database_only_source` (a whole-source class, outside strict mode) |++### What to watch for after you upgrade++- Migration `git_canonical_declared` adds a one-row counter of git-canonical sources and replaces the managed writer guard function. Nothing is backfilled or rewritten, and while no source is git-canonical the new guard branch refuses nothing.+- Hashing an LFS-routed file stores its object in `.git/lfs/objects` before the publication commits; a publication that rolls back can leave that object behind, unreferenced and harmless.+## [0.60.439.0] - 2026-10-24**`gbrain sources git-gap <source>` shows, read-only, how far a source's database is from what Git has committed: which pages match their committed file, which hold content Git lacks, which Git has moved past, and which are database-only by declaration. Doctor reports the totals as `db_ahead_of_git`. Nothing changes and nothing is written.**diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 9680eaa1c6..015761b574 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -6,6 +6,7 @@ The #6188 fence check and fence repair live in [fence repair](core-fence-repair.- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target or descends from it, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`; while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.- `src/core/persistence/git-gap.ts` + `src/commands/sources-git-gap.ts` + `src/commands/doctor/checks/db-ahead-of-git.ts` — git-canonical memory, wave G1 (`docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census`), read-only. `declaredDatabaseOnly` is the one predicate for pages that may not have a tracked file, tested in order: a read-only mirror source, a private page (`isPrivatePage`), an alias-private page (`isDerivationPrivate`), lineage-private (computed in SQL from `privatePagesFilterFragment`), `database_only_reason`, a `storage.db_only` prefix (`isSourceDbOnlySlug`, refusing an invalid gbrain.yml), a never-filed derive-phase page (page-prepare.ts `isNeverFiledDerivedPage`: no `source_path`/`source_uri` under `DERIVE_PHASE_DB_ONLY_DEFAULTS`), a path the checkout's Git ignores (`ignoredPaths`: filter-free `check-ignore -z --stdin`, tracked files never reported, exit 1 = none, null when Git cannot answer). The equality contract compares a committed blob with the page's export view (`readExportPage`, withdrawals overlaid): an inline blob parsed as reconcile parses a canonical file, aligned with the stored type, subtype and #6429 stamp and compared by `reconcileCanonical` digest; a segmented page by the Git blob id of its streamed export. HEAD is read with hardened plumbing only (`readHeadTree`: one `ls-tree -r -l -z --full-tree` under the source's directory; `readBlobs`: `cat-file --batch` in calls of at most 64 MiB) and the working tree by hashing raw bytes (`worktreeBlobOid`), never `git status`/`git diff`, so no repository filter, textconv or fsmonitor runs. `gbrain sources git-gap <id> [--sample n] [--json]` (trusted local CLI, not an MCP op) puts every live page in one state (`equal`, `database_ahead`, `git_ahead` when the sync import record's `blob_oid`/`disk_blob_oid` differs from HEAD, else folded into `database_ahead` and counted in `database_ahead_without_import_record`, `declared_database_only` per class, `undeclared_database_only`, `worktree_only`, `unparseable`, `unsafe_path`), reports the working tree separately, and counts rows with no Git home (unfenced active facts, fenced facts on a missing page or a page without a committed file, links whose `link_source` is not in `DERIVED_LINK_SOURCES`, timeline rows on pages without a file), open `sync-hold` records by code and parked effect targets by kind and code. Each 256-page batch reads in its own read-only transaction. Doctor `db_ahead_of_git` runs the census per non-archived source whose directory is a Git checkout (others are only counted) under `GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS` (default 10 s) and the entry deadline; it is always `ok` (informational) and lists totals only, a source the budget stopped or never reached as partial. Tests: `test/git-gap-census.test.ts` (PGLite and Postgres).+- `src/core/persistence/git-declared.ts` + `src/core/persistence/git-canonical-schema.ts` (migration `git_canonical_declared`) — git-canonical memory, wave G7a: the declared database-only classes of a strict source (`sources.config.canonical = "git"`, default off). `strictPageClass` judges a page by its slug and prior file (`declaredPathClass`: `db_only_prefix` for a `storage.db_only` dir, `derive_folder` for a never-filed derive-phase page; G3's indexer reads the same function) and then its rendered content (`privacyClass`: `private`, `alias_private`, or `lineage_private` from the same SQL remote reads use, `privatePagesFilterFragment`, over the page's own values). `page-prepare.ts` `prepareFileTarget` asks it before it builds a strict file target: a declared page gets no target (no file, no door commit, no Git effect), an untracked ignored target is `git_ignored`, a page turning private gets the removal of the file it still has in the worktree or at HEAD, and a path whose `filter` attribute is `lfs` passes `assertLfsTarget` only with `storage.git_lfs` and a checkout that configures the LFS filter (`git_lfs_not_enabled`). `preparePrivateTransition` (page-prepare.ts) is that removal for other writers (GBRA-60). In `publishMutation` and `publishGroup`, `assertNoPrivateCommit` refuses a file target carrying a private page's bytes before anything is written (`git_private_commit_refused`; a group rolls back whole), and `declareStrictPublication` (after apply, before the door commit) refuses a declared page's file or an undeclared file-less page (`git_home_required`), stamps `pages.database_only_reason` and, for a privacy class, clears `source_path`/`source_uri` in the transaction of the door commit that removed the file. A managed import builds its own file target, so it meets only these publication checks. `assertStrictGitHome` is the refusal for writers with no file form yet (G4, G5). The managed writer guard (`writer-guard-schema.ts`) refuses rows of a strict source unless the writer declares `gbrain.git_protocol` (`withCoordinatedWrite` does), behind the `git_canonical_brain.strict_sources` counter kept by `sources` triggers (`git_protocol_required`, mapped in `publication-failure.ts`). The census (`git-gap.ts`) adds `database_only_source` (a source with no checkout) and maps the stamped reasons to their own classes. Tests: `test/git-canonical-declared-g7a.test.ts` (both engines).- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `page_body_segmented` is a write error code, so a verb refused by a segmented target keeps it as `write_error` and canonical code under the frozen `invalid_params` (caller class, not retryable) on both the receipt and the pre-admission path (`runMemoryWrite`). `remember` reads a segmented entity page up to PAGE_MAX_BYTES back whole (`materializedPage`) for its inferred-target checks and fence write; over it, a named or inferred entity refuses before admission with `segmentedRememberRefusal` (fix: remember with `infer_entity: false`), never a silent `NO_ENTITY` (`test/large-pages/segmented-remember-refusal.test.ts`); `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex a3ef6083a0..24d05268ae 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1687,6 +1687,18 @@ More: [docs/guides/repair.md#ghost-pages](../../docs/guides/repair.md#ghost-pageMore: [docs/guides/concurrent-writes.md#git-durability-at-activation](../../docs/guides/concurrent-writes.md#git-durability-at-activation)+### git_home_required++<a id="git_home_required"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A git-canonical source would store content in the database without a file in Git; nothing was written. | On a source with canonical: git, page content reaches the database only after Git commits its file. The declared database-only classes (private, alias-private and lineage-private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores, detached pages and origin twins) are the only exceptions. no_file_form: the write has no file and is in no declared class; declared_target: a publication would commit a file for a declared page; facts_lane: a writer with no file form yet. | Ask the user which git home to configure (a path Git tracks, or a storage.db_only directory in gbrain.yml), then submit the write again with a new request_id. | agent | `repeat the read that failed` | 1 | no |++Reasons: `no_file_form`, `declared_target`, `facts_lane`.++More: [docs/guides/write-refusals.md#git_home_required](../../docs/guides/write-refusals.md#git_home_required)+### git_index_locked<a id="git_index_locked"></a>@@ -1703,6 +1715,18 @@ More: [docs/guides/concurrent-writes.md#git-durability-at-activation](../../docs|---|---|---|---|---|---|---|| Git index stale. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### git_lfs_not_enabled++<a id="git_lfs_not_enabled"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A git-canonical write falls under a Git LFS rule, but storage.git_lfs is off or the checkout does not configure the LFS filter; nothing was written. | The door commits a file before its database row. A path .gitattributes routes through Git LFS commits as an LFS pointer only when the checkout configures the LFS filter (git lfs install --local) and the operator opted in; otherwise the raw bytes would be committed. | Ask the user: configure git-lfs in the checkout and run gbrain config set storage.git_lfs true, or narrow the .gitattributes rule; then submit again with a new request_id. | agent | `repeat the read that failed` | 1 | no |++Reasons: `opt_in_off`, `checkout_unconfigured`.++More: [docs/guides/write-refusals.md#git_lfs_not_enabled](../../docs/guides/write-refusals.md#git_lfs_not_enabled)+### git_object_missing<a id="git_object_missing"></a>@@ -1723,6 +1747,28 @@ More: [docs/guides/write-refusals.md#git_object_missing](../../docs/guides/writeMore: [docs/guides/shared-checkout-git.md#stuck-rebase](../../docs/guides/shared-checkout-git.md#stuck-rebase)+### git_private_commit_refused++<a id="git_private_commit_refused"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A git-canonical source refused to commit the file of a private, alias-private or lineage-private page; nothing was written and HEAD is unchanged. | Private pages of a source with canonical: git are database-only: their bytes never enter Git history. A page turning private is published as the door commit that removes its file, never as a commit of its bytes. | The page stays database-only. Write it through put_page (which publishes a private page without a file), or remove visibility: private if it belongs in Git, then submit again with a new request_id. | agent | `repeat the read that failed` | 1 | no |++Reasons: `private`, `alias_private`, `lineage_private`.++More: [docs/guides/write-refusals.md#git_private_commit_refused](../../docs/guides/write-refusals.md#git_private_commit_refused)++### git_protocol_required++<a id="git_protocol_required"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A write reached a git-canonical source from a process that does not declare the git-canonical protocol (an older gbrain, or gbrain.write_sources set by hand); nothing was written. | Only the operator of the brain host can change what blocks this. | Upgrade or stop the gbrain process that wrote it (gbrain upgrade on its host), then retry with a new request_id. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/guides/write-refusals.md#git_protocol_required](../../docs/guides/write-refusals.md#git_protocol_required)+### git_push_unavailable<a id="git_push_unavailable"></a>diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 0b7960234c..f5b6507bc8 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -883,6 +883,23 @@ other operations to get around it.real credential reached the brain, rotate it, then follow["If a secret reached the brain"](../../SECURITY.md#if-a-secret-reached-the-brain).+## Git-canonical sources++A source with `config.canonical = "git"` (strict, set only by conversion; off for every source by default) commits each+page file to Git before its database row. Some pages keep no file on purpose: private, alias-private and lineage-private+pages (`database_only_reason` `private`, `alias_private`, `lineage_private`), pages under a `storage.db_only`+directory, derive-phase pages that never recorded a file, paths the checkout's Git ignores (`git_ignored`), detached+pages and origin twins. A write to one of them publishes database-only, with no commit and no Git effect. A page turning+private is published as a door commit that removes its file, and its recorded path is cleared in the same publication.+Earlier commits keep whatever was pushed before the change; gbrain never rewrites history.++| Code | What happened | What to do |+|---|---|---|+| <a id="git_home_required"></a>`git_home_required` | The write would store content in the database with no file in Git and is in no declared class (`no_file_form`), a publication would commit a file for a declared page (`declared_target`), or a writer with no file form yet wrote to the source (`facts_lane`). Nothing was written. | Ask the user which git home to configure: write the page to a path Git tracks, declare its directory under `storage.db_only` in `gbrain.yml`, or mark it `visibility: private`. `gbrain sources git-gap <source> --json` shows every page's class. Submit again with a new request ID. |+| <a id="git_private_commit_refused"></a>`git_private_commit_refused` | A publication would have committed the file bytes of a private, alias-private or lineage-private page. Nothing was written and `HEAD` is unchanged. A grouped publication refuses as a whole. | The page stays database-only. Write it with `put_page`, which publishes a private page without a file, or remove `visibility: private` if it belongs in Git. |+| <a id="git_protocol_required"></a>`git_protocol_required` | A database trigger refused a row on a strict source because the writing process does not declare the git-canonical protocol: an older gbrain, or `gbrain.write_sources` set by hand. Nothing was written. | Upgrade (`gbrain upgrade`) or stop every gbrain process that shares the database, then retry with a new request ID. |+| <a id="git_lfs_not_enabled"></a>`git_lfs_not_enabled` | The file falls under a Git LFS rule in `.gitattributes`, and either `storage.git_lfs` is off (`opt_in_off`, the default) or the checkout does not configure the LFS filter or git-lfs does not run (`checkout_unconfigured`). Nothing was written. | Ask the user. To store it with LFS: `git lfs install --local` in the checkout, then `gbrain config set storage.git_lfs true`. Otherwise narrow the `.gitattributes` rule. With the key on and LFS configured, the door commits the LFS pointer and the object goes to the checkout's LFS store; a publication that rolls back can leave an unreferenced object there, which is harmless. |+## Related- [Concurrent writes and durable receipts](concurrent-writes.md) — receipt states, retries, capacity limitsdiff --git a/scripts/build-schema.ts b/scripts/build-schema.tsindex 2d74b19d02..46af90354a 100644--- a/scripts/build-schema.ts+++ b/scripts/build-schema.ts@@ -47,6 +47,7 @@ import { CORE_EDIT_NOTICES_SCHEMA_SQL } from '../src/core/core-memory-schema.ts'import { FACT_PURGE_LOOKUP_INDEX_SQL, MEMORY_PURGE_SCHEMA_SQL } from '../src/core/facts/purge-schema.ts';import { WRITE_GATE_SCHEMA_SQL } from '../src/core/write-gate-schema.ts';import { BELIEF_LEDGER_SCHEMA_SQL } from '../src/core/belief/schema.ts';+import { GIT_CANONICAL_SCHEMA_SQL } from '../src/core/persistence/git-canonical-schema.ts';const REPO = resolve(import.meta.dir, '..');export const SCHEMA_SQL_PATH = 'src/schema.sql';@@ -115,6 +116,7 @@ export const FRAGMENTS: readonly Fragment[] = [{ source: 'src/core/write-gate-schema.ts', expr: 'WRITE_GATE_SCHEMA_SQL', postgres: WRITE_GATE_SCHEMA_SQL, pglite: WRITE_GATE_SCHEMA_SQL },{ source: 'src/core/questions/schema.ts', expr: 'PINNED_QUESTIONS_SCHEMA_SQL', postgres: PINNED_QUESTIONS_SCHEMA_SQL, pglite: PINNED_QUESTIONS_SCHEMA_SQL },{ source: 'src/core/belief/schema.ts', expr: 'BELIEF_LEDGER_SCHEMA_SQL', postgres: BELIEF_LEDGER_SCHEMA_SQL, pglite: BELIEF_LEDGER_SCHEMA_SQL },+ { source: 'src/core/persistence/git-canonical-schema.ts', expr: 'GIT_CANONICAL_SCHEMA_SQL', postgres: GIT_CANONICAL_SCHEMA_SQL, pglite: GIT_CANONICAL_SCHEMA_SQL },];const fragmentLabel = (f: Fragment) => `${f.source} (${f.expr})`;diff --git a/scripts/check-agent-contract.ts b/scripts/check-agent-contract.tsindex 70cd31d20c..ab8b51e8c7 100644--- a/scripts/check-agent-contract.ts+++ b/scripts/check-agent-contract.ts@@ -277,7 +277,9 @@ const READ_ONLY_SUBCOMMANDS = new Set(['config get', 'sources list', 'sources st// #6803: the stale-extraction preview returns before any write and reports the terminal counts (actionable, mention_due).'extract --stale --dry-run',// #7179: per-page search state; reads page, chunk, budget and hold rows plus Git objects, writes nothing.- 'pages status']);+ 'pages status',+ // G1/G7a: the git-gap census reads pages and Git objects in read-only transactions and writes nothing.+ 'sources git-gap']);function tsFiles(dir: string): string[] {if (!existsSync(dir)) return [];diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 69360009d3..c9471079a3 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 2009 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured)+src/core/config.ts 2010 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts)src/core/persistence/sync-run.ts 1682 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives)src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optiondiff --git a/src/commands/sources-git-gap.ts b/src/commands/sources-git-gap.tsindex c4da4138bc..c18375e9f1 100644--- a/src/commands/sources-git-gap.ts+++ b/src/commands/sources-git-gap.ts@@ -57,7 +57,7 @@ export interface GitGapCensus {database_ahead_without_import_record: number;/** git_ahead pages whose row also moved since its last import: both sides changed. */git_ahead_database_also_moved: number;- /** Pages of a source without a checkout that are not declared: nothing to compare them with. */+ /** Pages of a source without a checkout that are not declared. Since G7a such a source is declared `database_only_source`, so this stays 0; kept for readers of the JSON. */not_compared: number;/** Working-tree files of the pages that may have a tracked file, by their raw bytes against HEAD; null without a checkout. */worktree: Record<WorktreeState, number> | null;@@ -133,7 +133,8 @@ export async function censusGitGap(engine: BrainEngine, sourceId: string, opts:checkout = { root, head, mode: await scannerSlugRootMode(engine, sourceId, root), scope };}const census = emptyCensus(sourceId, root, checkout?.head ?? null);- const policy = { mirror, dbOnly: (slug: string) => root !== null && isSourceDbOnlySlug(root, slug, 'refuse'), ignored: new Set<string>() };+ // G7a: a source with no checkout is a database-only source, one declared class for all its pages (outside strict mode).+ const policy = { mirror, databaseOnlySource: root === null, dbOnly: (slug: string) => root !== null && isSourceDbOnlySlug(root, slug, 'refuse'), ignored: new Set<string>() };for (let cursor = '0'; ;) {if (opts.deadlineAt !== undefined && Date.now() >= opts.deadlineAt) { census.complete = false; break; }const done = await engine.transaction(async tx => {@@ -153,7 +154,7 @@ export async function censusGitGap(engine: BrainEngine, sourceId: string, opts:return census;}-interface BatchContext { checkout: Checkout | null; policy: { mirror: boolean; dbOnly: (slug: string) => boolean; ignored: Set<string> }; incarnation: string; sample: number }+interface BatchContext { checkout: Checkout | null; policy: { mirror: boolean; databaseOnlySource: boolean; dbOnly: (slug: string) => boolean; ignored: Set<string> }; incarnation: string; sample: number }function note(census: GitGapCensus, limit: number, item: GitGapSample): void {if (census.sample.length < limit) census.sample.push(item);@@ -299,7 +300,7 @@ const counts = (record: Record<string, number>) => Object.entries(record).filterexport function describeGitGap(census: GitGapCensus): string {const lines = [`Git gap of source ${census.source_id} (read-only): ${census.pages} live page(s)${census.head ? `, compared with HEAD ${census.head.slice(0, 12)}` : ''}.`];- if (!census.checkout) lines.push(`The source has no checkout, so ${census.not_compared} page(s) were not compared.`);+ if (!census.checkout) lines.push(`The source has no checkout: a database-only source, so its page(s) are declared database_only_source and none were compared.`);else if (!census.head) lines.push('The checkout has no commit yet, so no page has a committed file.');lines.push(`Pages: ${counts(census.states)}.`, `Declared database-only: ${counts(census.declared)}${census.declared_with_head_blob ? ` (${census.declared_with_head_blob} still committed at HEAD)` : ''}.`);if (census.database_ahead_without_import_record) lines.push(`${census.database_ahead_without_import_record} database_ahead page(s) have no import record, so the side that moved is unknown.`);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 63bc53cc6a..2258ffcacc 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1246,6 +1246,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.437.0', text: 'A chat-connector cookie or token holding a line break, NUL, another control character or a non-ASCII character is refused before any request (`invalid_header_value`): `connectors auth` reports it and `connectors sync` returns `auth_required` with that hint and stamps the auth error. A request that fails before a response is reported by its error code (`ECONNREFUSED`, `TypeError`), never by the runtime\'s message, so a header value can never be echoed into probe output, sync hints or logs (#7483).' },// GBRA-133 G2 (superseded remote blobs). `since` is stamped at the merge slot.{ since: '0.60.438.0', text: '`gbrain git commit-push` now keeps this machine\'s version of a file the remote changed back to a version this checkout already had at that path and later replaced (a stale clone or writer pushing an old copy, often inside a merge), instead of stopping with `integrate_conflict`. It reads the last 200 commits that changed the file. The push lists those files in `superseded_remote_paths` and the merge message names them. A version this checkout never had, a remote deletion and a file named with `--resolve` still conflict; when both kinds meet, `integrate_conflict` lists only the real conflicts and `detail.superseded` names the others.' },+ // GBRA-95 G7a (declared database-only classes). `since` is stamped at the merge slot.+ { since: 'TBD', id: 'git_canonical_declared_classes', text: '`gbrain sources git-gap` now declares every page of a source without a checkout `database_only_source` instead of counting it as not compared. On a git-canonical source (`config.canonical = "git"`, off by default and set by nothing yet), private, alias-private and lineage-private pages, `storage.db_only` directories, never-filed derive folders and ignored paths keep no file in Git (no file, no commit, no Git effect), a page turning private is published as the commit that removes its file, and a write that would commit a private page (`git_private_commit_refused`), store an undeclared page without a file (`git_home_required`), commit a file under an LFS rule without `storage.git_lfs` (`git_lfs_not_enabled`) or come from a writer without the git protocol (`git_protocol_required`) is refused.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/config.ts b/src/core/config.tsindex 06a7ead68d..46919907bf 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1517,6 +1517,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// didn't specify one: 'private' (default) | 'world'. Resolved by// src/core/facts/visibility.ts; explicit caller values always win.'facts.default_visibility',+ 'storage.git_lfs', // G7a: a git-canonical door commit under a Git LFS rule commits the LFS pointer; default off refuses it (persistence/git-declared.ts)'visibility.honor_aliases', // remote page reads honor `access`/`confidentiality` aliases on pages without `visibility`; default on, false opts out (search/private-visibility.ts)'facts.entity_inference', // #5836: write-time subject inference kill switch (subject-infer.ts)'facts.candidate_fusion', // C2: 'rrf_free' (default, cosine arm) | 'interleave' (cosine + keyword; facts/single-prepare.ts)diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5a7fc69010..a7995f3dfb 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -329,6 +329,10 @@ export const CODES = {git_target_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },git_unavailable: { class: 'retryable', summary: "A git command did not complete." },git_object_missing: { class: 'caller', summary: "A committed file's Git object is missing from the checkout and its working-tree copy differs or is gone, so managed sync holds that file alone.", why: "An interrupted gc, a partial clone without its promisor remote or disk corruption can drop an object a commit still names. Sync imports the working-tree bytes when they hash to the committed blob id; otherwise it imports nothing from a guess, and the rest of the source keeps syncing.", docs: 'docs/guides/write-refusals.md#git_object_missing', suggestion: 'Run git fsck in the checkout to see what is missing, restore it with git fetch (a partial or shallow clone) or from a backup, then sync again; every sync re-tests the hold.' },+ git_home_required: { class: 'caller', summary: "A git-canonical source would store content in the database without a file in Git; nothing was written.", reasons: ['no_file_form', 'declared_target', 'facts_lane'], why: "On a source with canonical: git, page content reaches the database only after Git commits its file. The declared database-only classes (private, alias-private and lineage-private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores, detached pages and origin twins) are the only exceptions. no_file_form: the write has no file and is in no declared class; declared_target: a publication would commit a file for a declared page; facts_lane: a writer with no file form yet.", docs: 'docs/guides/write-refusals.md#git_home_required', suggestion: 'Ask the user which git home to configure (a path Git tracks, or a storage.db_only directory in gbrain.yml), then submit the write again with a new request_id.' },+ git_private_commit_refused: { class: 'caller', summary: "A git-canonical source refused to commit the file of a private, alias-private or lineage-private page; nothing was written and HEAD is unchanged.", reasons: ['private', 'alias_private', 'lineage_private'], why: "Private pages of a source with canonical: git are database-only: their bytes never enter Git history. A page turning private is published as the door commit that removes its file, never as a commit of its bytes.", docs: 'docs/guides/write-refusals.md#git_private_commit_refused', suggestion: 'The page stays database-only. Write it through put_page (which publishes a private page without a file), or remove visibility: private if it belongs in Git, then submit again with a new request_id.' },+ git_protocol_required: { class: 'host_only', summary: "A write reached a git-canonical source from a process that does not declare the git-canonical protocol (an older gbrain, or gbrain.write_sources set by hand); nothing was written.", docs: 'docs/guides/write-refusals.md#git_protocol_required', suggestion: 'Upgrade or stop the gbrain process that wrote it (gbrain upgrade on its host), then retry with a new request_id.' },+ git_lfs_not_enabled: { class: 'caller', summary: "A git-canonical write falls under a Git LFS rule, but storage.git_lfs is off or the checkout does not configure the LFS filter; nothing was written.", reasons: ['opt_in_off', 'checkout_unconfigured'], why: "The door commits a file before its database row. A path .gitattributes routes through Git LFS commits as an LFS pointer only when the checkout configures the LFS filter (git lfs install --local) and the operator opted in; otherwise the raw bytes would be committed.", docs: 'docs/guides/write-refusals.md#git_lfs_not_enabled', suggestion: 'Ask the user: configure git-lfs in the checkout and run gbrain config set storage.git_lfs true, or narrow the .gitattributes rule; then submit again with a new request_id.' },gitlink_not_followed: { class: 'caller', summary: "A classic sync range added a gitlink (a submodule or an embedded repository); sync does not follow it, so the linked repository's files are not indexed.", why: "A gitlink records another repository's commit, not files, and that repository may be absent or uninitialized. The rest of the source syncs; the notice (`gitlinks_not_followed` in the result and one stderr line) comes once, in the run that passes the gitlink.", docs: 'docs/guides/write-refusals.md#gitlink_not_followed', suggestion: 'Nothing is blocked. To index the linked repository, check it out and add the checkout as its own source (gbrain sources add <name> --path <checkout>).' },graduation_drain_timeout: { class: 'retryable', summary: "Queued or running writes did not drain within --drain-timeout; the move stopped before copying and the source is unchanged.", docs: 'docs/guides/move-to-postgres.md#drain', reasons: ['progressing', 'blocked'], exit: 11 },graduation_embedding_dimension_mismatch: { class: 'caller', summary: "An existing, non-empty target database has a different embedding column layout than the brain being moved.", docs: 'docs/guides/move-to-postgres.md#embeddings' },diff --git a/src/core/persistence/context.ts b/src/core/persistence/context.tsindex 7e204ac334..56ba6393be 100644--- a/src/core/persistence/context.ts+++ b/src/core/persistence/context.ts@@ -60,10 +60,12 @@ export async function withCoordinatedWrite<T>(engine: BrainEngine, sourceIds: st// #6007: the persistence identity, the enclosing settings and the new settings in one round trip;// nothing is set when the identity row is missing. The OFFSET 0 subquery reads the enclosing values first.// A declared trust tier nests as min(outer, inner) (ranks compared in SQL); an undeclared one leaves the enclosing settings.- const names = ['gbrain.write_sources', ...ATTRIBUTION_SETTINGS, ...TRUST_SETTINGS];+ // G7a: `gbrain.git_protocol` declares that this build applies the git-canonical rules (git-declared.ts); the managed+ // writer guard refuses rows of a git-canonical source from a writer without it (an older gbrain).+ const names = ['gbrain.write_sources', ...ATTRIBUTION_SETTINGS, ...TRUST_SETTINGS, 'gbrain.git_protocol'];const [tier, origin] = trustValues(attribution.trust ?? null);const [brain] = await engine.executeRaw<Record<string, string | null>>(`SELECT b.brain_id,prev.*,- CASE WHEN b.brain_id IS NOT NULL THEN concat(set_config('gbrain.write_sources',$1,true),+ CASE WHEN b.brain_id IS NOT NULL THEN concat(set_config('gbrain.write_sources',$1,true),set_config('gbrain.git_protocol','1',true),set_config('gbrain.write_request',CASE WHEN prev.s2<>'' THEN prev.s1 ELSE $2 END,true),set_config('gbrain.write_principal_kind',CASE WHEN prev.s2<>'' THEN prev.s2 ELSE $3 END,true),set_config('gbrain.write_principal_id',CASE WHEN prev.s2<>'' THEN prev.s3 ELSE $4 END,true),diff --git a/src/core/persistence/git-canonical-schema.ts b/src/core/persistence/git-canonical-schema.tsnew file mode 100644index 0000000000..d5ad1fcb3c--- /dev/null+++ b/src/core/persistence/git-canonical-schema.ts@@ -0,0 +1,43 @@+/**+ * Git-canonical memory, wave G7a: the fast path of the git-canonical database fence. `git_canonical_brain.strict_sources`+ * counts the sources whose row says `config.canonical = "git"`, kept by row triggers on `sources` that fire only when+ * that key changes (or a strict row is inserted or deleted), so routine source updates never touch it. The fence itself is+ * a branch of the managed writer guard (writer-guard-schema.ts): while the count is zero it costs one indexed probe and+ * refuses nothing. Shared by migration v271 and both schema blobs (`bun run build:schema`).+ *+ * Additive: no page or source row is read for anything but the count, and nothing is backfilled or rewritten. RLS is+ * enabled on the counter as on every public table (doctor `rls`), only when the role bypasses it (the page-body pattern).+ */+export const GIT_CANONICAL_SCHEMA_SQL = `+CREATE TABLE IF NOT EXISTS git_canonical_brain (+ singleton INTEGER PRIMARY KEY DEFAULT 1 CHECK (singleton = 1),+ strict_sources INTEGER NOT NULL DEFAULT 0 CHECK (strict_sources >= 0)+);+CREATE OR REPLACE FUNCTION gbrain_count_git_canonical_sources() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$+BEGIN+ INSERT INTO git_canonical_brain(singleton, strict_sources)+ VALUES (1, (SELECT count(*) FROM sources WHERE config->>'canonical' = 'git'))+ ON CONFLICT (singleton) DO UPDATE SET strict_sources = EXCLUDED.strict_sources;+ RETURN NULL;+END $fn$;+DROP TRIGGER IF EXISTS git_canonical_sources_count_insert ON sources;+CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON sources+ FOR EACH ROW WHEN (NEW.config->>'canonical' = 'git') EXECUTE FUNCTION gbrain_count_git_canonical_sources();+DROP TRIGGER IF EXISTS git_canonical_sources_count_update ON sources;+CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON sources+ FOR EACH ROW WHEN (OLD.config->>'canonical' IS DISTINCT FROM NEW.config->>'canonical') EXECUTE FUNCTION gbrain_count_git_canonical_sources();+DROP TRIGGER IF EXISTS git_canonical_sources_count_delete ON sources;+CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON sources+ FOR EACH ROW WHEN (OLD.config->>'canonical' = 'git') EXECUTE FUNCTION gbrain_count_git_canonical_sources();+INSERT INTO git_canonical_brain(singleton, strict_sources)+ VALUES (1, (SELECT count(*) FROM sources WHERE config->>'canonical' = 'git'))+ ON CONFLICT (singleton) DO UPDATE SET strict_sources = EXCLUDED.strict_sources;+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))+ AND EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relname = 'git_canonical_brain' AND c.relkind = 'r' AND NOT c.relrowsecurity) THEN+ ALTER TABLE git_canonical_brain ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+`;diff --git a/src/core/persistence/git-declared.ts b/src/core/persistence/git-declared.tsnew file mode 100644index 0000000000..89a325eee4--- /dev/null+++ b/src/core/persistence/git-declared.ts@@ -0,0 +1,235 @@+/**+ * Git-canonical memory, wave G7a (docs/designs/GIT_CANONICAL_MEMORY.md, "Declared database-only classes"): which pages of+ * a strict source (`sources.config.canonical = "git"`, set only by conversion) keep no file in Git on purpose, and the+ * refusal for anything else that would land in the database alone.+ *+ * - **Classification** (`strictPageClass`): a page under a `storage.db_only` prefix, a derive-phase page that never+ * recorded a file (G1's per-page rule), or a private, alias-private or lineage-private page is declared database-only.+ * A file target the checkout's Git ignores is declared `git_ignored`. page-prepare.ts `prepareFileTarget` asks this+ * before it builds a file target, so such a page gets no file, no door commit and no Git effect; a page turning private+ * gets a removal that the door commits.+ * - **Private backstop** (`assertNoPrivateCommit`, before a publication writes its file): a file target carrying a+ * private page's bytes is refused (`git_private_commit_refused`), whatever writer prepared it.+ * - **Publication check** (`declareStrictPublication`, called by publishMutation and publishGroup after apply, before+ * the door commit): a strict publication that writes no file must be declared (else `git_home_required`), one that+ * writes a file must not be (`declared_target`). It stamps `pages.database_only_reason` with the class+ * (`private`, `alias_private`, `lineage_private`, `git_ignored`) and, for the privacy classes, clears the recorded+ * origin in the same transaction as the door commit that removed the file, so the indexer never reads that removal as+ * a deletion of a live page.+ * - **LFS** (`assertLfsTarget`): a target whose `filter` attribute is `lfs` commits only when the operator opted in+ * (`storage.git_lfs`, default off) and the checkout configures the LFS filter itself; the door's `hash-object -w` applies+ * that clean filter and commits the pointer.+ *+ * Nothing here runs for a source without the flag or for an unbound write (a database-only source is its own class).+ */+import { promisify } from 'node:util';+import { join, relative, sep } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { gitChildEnv } from '../git-env.ts';+import type { Action } from '../agent-output.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { execFile } from '../spawn.ts';+import { isDerivationPrivate, isPrivatePage, privatePagesFilterFragment, readHonorAliases } from '../search/private-visibility.ts';+import { DERIVE_PHASE_DB_ONLY_DEFAULTS } from '../storage-config.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import type { PageMutationFile } from './coordinator.ts';+import type { WriteRequest } from './model.ts';+import type { WorktreeBinding } from './ownership.ts';+import { isSourceDbOnlySlug } from './source-storage.ts';+import { gitIgnoresUntracked } from './sync-origin-evidence.ts';+import { isStreamedContent, type StreamedFileContent } from './large-file.ts';+import { parseMarkdown } from '../markdown.ts';++const execFileAsync = promisify(execFile);+const DOCS = 'docs/guides/write-refusals.md#git_home_required';++/** The `database_only_reason` values G7a stamps, one per declared class that is not computed from the slug or config. */+export const DECLARED_REASONS = ['private', 'alias_private', 'lineage_private', 'git_ignored'] as const;+export type DeclaredReason = typeof DECLARED_REASONS[number];+export type PrivacyClass = 'private' | 'alias_private' | 'lineage_private';+export type StrictClass = PrivacyClass | 'db_only_prefix' | 'derive_folder' | 'git_ignored' | 'database_only';+const PRIVACY: ReadonlySet<string> = new Set<PrivacyClass>(['private', 'alias_private', 'lineage_private']);+/** A reason a publication or page already carries that declares it database-only (detached pages, origin twins, mirrors...): any but the generic `db_only` and G7a's own. */+const legacyReason = (value: string | null | undefined) => value != null && value !== 'db_only' && !isDeclaredReason(value);++export const isPrivacyClass = (value: string | null | undefined): value is PrivacyClass => value != null && PRIVACY.has(value);+export const isDeclaredReason = (value: string | null | undefined): value is DeclaredReason => value != null && (DECLARED_REASONS as readonly string[]).includes(value);++/** A derive-phase page (DERIVE_PHASE_DB_ONLY_DEFAULTS) that never recorded a canonical file. */+export function isNeverFiledDerivedPage(slug: string, page: { source_path?: string | null; source_uri?: string | null }): boolean {+ return !page.source_path && !page.source_uri && DERIVE_PHASE_DB_ONLY_DEFAULTS.some(prefix => slug.startsWith(prefix));+}++/**+ * The class G3's indexer reads for a page's path: `db_only_prefix` (a `storage.db_only` dir, folder-wide) or+ * `derive_folder` (a derive-phase page that never recorded a file), else null. A committed file under a derive folder+ * belongs to Git, so a page that records one is never `derive_folder`.+ */+export function declaredPathClass(root: string, slug: string, page: { source_path?: string | null; source_uri?: string | null } | null): 'db_only_prefix' | 'derive_folder' | null {+ if (isSourceDbOnlySlug(root, slug, 'refuse')) return 'db_only_prefix';+ return isNeverFiledDerivedPage(slug, page ?? {}) ? 'derive_folder' : null;+}++/**+ * Why a page is private, or null: its own fields (`visibility`, a pinned question, the derived-type default), a privacy+ * alias (with `visibility.honor_aliases` read first), or its declared lineage and derived origin, read with the same SQL+ * remote reads use (`privatePagesFilterFragment`) over the page's own values, so an unwritten page is judged too.+ */+export async function privacyClass(engine: BrainEngine, sourceId: string, page: { id?: number | null; slug: string; type?: string | null; frontmatter?: unknown }): Promise<PrivacyClass | null> {+ await readHonorAliases(engine);+ if (isPrivatePage(page)) return 'private';+ if (isDerivationPrivate(page)) return 'alias_private';+ const frontmatter = typeof page.frontmatter === 'object' && page.frontmatter !== null ? page.frontmatter as Record<string, unknown> : {};+ if (frontmatter.derived_from == null && !['atom', 'concept', 'event'].includes(page.type ?? '')) return null;+ const [row] = await engine.executeRaw<{ lineage: boolean }>(`SELECT NOT ${privatePagesFilterFragment('p')} AS lineage+ FROM (SELECT $1::text AS source_id, $2::text AS slug, $3::text AS type, $4::text::jsonb AS frontmatter, $5::bigint AS id) p`,+ [sourceId, page.slug, page.type ?? null, JSON.stringify(frontmatter), page.id ?? null]);+ return row?.lineage === true ? 'lineage_private' : null;+}++/** The declared class a strict page belongs to by its slug, its prior file and its content, or null when it belongs in Git. */+export async function strictPageClass(engine: BrainEngine, sourceId: string, root: string,+ page: { id?: number | null; slug: string; type?: string | null; frontmatter?: unknown }, before: { source_path?: string | null; source_uri?: string | null } | null): Promise<StrictClass | null> {+ return declaredPathClass(root, page.slug, before) ?? await privacyClass(engine, sourceId, page);+}++const rel = (root: string, path: string) => relative(root, path).split(sep).join('/');++/** Whether the checkout ignores `path` and does not track it, so Git could never commit a file there. */+export function ignoredTarget(root: string, path: string): Promise<boolean> {+ return gitIgnoresUntracked(root, rel(root, path));+}++async function git(root: string, args: string[]): Promise<{ code: number; stdout: string }> {+ try {+ const { stdout } = await execFileAsync('git', ['-c', 'core.quotepath=false', '-C', root, ...args], { env: gitChildEnv(), encoding: 'utf8', timeout: 30_000, maxBuffer: 1024 * 1024 });+ return { code: 0, stdout };+ } catch (error) {+ const e = error as { code?: unknown; stdout?: unknown };+ return { code: typeof e.code === 'number' ? e.code : -1, stdout: typeof e.stdout === 'string' ? e.stdout : '' };+ }+}++export const GIT_LFS_KEY = 'storage.git_lfs';+const ON = /^(true|1|on|yes)$/i;++/**+ * Whether a door commit of the file at `path` may run under LFS rules. Null when the path's `filter` attribute is not+ * `lfs` (the ordinary case: one `check-attr`). Otherwise `ready` only when the operator opted in (`storage.git_lfs`) and+ * the checkout's own config names the LFS filter (`filter.lfs.process` or `filter.lfs.clean`) and `git lfs` runs: the+ * door's child Git keeps repo-local config and PATH, so its `hash-object -w` commits the pointer and stores the object.+ * That hash runs before the door's ref update, so a publication that rolls back can leave the object in the LFS store,+ * which is harmless (an unreferenced LFS object).+ */+export async function lfsTargetState(engine: Pick<BrainEngine, 'getConfig'>, root: string, path: string): Promise<null | 'opt_in_off' | 'checkout_unconfigured' | 'ready'> {+ const attr = await git(root, ['check-attr', '-z', 'filter', '--', rel(root, path)]);+ if (attr.code !== 0 || attr.stdout.split('\0')[2] !== 'lfs') return null;+ if (!ON.test((await engine.getConfig(GIT_LFS_KEY))?.trim() ?? '')) return 'opt_in_off';+ const [process, clean, binary] = await Promise.all([git(root, ['config', '--local', '--get', 'filter.lfs.process']),+ git(root, ['config', '--local', '--get', 'filter.lfs.clean']), git(root, ['lfs', 'version'])]);+ return (process.code === 0 || clean.code === 0) && binary.code === 0 ? 'ready' : 'checkout_unconfigured';+}++/** Refuses a strict file target under an LFS rule unless `lfsTargetState` says ready. */+export async function assertLfsTarget(engine: Pick<BrainEngine, 'getConfig'>, row: Pick<WriteRequest, 'source_id' | 'slug'>, root: string, path: string, remote: boolean): Promise<void> {+ const state = await lfsTargetState(engine, root, path);+ if (state === null || state === 'ready') return;+ const where = remote ? `page ${row.slug}'s file` : rel(root, path);+ const why = 'A git-canonical source commits a file before its database row. A path .gitattributes routes through Git LFS commits as an LFS pointer only when the checkout configures the LFS filter and the operator opted in; otherwise the door would commit the raw bytes.';+ throw opError('git_lfs_not_enabled', state === 'opt_in_off'+ ? `Source ${row.source_id} is git-canonical and ${where} falls under a Git LFS rule, but ${GIT_LFS_KEY} is off, so nothing was written.`+ : `Source ${row.source_id} is git-canonical and ${where} falls under a Git LFS rule, but the checkout does not configure the LFS filter (git lfs install --local) or git-lfs does not run, so nothing was written.`,+ 'Ask the user whether this file belongs in Git LFS. If it does, they configure git-lfs in the checkout and turn on storage.git_lfs, then the write is submitted again with a new request_id; if not, they narrow the .gitattributes rule.',+ { reason: state, why, docs: 'docs/guides/write-refusals.md#git_lfs_not_enabled', fix: { ask_user: true, actor: 'user', consent: [], requires_exclusive: false, why,+ user_message: `A write to source ${row.source_id} falls under a Git LFS rule in .gitattributes. Should it be stored with Git LFS? If so, configure git-lfs in the checkout (git lfs install --local) and run gbrain config set ${GIT_LFS_KEY} true on the brain host; otherwise narrow the .gitattributes rule.`,+ verify: { argv: ['gbrain', 'config', 'get', GIT_LFS_KEY] } } });+}++/**+ * The refusal for content a strict source would hold in the database alone (`no_file_form`, `facts_lane`), or for a+ * file a strict publication would commit for a declared page (`declared_target`). Remote callers get no class.+ */+export function gitHomeRequired(row: Pick<WriteRequest, 'source_id' | 'slug'>, reason: 'no_file_form' | 'declared_target' | 'facts_lane', remote: boolean, declared?: StrictClass): OperationError {+ const why = 'Git is the source of truth for a git-canonical source: page content reaches the database only after Git commits its file, except for the declared database-only classes (private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores).';+ const message = reason === 'declared_target'+ ? `Source ${row.source_id} is git-canonical and page ${row.slug} is declared database-only${remote || !declared ? '' : ` (${declared})`}, so its file is never committed; nothing was written.`+ : `Source ${row.source_id} is git-canonical and this write would store ${reason === 'facts_lane' ? 'rows' : `page ${row.slug}`} in the database without a file in Git, so nothing was written.`;+ const fix: Action = { ask_user: true, actor: 'user', consent: [], requires_exclusive: false, why, docs: DOCS,+ user_message: reason === 'declared_target'+ ? `Page ${row.slug} in git-canonical source ${row.source_id} is declared database-only, so gbrain will not commit its file. Should it stay database-only, or move to a path Git tracks (outside storage.db_only and the derive folders, and not private)?`+ : `Source ${row.source_id} is git-canonical, so every page needs a home in Git. Should ${reason === 'facts_lane' ? 'these rows' : `page ${row.slug}`} be written to a file Git tracks, or declared database-only (its directory under storage.db_only in gbrain.yml, or the page marked visibility: private)?`,+ verify: { argv: ['gbrain', 'sources', 'git-gap', row.source_id, '--json'] } };+ return opError('git_home_required', message, 'Ask the user which git home to configure, then submit the write again with a new request_id.', { reason, why, fix, docs: DOCS });+}++/** The page a strict file target publishes, judged for its class; streamed content keeps the snapshot's frontmatter. */+export function renderedPageForClass(slug: string, content: string | Uint8Array | StreamedFileContent, snapshot: PageSnapshot | null): { id: number | null; slug: string; type: string | null; frontmatter: unknown } {+ if (isStreamedContent(content)) return { id: snapshot?.page.id ?? null, slug, type: snapshot?.page.type ?? null, frontmatter: snapshot?.page.frontmatter };+ const parsed = parseMarkdown(typeof content === 'string' ? content : Buffer.from(content).toString('utf8'), `${slug}.md`);+ return { id: snapshot?.page.id ?? null, slug, type: parsed.typeExplicit ? parsed.type : snapshot?.page.type ?? parsed.type, frontmatter: parsed.frontmatter };+}++/** The refusal for a publication that would commit a private page's bytes: the page stays database-only. */+export function privateCommitRefused(row: Pick<WriteRequest, 'source_id' | 'slug'>, privacy: PrivacyClass, remote: boolean): OperationError {+ const why = 'Private, alias-private and lineage-private pages of a git-canonical source are database-only: their bytes never enter Git history. A page turning private is published as the door commit that removes its file.';+ return opError('git_private_commit_refused', `Source ${row.source_id} is git-canonical and page ${row.slug} is ${privacy.replace('_', '-')}, so its file was not committed; nothing was written and HEAD is unchanged.`,+ 'The page stays database-only: write it with put_page, which publishes a private page without a file, or remove visibility: private if it belongs in Git, then submit again with a new request_id.',+ { reason: privacy, why, docs: 'docs/guides/write-refusals.md#git_private_commit_refused', fix: { ask_user: true, actor: 'user', consent: [], requires_exclusive: false, why,+ user_message: `Page ${row.slug} in git-canonical source ${row.source_id} is private, so it stays database-only and gbrain will not commit its file. Should it stay private (written database-only), or become public so its file is committed?`,+ verify: { argv: ['gbrain', 'sources', 'git-gap', row.source_id, '--json'] } } });+}++/** What the publication checks read of a prepared publication: its file target, noop flag and database-only reason. */+type StrictPublication = { noop?: boolean; databaseOnlyReason?: string; file?: Pick<PageMutationFile, 'content'> };++const syncRow = (row: Pick<WriteRequest, 'operation' | 'intent'>) => row.operation === 'submit_job' && /^managed_sync_/.test(String(row.intent?.kind ?? ''));++/**+ * Before a strict publication writes or commits anything: refuses one whose file target carries the bytes of a private,+ * alias-private or lineage-private page, judged from those bytes (the page as it will be published). A removal is the+ * private transition and passes. Sync members are G3's.+ */+export async function assertNoPrivateCommit(tx: BrainEngine, row: WriteRequest, prepared: StrictPublication, snapshot: PageSnapshot | null,+ binding: Pick<WorktreeBinding, 'canonical_git'> | null | undefined): Promise<void> {+ if (binding?.canonical_git !== true || !row.worktree_id || prepared.noop || !prepared.file || prepared.file.content === null || syncRow(row)) return;+ const privacy = await privacyClass(tx, row.source_id, renderedPageForClass(row.slug, prepared.file.content, snapshot));+ if (privacy) throw privateCommitRefused(row, privacy, row.authority?.remote === true);+}++/** For writers with no file form yet (G4, G5): refuses on a strict source, so a database-only row is never written there. */+export async function assertStrictGitHome(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'slug'>, remote: boolean): Promise<void> {+ const [source] = await engine.executeRaw<{ strict: boolean }>(`SELECT COALESCE(config->>'canonical','')='git' AS strict FROM sources WHERE id=$1`, [row.source_id]);+ if (source?.strict === true) throw gitHomeRequired(row, 'facts_lane', remote);+}++/**+ * The publication check and stamp (see the header). `before` is the page as the publication read it under its page+ * lock, `final` after apply. Runs before the door commit, inside the publication transaction; a no-op unless the+ * binding is strict and the write is bound. Sync members are G3's (the indexer imports what Git holds).+ */+export async function declareStrictPublication(tx: BrainEngine, row: WriteRequest, prepared: StrictPublication,+ before: PageSnapshot | null, final: PageSnapshot | null, binding: Pick<WorktreeBinding, 'canonical_git' | 'local_path' | 'relative_path'> | null | undefined): Promise<void> {+ if (binding?.canonical_git !== true || !binding.local_path || !row.worktree_id || prepared.noop || !final || final.page.deleted_at) return;+ if (syncRow(row)) return;+ const [stored] = await tx.executeRaw<{ reason: string | null }>('SELECT database_only_reason AS reason FROM pages WHERE id=$1', [final.page.id]);+ const reason = stored?.reason ?? null;+ const root = join(binding.local_path, binding.relative_path ?? '');+ const page = final.page;+ const remote = row.authority?.remote === true;+ if (prepared.file && prepared.file.content !== null) {+ const declared = await strictPageClass(tx, row.source_id, root, page, before?.page ?? null);+ if (isPrivacyClass(declared)) throw privateCommitRefused(row, declared, remote);+ if (declared) throw gitHomeRequired(row, 'declared_target', remote, declared);+ if (isDeclaredReason(reason)) await tx.executeRaw('UPDATE pages SET database_only_reason=NULL WHERE id=$1', [page.id]);+ return;+ }+ const declared: StrictClass | null = legacyReason(prepared.databaseOnlyReason) || legacyReason(reason) ? 'database_only'+ : await strictPageClass(tx, row.source_id, root, page, before?.page ?? null)+ ?? (await ignoredTarget(root, join(root, page.source_path || `${page.slug}.md`)) ? 'git_ignored' : null);+ if (!declared) throw gitHomeRequired(row, 'no_file_form', remote);+ if (isPrivacyClass(declared)) {+ await tx.executeRaw('UPDATE pages SET database_only_reason=$2, source_path=NULL, source_uri=NULL WHERE id=$1', [page.id, declared]);+ } else if (declared === 'git_ignored' && reason !== 'git_ignored') {+ await tx.executeRaw('UPDATE pages SET database_only_reason=$2 WHERE id=$1', [page.id, declared]);+ }+}diff --git a/src/core/persistence/git-gap.ts b/src/core/persistence/git-gap.tsindex d95264f321..3dce854b58 100644--- a/src/core/persistence/git-gap.ts+++ b/src/core/persistence/git-gap.ts@@ -16,21 +16,22 @@ import { parseMarkdown } from '../markdown.ts';import { isDerivationPrivate, isPrivatePage } from '../search/private-visibility.ts';import { alignWithStored } from './align-stored.ts';import { digest } from './digest.ts';-import { isNeverFiledDerivedPage } from './page-prepare.ts';+import { isDeclaredReason, isNeverFiledDerivedPage } from './git-declared.ts';import { classifyDrift } from './reconcile-additive.ts';import { reconcileCanonical } from './reconcile-merge.ts';import { reconcileFileReading } from './reconcile-state.ts';/** Why a page has no tracked file on purpose, in the order `declaredDatabaseOnly` tests them. */-export const DECLARED_CLASSES = ['mirror_source', 'private', 'alias_private', 'lineage_private', 'database_only', 'db_only_prefix', 'derive_folder', 'git_ignored'] as const;+export const DECLARED_CLASSES = ['mirror_source', 'database_only_source', 'private', 'alias_private', 'lineage_private', 'database_only', 'db_only_prefix', 'derive_folder', 'git_ignored'] as const;export type DeclaredClass = typeof DECLARED_CLASSES[number];/*** What decides a declared class beyond the page itself: whether the source is a read-only mirror (sourceMirrorReadOnly),- * whether a slug sits under a `storage.db_only` dir (isSourceDbOnlySlug, which refuses an invalid gbrain.yml) and the- * paths the checkout's Git ignores.+ * whether the whole source is database-only (G7a: no checkout, so every write is unbound and outside strict mode), whether+ * a slug sits under a `storage.db_only` dir (isSourceDbOnlySlug, which refuses an invalid gbrain.yml) and the paths the+ * checkout's Git ignores.*/-export interface GitHomePolicy { mirror: boolean; dbOnly: (slug: string) => boolean; ignored: ReadonlySet<string> }+export interface GitHomePolicy { mirror: boolean; databaseOnlySource?: boolean; dbOnly: (slug: string) => boolean; ignored: ReadonlySet<string> }/*** Why a page may not have a tracked file, or null when it may. gbrain never writes a read-only mirror's checkout (#5409);@@ -43,9 +44,13 @@ export interface GitHomePolicy { mirror: boolean; dbOnly: (slug: string) => boolexport function declaredDatabaseOnly(page: { slug: string; type?: string | null; frontmatter?: unknown; database_only_reason?: string | null;lineage_private?: boolean; source_path?: string | null; source_uri?: string | null }, relativePath: string | null, policy: GitHomePolicy): DeclaredClass | null {if (policy.mirror) return 'mirror_source';+ if (policy.databaseOnlySource) return 'database_only_source';if (isPrivatePage(page)) return 'private';if (isDerivationPrivate(page)) return 'alias_private';if (page.lineage_private) return 'lineage_private';+ // G7a (git-declared.ts): a strict publication stamps the class it declared; one whose cause is gone (an origin turned+ // public, `visibility.honor_aliases` off, the ignore rule removed) keeps it until the page is written again.+ if (isDeclaredReason(page.database_only_reason)) return page.database_only_reason;if (page.database_only_reason) return 'database_only';if (policy.dbOnly(page.slug)) return 'db_only_prefix';if (isNeverFiledDerivedPage(page.slug, page)) return 'derive_folder';diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 2f0535393d..adad2276fd 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -20,6 +20,7 @@ import { OperationError, opError } from '../ops/contract.ts';import { CANONICAL_FILE_MISSING } from './publication-failure.ts';import { committedBlob, committedPendingImport, headBlob, pendingImportRefusal, SYNC_HELD } from './pending-import.ts';import { sourceCanonicalGit } from './git-door.ts';+import { assertLfsTarget, ignoredTarget, isNeverFiledDerivedPage, isPrivacyClass, renderedPageForClass, strictPageClass } from './git-declared.ts';import { readFix } from '../ops/op-fix.ts';import { isOpPageSlug } from '../ops/context.ts';import { shellQuote, type Action } from '../agent-output.ts';@@ -76,7 +77,6 @@ import { isSourceDbOnlySlug } from './source-storage.ts';import { gitIgnoresUntracked } from './sync-origin-evidence.ts';import { gitDurabilityPolicy } from './git-durability-policy.ts';import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';-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, parseEditWithin, parsePageEdits, prepareSegmentedEditMutation } from './page-edit.ts';@@ -150,10 +150,7 @@ function putProvenance(row: WriteRequest, snapshot: PageSnapshot | null, parsed:Object.assign(parsed.frontmatter, stamp);return stamp;}-/** A derive-phase page (DERIVE_PHASE_DB_ONLY_DEFAULTS) that never recorded a canonical file. */-export function isNeverFiledDerivedPage(slug: string, page: { source_path?: string | null; source_uri?: string | null }): boolean {- return !page.source_path && !page.source_uri && DERIVE_PHASE_DB_ONLY_DEFAULTS.some(prefix => slug.startsWith(prefix));-}+export { isNeverFiledDerivedPage };/*** A live page whose canonical file is absent publishes to the database only* when its slug is a declared db_only path or a never-filed derive-phase page.@@ -303,6 +300,19 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ// target file does not exist yet: an existing page keeps its file (and its drift checks and storage refusals), and only a// person's detach turns it database-only. A Git-durable source keeps writing the file: its Git effect cannot commit an// ignored target and parks it (`git_target_unsafe`), which already shows the page needs a decision.+ // G7a (git-declared.ts): on a strict source a declared database-only page gets no file to commit (no door commit, no Git+ // effect), a page turning private gets the removal of the file it still has, and a path under an LFS rule commits only+ // when the operator opted in and the checkout configures LFS. Removals are never refused: they move the database toward Git.+ if (binding.canonical_git === true && content !== null) {+ const declared = await strictPageClass(engine, row.source_id, root, renderedPageForClass(row.slug, content, snapshot), snapshot?.page ?? null)+ ?? (await waitingOnWhile(options.clock, 'git', () => ignoredTarget(root, path)) ? 'git_ignored' : null);+ if (declared) {+ if (!isPrivacyClass(declared) || !snapshot || snapshot.page.deleted_at) return undefined;+ if (!existsSync(path) && await headBlob(root, path) === null) return undefined;+ content = null;+ options = { ...options, deleting: true };+ } else await assertLfsTarget(engine, row, root, path, options.remote === true);+ }if (options.newPageIgnoredDatabaseOnly && !snapshot && content !== null && !existsSync(path) && !isSourceDbOnlySlug(root, row.slug, 'not_db_only') && await waitingOnWhile(options.clock, 'git', () => gitIgnoresUntracked(root, relative(root, path).split(sep).join('/')))&& !(await gitDurabilityPolicy(binding, root)).durable) return undefined;if (options.excludeTombstone && snapshot?.page.deleted_at) {@@ -341,8 +351,11 @@ async function compareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 's// missing still refuses below.if (publishesDatabaseOnly(root, row.slug, snapshot)) return undefined;if (options.deleting === true && content === null && !snapshot.page.source_path && !capturedPath) return undefined;- // G2: on a strict source a removal Git already holds (a replay after the door commit landed) completes in the database.- if (options.deleting === true && content === null && await sourceCanonicalGit(engine, row.source_id) && await headBlob(root, path) === null) return undefined;+ // G2: on a strict source a removal Git already holds (a replay after the door commit landed) completes in the database;+ // G7a: one whose file HEAD still holds (only the worktree copy is gone) is committed through the door.+ if (options.deleting === true && content === null && await sourceCanonicalGit(engine, row.source_id)) {+ return await headBlob(root, path) === null ? undefined : { path, root, content: null, expectedBeforeHash: null };+ }// #6696 (A12): tagged, so a producer can refuse this before admission and the receipt says which refusal it was.throw opError('source_changed', 'The canonical file was removed outside coordinated publication.','Import the local deletion or recover the canonical file before editing this page.', { detail: CANONICAL_FILE_MISSING });@@ -427,6 +440,17 @@ async function heldFileRefusal(engine: BrainEngine, row: Pick<WriteRequest, 'souexport function databaseOnlyPublication(row: Pick<WriteRequest, 'worktree_id'>, file: PreparedMutation['file']): Pick<PreparedMutation, 'databaseOnlyReason'> {return row.worktree_id && !file ? { databaseOnlyReason: 'db_only' } : {};}+/**+ * G7a: the file target of a strict page turning private (git-declared.ts): the removal of the file it still has in the+ * worktree or at HEAD, which the door commits. The publication then stamps `database_only_reason` and clears+ * `source_path`/`source_uri` in the same transaction (`declareStrictPublication`). Undefined when there is no file to+ * remove, the write is unbound, or the source is not strict (such a page publishes as before).+ */+export async function preparePrivateTransition(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, snapshot: PageSnapshot,+ options: { remote?: boolean; clock?: ClaimPhaseClock } = {}): Promise<PreparedMutation['file']> {+ if (!row.worktree_id || !await sourceCanonicalGit(engine, row.source_id)) return undefined;+ return prepareFileTarget(engine, row, snapshot, null, undefined, { ...options, deleting: true });+}export async function pageDatabaseOnlyPublication(engine: SqlEngine, row: WriteRequest, file: PreparedMutation['file']): Promise<Pick<PreparedMutation, 'databaseOnlyReason'>> {const reason = databaseOnlyPublication(row, file);if (reason.databaseOnlyReason && (await sourceMirrorReadOnly(engine, row.source_id) || await isMirrorOnlyPage(engine, row.source_id, row.slug))) {diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex c65379a7bb..4634d98294 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -65,6 +65,8 @@ export interface PublicationFailure { code: string; message: string; detail?: Puconst IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;const ident = (value: unknown) => typeof value === 'string' && IDENT.test(value) ? value : undefined;const GUARD_PREFIX = 'writer_coordinator_required:';+/** G7a (writer-guard-schema.ts): the guard's refusal of a git-canonical source's row from a writer without the git protocol. */+const GIT_PROTOCOL_PREFIX = 'git_protocol_required:';/** trust/schema.ts: the tier trigger's refusal of a raise without owner confirmation. */const TRUST_PREFIX = 'trust_raise_refused:';const PURGED_PREFIX = 'purged_content:';@@ -142,6 +144,10 @@ export function databaseRefusal(error: unknown): PublicationFailure | null {}if (message.startsWith(PURGED_PREFIX)) return { code: 'purged_content', message: `${message.slice(PURGED_PREFIX.length).trim()}. Nothing was committed.`,detail: { origin: 'database_trigger', sqlstate, ...(raiser ? { raiser } : {}), ...(table ? { table } : {}) } };+ if (message.startsWith(GIT_PROTOCOL_PREFIX) || constraint.startsWith('git_canonical_fence')) {+ return { code: 'git_protocol_required', detail: { origin: 'database_guard', sqlstate, raiser: raiser ?? 'gbrain_require_managed_writer', ...(table ? { table } : {}), ...guardDetail(e.detail) },+ message: `The git-canonical database fence refused a write${table ? ` on ${table}` : ''}: the source is git-canonical and this gbrain process does not declare the git protocol (an older gbrain). Nothing was committed.` };+ }if (message.startsWith(GUARD_PREFIX) || constraint.startsWith('managed_writer_guard')) {const branch = constraint.startsWith('managed_writer_guard:') ? ident(constraint.slice('managed_writer_guard:'.length)) : undefined;const detail: PublicationFailureDetail = { origin: 'database_guard', sqlstate, raiser: raiser ?? 'gbrain_require_managed_writer',diff --git a/src/core/persistence/writer-guard-schema.ts b/src/core/persistence/writer-guard-schema.tsindex 52035ebe27..1f8384fe75 100644--- a/src/core/persistence/writer-guard-schema.ts+++ b/src/core/persistence/writer-guard-schema.ts@@ -73,6 +73,14 @@ BEGINWHEN NOT (allowed ? target_source) THEN 'different_source' ELSE 'old_source_outside' END,'target_source',target_source,'old_source',old_source,'allowed',allowed)::text;END IF;+ -- G7a (git-canonical-schema.ts): a git-canonical source takes rows only from a writer that declares the git protocol.+ IF COALESCE(current_setting('gbrain.git_protocol',true),'') <> '1'+ AND EXISTS (SELECT 1 FROM git_canonical_brain WHERE singleton=1 AND strict_sources>0)+ AND EXISTS (SELECT 1 FROM sources WHERE id IN (target_source, old_source) AND config->>'canonical'='git') THEN+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='git_protocol_required: this source is git-canonical and the writer does not declare the git protocol',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='git_canonical_fence:mutation',+ DETAIL=jsonb_build_object('op',TG_OP,'target_source',target_source,'old_source',old_source)::text;+ END IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END $fn$;`;diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex d985f98aba..02a44f2540 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1670,6 +1670,14 @@ BEGINWHEN NOT (allowed ? target_source) THEN 'different_source' ELSE 'old_source_outside' END,'target_source',target_source,'old_source',old_source,'allowed',allowed)::text;END IF;+ -- G7a (git-canonical-schema.ts): a git-canonical source takes rows only from a writer that declares the git protocol.+ IF COALESCE(current_setting('gbrain.git_protocol',true),'') <> '1'+ AND EXISTS (SELECT 1 FROM git_canonical_brain WHERE singleton=1 AND strict_sources>0)+ AND EXISTS (SELECT 1 FROM sources WHERE id IN (target_source, old_source) AND config->>'canonical'='git') THEN+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='git_protocol_required: this source is git-canonical and the writer does not declare the git protocol',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='git_canonical_fence:mutation',+ DETAIL=jsonb_build_object('op',TG_OP,'target_source',target_source,'old_source',old_source)::text;+ END IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END \$fn\$;@@ -1684,6 +1692,38 @@ BEGINEND LOOP;END \$body\$;;++CREATE TABLE IF NOT EXISTS git_canonical_brain (+ singleton INTEGER PRIMARY KEY DEFAULT 1 CHECK (singleton = 1),+ strict_sources INTEGER NOT NULL DEFAULT 0 CHECK (strict_sources >= 0)+);+CREATE OR REPLACE FUNCTION gbrain_count_git_canonical_sources() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$fn\$+BEGIN+ INSERT INTO git_canonical_brain(singleton, strict_sources)+ VALUES (1, (SELECT count(*) FROM sources WHERE config->>'canonical' = 'git'))+ ON CONFLICT (singleton) DO UPDATE SET strict_sources = EXCLUDED.strict_sources;+ RETURN NULL;+END \$fn\$;+DROP TRIGGER IF EXISTS git_canonical_sources_count_insert ON sources;+CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON sources+ FOR EACH ROW WHEN (NEW.config->>'canonical' = 'git') EXECUTE FUNCTION gbrain_count_git_canonical_sources();+DROP TRIGGER IF EXISTS git_canonical_sources_count_update ON sources;+CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON sources+ FOR EACH ROW WHEN (OLD.config->>'canonical' IS DISTINCT FROM NEW.config->>'canonical') EXECUTE FUNCTION gbrain_count_git_canonical_sources();+DROP TRIGGER IF EXISTS git_canonical_sources_count_delete ON sources;+CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON sources+ FOR EACH ROW WHEN (OLD.config->>'canonical' = 'git') EXECUTE FUNCTION gbrain_count_git_canonical_sources();+INSERT INTO git_canonical_brain(singleton, strict_sources)+ VALUES (1, (SELECT count(*) FROM sources WHERE config->>'canonical' = 'git'))+ ON CONFLICT (singleton) DO UPDATE SET strict_sources = EXCLUDED.strict_sources;+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))+ AND EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relname = 'git_canonical_brain' AND c.relkind = 'r' AND NOT c.relrowsecurity) THEN+ ALTER TABLE git_canonical_brain ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;-- Verified text projection work (migration 153).DROP TRIGGER IF EXISTS trg_pages_search_vector ON pages;DO \$trg\$ BEGINdiff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 01c7e8bcb9..7de5ffd4c0 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -2415,6 +2415,14 @@ BEGINWHEN NOT (allowed ? target_source) THEN 'different_source' ELSE 'old_source_outside' END,'target_source',target_source,'old_source',old_source,'allowed',allowed)::text;END IF;+ -- G7a (git-canonical-schema.ts): a git-canonical source takes rows only from a writer that declares the git protocol.+ IF COALESCE(current_setting('gbrain.git_protocol',true),'') <> '1'+ AND EXISTS (SELECT 1 FROM git_canonical_brain WHERE singleton=1 AND strict_sources>0)+ AND EXISTS (SELECT 1 FROM sources WHERE id IN (target_source, old_source) AND config->>'canonical'='git') THEN+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='git_protocol_required: this source is git-canonical and the writer does not declare the git protocol',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='git_canonical_fence:mutation',+ DETAIL=jsonb_build_object('op',TG_OP,'target_source',target_source,'old_source',old_source)::text;+ END IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END \$fn\$;@@ -2430,6 +2438,40 @@ BEGINEND \$body\$;;-- END GENERATED from src/core/persistence/schema.ts (PERSISTENCE_SCHEMA_STATEMENTS)++-- BEGIN GENERATED from src/core/persistence/git-canonical-schema.ts (GIT_CANONICAL_SCHEMA_SQL). Edit that file, then run: bun run build:schema+CREATE TABLE IF NOT EXISTS git_canonical_brain (+ singleton INTEGER PRIMARY KEY DEFAULT 1 CHECK (singleton = 1),+ strict_sources INTEGER NOT NULL DEFAULT 0 CHECK (strict_sources >= 0)+);+CREATE OR REPLACE FUNCTION gbrain_count_git_canonical_sources() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$fn\$+BEGIN+ INSERT INTO git_canonical_brain(singleton, strict_sources)+ VALUES (1, (SELECT count(*) FROM sources WHERE config->>'canonical' = 'git'))+ ON CONFLICT (singleton) DO UPDATE SET strict_sources = EXCLUDED.strict_sources;+ RETURN NULL;+END \$fn\$;+DROP TRIGGER IF EXISTS git_canonical_sources_count_insert ON sources;+CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON sources+ FOR EACH ROW WHEN (NEW.config->>'canonical' = 'git') EXECUTE FUNCTION gbrain_count_git_canonical_sources();+DROP TRIGGER IF EXISTS git_canonical_sources_count_update ON sources;+CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON sources+ FOR EACH ROW WHEN (OLD.config->>'canonical' IS DISTINCT FROM NEW.config->>'canonical') EXECUTE FUNCTION gbrain_count_git_canonical_sources();+DROP TRIGGER IF EXISTS git_canonical_sources_count_delete ON sources;+CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON sources+ FOR EACH ROW WHEN (OLD.config->>'canonical' = 'git') EXECUTE FUNCTION gbrain_count_git_canonical_sources();+INSERT INTO git_canonical_brain(singleton, strict_sources)+ VALUES (1, (SELECT count(*) FROM sources WHERE config->>'canonical' = 'git'))+ ON CONFLICT (singleton) DO UPDATE SET strict_sources = EXCLUDED.strict_sources;+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))+ AND EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relname = 'git_canonical_brain' AND c.relkind = 'r' AND NOT c.relrowsecurity) THEN+ ALTER TABLE git_canonical_brain ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+-- END GENERATED from src/core/persistence/git-canonical-schema.ts (GIT_CANONICAL_SCHEMA_SQL)-- Verified text projection work (migration 153).-- BEGIN GENERATED from src/core/page-state/projection-schema.ts (PAGE_PROJECTION_SCHEMA_SQL). Edit that file, then run: bun run build:schemaDROP TRIGGER IF EXISTS trg_pages_search_vector ON pages;diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 38bbe95f83..c36bc50268 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 270;+export const LATEST_SCHEMA_VERSION = 271;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 416ba8eac7..85f30ae114 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -271,6 +271,7 @@ import { v267 } from './v267-pages-title-search-index.ts';import { v268 } from './v268-effect-claim-owner.ts';import { v269 } from './v269-links-supersedes-index.ts';import { v270 } from './v270-pages-source-created-index.ts';+import { v271 } from './v271-git-canonical-declared.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -540,4 +541,5 @@ export const MIGRATIONS: Migration[] = [v268,v269,v270,+ v271,];diff --git a/src/core/schema-migrations/v271-git-canonical-declared.ts b/src/core/schema-migrations/v271-git-canonical-declared.tsnew file mode 100644index 0000000000..6584a345e1--- /dev/null+++ b/src/core/schema-migrations/v271-git-canonical-declared.ts@@ -0,0 +1,22 @@+import type { Migration } from './types.ts';+import { GIT_CANONICAL_SCHEMA_SQL } from '../persistence/git-canonical-schema.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.+//+// Git-canonical memory, wave G7a (docs/designs/GIT_CANONICAL_MEMORY.md): the+// strict-source counter (git_canonical_brain, kept by row triggers on sources)+// and the git-canonical fence branch of the managed writer guard, which refuses a+// row of a source with config.canonical = "git" from a writer that does not+// declare gbrain.git_protocol (an older gbrain). Replaces only the guard+// function: its triggers already call it, and re-creating them would take+// ACCESS EXCLUSIVE locks on the largest tables. Additive: no source is strict+// until conversion, so the fence refuses nothing; no page row is read or changed.+// Provisional number: renumbered at the merge slot.+export const v271: Migration = {+ version: 271,+ name: 'git_canonical_declared',+ idempotent: true,+ sql: `${GIT_CANONICAL_SCHEMA_SQL}\n${MANAGED_WRITER_GUARD_FUNCTION_SQL}`,+};diff --git a/src/schema.sql b/src/schema.sqlindex 6559d0bd9d..4b46a3bed2 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -2411,6 +2411,14 @@ BEGINWHEN NOT (allowed ? target_source) THEN 'different_source' ELSE 'old_source_outside' END,'target_source',target_source,'old_source',old_source,'allowed',allowed)::text;END IF;+ -- G7a (git-canonical-schema.ts): a git-canonical source takes rows only from a writer that declares the git protocol.+ IF COALESCE(current_setting('gbrain.git_protocol',true),'') <> '1'+ AND EXISTS (SELECT 1 FROM git_canonical_brain WHERE singleton=1 AND strict_sources>0)+ AND EXISTS (SELECT 1 FROM sources WHERE id IN (target_source, old_source) AND config->>'canonical'='git') THEN+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='git_protocol_required: this source is git-canonical and the writer does not declare the git protocol',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='git_canonical_fence:mutation',+ DETAIL=jsonb_build_object('op',TG_OP,'target_source',target_source,'old_source',old_source)::text;+ END IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END $fn$;@@ -2426,6 +2434,40 @@ BEGINEND $body$;;-- END GENERATED from src/core/persistence/schema.ts (PERSISTENCE_SCHEMA_STATEMENTS)++-- BEGIN GENERATED from src/core/persistence/git-canonical-schema.ts (GIT_CANONICAL_SCHEMA_SQL). Edit that file, then run: bun run build:schema+CREATE TABLE IF NOT EXISTS git_canonical_brain (+ singleton INTEGER PRIMARY KEY DEFAULT 1 CHECK (singleton = 1),+ strict_sources INTEGER NOT NULL DEFAULT 0 CHECK (strict_sources >= 0)+);+CREATE OR REPLACE FUNCTION gbrain_count_git_canonical_sources() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$+BEGIN+ INSERT INTO git_canonical_brain(singleton, strict_sources)+ VALUES (1, (SELECT count(*) FROM sources WHERE config->>'canonical' = 'git'))+ ON CONFLICT (singleton) DO UPDATE SET strict_sources = EXCLUDED.strict_sources;+ RETURN NULL;+END $fn$;+DROP TRIGGER IF EXISTS git_canonical_sources_count_insert ON sources;+CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON sources+ FOR EACH ROW WHEN (NEW.config->>'canonical' = 'git') EXECUTE FUNCTION gbrain_count_git_canonical_sources();+DROP TRIGGER IF EXISTS git_canonical_sources_count_update ON sources;+CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON sources+ FOR EACH ROW WHEN (OLD.config->>'canonical' IS DISTINCT FROM NEW.config->>'canonical') EXECUTE FUNCTION gbrain_count_git_canonical_sources();+DROP TRIGGER IF EXISTS git_canonical_sources_count_delete ON sources;+CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON sources+ FOR EACH ROW WHEN (OLD.config->>'canonical' = 'git') EXECUTE FUNCTION gbrain_count_git_canonical_sources();+INSERT INTO git_canonical_brain(singleton, strict_sources)+ VALUES (1, (SELECT count(*) FROM sources WHERE config->>'canonical' = 'git'))+ ON CONFLICT (singleton) DO UPDATE SET strict_sources = EXCLUDED.strict_sources;+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))+ AND EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = current_schema() AND c.relname = 'git_canonical_brain' AND c.relkind = 'r' AND NOT c.relrowsecurity) THEN+ ALTER TABLE git_canonical_brain ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+-- END GENERATED from src/core/persistence/git-canonical-schema.ts (GIT_CANONICAL_SCHEMA_SQL)-- Verified text projection work (migration 153).-- BEGIN GENERATED from src/core/page-state/projection-schema.ts (PAGE_PROJECTION_SCHEMA_SQL). Edit that file, then run: bun run build:schemaDROP TRIGGER IF EXISTS trg_pages_search_vector ON pages;diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 7b7e693366..3eb18bd37d 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -124,6 +124,9 @@"files.files_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","files.files_storage_path_key": "u UNIQUE (storage_path)","gbrain_cycle_locks.gbrain_cycle_locks_pkey": "p PRIMARY KEY (id)",+ "git_canonical_brain.git_canonical_brain_pkey": "p PRIMARY KEY (singleton)",+ "git_canonical_brain.git_canonical_brain_singleton_check": "c CHECK ((singleton = 1))",+ "git_canonical_brain.git_canonical_brain_strict_sources_check": "c CHECK ((strict_sources >= 0))","ingest_log.ingest_log_pkey": "p PRIMARY KEY (id)","link_edge_proposals.link_edge_proposals_a_to_page_id_fkey": "f FOREIGN KEY (a_to_page_id) REFERENCES pages(id) ON DELETE CASCADE","link_edge_proposals.link_edge_proposals_b_to_page_id_fkey": "f FOREIGN KEY (b_to_page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -519,6 +522,7 @@"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",+ "gbrain_count_git_canonical_sources()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ef162804d8f0946d3df6209096567f0ca4255e02fceeee0adc8e52c47806d6a0","gbrain_count_modifications()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=9518c925621def19cafb2918da4d41e602ce94619af872eafa3c11b46c66296f","gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=ff99709590deb4c83f0e16d30b3988ca2598018f5fd6f30d132acf31b1010174","gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c",@@ -537,7 +541,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -705,6 +709,9 @@"gbrain_cycle_locks": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "git_canonical_brain": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"ingest_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1139,6 +1146,7 @@"files_pkey": "CREATE UNIQUE INDEX files_pkey ON public.files USING btree (id)","files_storage_path_key": "CREATE UNIQUE INDEX files_storage_path_key ON public.files USING btree (storage_path)","gbrain_cycle_locks_pkey": "CREATE UNIQUE INDEX gbrain_cycle_locks_pkey ON public.gbrain_cycle_locks USING btree (id)",+ "git_canonical_brain_pkey": "CREATE UNIQUE INDEX git_canonical_brain_pkey ON public.git_canonical_brain USING btree (singleton)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)","idx_budget_reservations_expires": "CREATE INDEX idx_budget_reservations_expires ON public.budget_reservations USING btree (expires_at) WHERE (status = 'held'::text)","idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)",@@ -2442,6 +2450,13 @@],"flags": "relkind=r rls=false force_rls=false"},+ "git_canonical_brain": {+ "columns": [+ "1 singleton integer/int4 NOT NULL DEFAULT 1",+ "2 strict_sources integer/int4 NOT NULL DEFAULT 0"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"ingest_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('ingest_log_id_seq'::regclass)",@@ -4242,6 +4257,9 @@"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","shared_skill_revisions.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_revisions FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","slug_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.slug_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "sources.git_canonical_sources_count_delete": "CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_insert": "CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON public.sources FOR EACH ROW WHEN (((new.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_update": "CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) IS DISTINCT FROM (new.config ->> 'canonical'::text))) EXECUTE FUNCTION gbrain_count_git_canonical_sources()","sources.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.sources FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 195f585823..69f0cf98a6 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -124,6 +124,9 @@"files.files_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","files.files_storage_path_key": "u UNIQUE (storage_path)","gbrain_cycle_locks.gbrain_cycle_locks_pkey": "p PRIMARY KEY (id)",+ "git_canonical_brain.git_canonical_brain_pkey": "p PRIMARY KEY (singleton)",+ "git_canonical_brain.git_canonical_brain_singleton_check": "c CHECK ((singleton = 1))",+ "git_canonical_brain.git_canonical_brain_strict_sources_check": "c CHECK ((strict_sources >= 0))","ingest_log.ingest_log_pkey": "p PRIMARY KEY (id)","link_edge_proposals.link_edge_proposals_a_to_page_id_fkey": "f FOREIGN KEY (a_to_page_id) REFERENCES pages(id) ON DELETE CASCADE","link_edge_proposals.link_edge_proposals_b_to_page_id_fkey": "f FOREIGN KEY (b_to_page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -519,6 +522,7 @@"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",+ "gbrain_count_git_canonical_sources()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ef162804d8f0946d3df6209096567f0ca4255e02fceeee0adc8e52c47806d6a0","gbrain_count_modifications()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=9518c925621def19cafb2918da4d41e602ce94619af872eafa3c11b46c66296f","gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=ff99709590deb4c83f0e16d30b3988ca2598018f5fd6f30d132acf31b1010174","gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c",@@ -537,7 +541,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -705,6 +709,9 @@"gbrain_cycle_locks": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "git_canonical_brain": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"ingest_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1139,6 +1146,7 @@"files_pkey": "CREATE UNIQUE INDEX files_pkey ON public.files USING btree (id)","files_storage_path_key": "CREATE UNIQUE INDEX files_storage_path_key ON public.files USING btree (storage_path)","gbrain_cycle_locks_pkey": "CREATE UNIQUE INDEX gbrain_cycle_locks_pkey ON public.gbrain_cycle_locks USING btree (id)",+ "git_canonical_brain_pkey": "CREATE UNIQUE INDEX git_canonical_brain_pkey ON public.git_canonical_brain USING btree (singleton)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)","idx_budget_reservations_expires": "CREATE INDEX idx_budget_reservations_expires ON public.budget_reservations USING btree (expires_at) WHERE (status = 'held'::text)","idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)",@@ -2442,6 +2450,13 @@],"flags": "relkind=r rls=false force_rls=false"},+ "git_canonical_brain": {+ "columns": [+ "1 singleton integer/int4 NOT NULL DEFAULT 1",+ "2 strict_sources integer/int4 NOT NULL DEFAULT 0"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"ingest_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('ingest_log_id_seq'::regclass)",@@ -4242,6 +4257,9 @@"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","shared_skill_revisions.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_revisions FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","slug_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.slug_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "sources.git_canonical_sources_count_delete": "CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_insert": "CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON public.sources FOR EACH ROW WHEN (((new.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_update": "CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) IS DISTINCT FROM (new.config ->> 'canonical'::text))) EXECUTE FUNCTION gbrain_count_git_canonical_sources()","sources.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.sources FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 4c946e50b3..c141f271a5 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -124,6 +124,9 @@"files.files_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","files.files_storage_path_key": "u UNIQUE (storage_path)","gbrain_cycle_locks.gbrain_cycle_locks_pkey": "p PRIMARY KEY (id)",+ "git_canonical_brain.git_canonical_brain_pkey": "p PRIMARY KEY (singleton)",+ "git_canonical_brain.git_canonical_brain_singleton_check": "c CHECK ((singleton = 1))",+ "git_canonical_brain.git_canonical_brain_strict_sources_check": "c CHECK ((strict_sources >= 0))","ingest_log.ingest_log_pkey": "p PRIMARY KEY (id)","link_edge_proposals.link_edge_proposals_a_to_page_id_fkey": "f FOREIGN KEY (a_to_page_id) REFERENCES pages(id) ON DELETE CASCADE","link_edge_proposals.link_edge_proposals_b_to_page_id_fkey": "f FOREIGN KEY (b_to_page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -519,6 +522,7 @@"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",+ "gbrain_count_git_canonical_sources()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ef162804d8f0946d3df6209096567f0ca4255e02fceeee0adc8e52c47806d6a0","gbrain_count_modifications()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=9518c925621def19cafb2918da4d41e602ce94619af872eafa3c11b46c66296f","gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=ff99709590deb4c83f0e16d30b3988ca2598018f5fd6f30d132acf31b1010174","gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c",@@ -537,7 +541,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -705,6 +709,9 @@"gbrain_cycle_locks": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "git_canonical_brain": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"ingest_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1139,6 +1146,7 @@"files_pkey": "CREATE UNIQUE INDEX files_pkey ON public.files USING btree (id)","files_storage_path_key": "CREATE UNIQUE INDEX files_storage_path_key ON public.files USING btree (storage_path)","gbrain_cycle_locks_pkey": "CREATE UNIQUE INDEX gbrain_cycle_locks_pkey ON public.gbrain_cycle_locks USING btree (id)",+ "git_canonical_brain_pkey": "CREATE UNIQUE INDEX git_canonical_brain_pkey ON public.git_canonical_brain USING btree (singleton)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)","idx_budget_reservations_expires": "CREATE INDEX idx_budget_reservations_expires ON public.budget_reservations USING btree (expires_at) WHERE (status = 'held'::text)","idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)",@@ -2438,6 +2446,13 @@],"flags": "relkind=r rls=false force_rls=false"},+ "git_canonical_brain": {+ "columns": [+ "1 singleton integer/int4 NOT NULL DEFAULT 1",+ "2 strict_sources integer/int4 NOT NULL DEFAULT 0"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"ingest_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('ingest_log_id_seq'::regclass)",@@ -4238,6 +4253,9 @@"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","shared_skill_revisions.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_revisions FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","slug_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.slug_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "sources.git_canonical_sources_count_delete": "CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_insert": "CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON public.sources FOR EACH ROW WHEN (((new.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_update": "CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) IS DISTINCT FROM (new.config ->> 'canonical'::text))) EXECUTE FUNCTION gbrain_count_git_canonical_sources()","sources.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.sources FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex bc74d5283f..602fd71e36 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -85,6 +85,9 @@"files.files_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","files.files_storage_path_key": "u UNIQUE (storage_path)","gbrain_cycle_locks.gbrain_cycle_locks_pkey": "p PRIMARY KEY (id)",+ "git_canonical_brain.git_canonical_brain_pkey": "p PRIMARY KEY (singleton)",+ "git_canonical_brain.git_canonical_brain_singleton_check": "c CHECK ((singleton = 1))",+ "git_canonical_brain.git_canonical_brain_strict_sources_check": "c CHECK ((strict_sources >= 0))","ingest_log.ingest_log_pkey": "p PRIMARY KEY (id)","link_edge_proposals.link_edge_proposals_a_to_page_id_fkey": "f FOREIGN KEY (a_to_page_id) REFERENCES pages(id) ON DELETE CASCADE","link_edge_proposals.link_edge_proposals_b_to_page_id_fkey": "f FOREIGN KEY (b_to_page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -388,6 +391,7 @@"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784","gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",+ "gbrain_count_git_canonical_sources()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ef162804d8f0946d3df6209096567f0ca4255e02fceeee0adc8e52c47806d6a0","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b","gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",@@ -396,7 +400,7 @@"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"@@ -525,6 +529,9 @@"gbrain_cycle_locks": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "git_canonical_brain": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"ingest_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -873,6 +880,7 @@"files_pkey": "CREATE UNIQUE INDEX files_pkey ON public.files USING btree (id)","files_storage_path_key": "CREATE UNIQUE INDEX files_storage_path_key ON public.files USING btree (storage_path)","gbrain_cycle_locks_pkey": "CREATE UNIQUE INDEX gbrain_cycle_locks_pkey ON public.gbrain_cycle_locks USING btree (id)",+ "git_canonical_brain_pkey": "CREATE UNIQUE INDEX git_canonical_brain_pkey ON public.git_canonical_brain USING btree (singleton)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)","idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)","idx_chat_usage_log_model": "CREATE INDEX idx_chat_usage_log_model ON public.chat_usage_log USING btree (model, created_at)",@@ -1841,6 +1849,13 @@],"flags": "relkind=r rls=false force_rls=false"},+ "git_canonical_brain": {+ "columns": [+ "1 singleton integer/int4 NOT NULL DEFAULT 1",+ "2 strict_sources integer/int4 NOT NULL DEFAULT 0"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"ingest_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('ingest_log_id_seq'::regclass)",@@ -3196,6 +3211,9 @@"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","shared_skill_revisions.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_revisions FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","slug_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.slug_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "sources.git_canonical_sources_count_delete": "CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_insert": "CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON public.sources FOR EACH ROW WHEN (((new.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_update": "CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) IS DISTINCT FROM (new.config ->> 'canonical'::text))) EXECUTE FUNCTION gbrain_count_git_canonical_sources()","sources.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.sources FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex f250bbb6dd..6c74df0d18 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -85,6 +85,9 @@"files.files_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","files.files_storage_path_key": "u UNIQUE (storage_path)","gbrain_cycle_locks.gbrain_cycle_locks_pkey": "p PRIMARY KEY (id)",+ "git_canonical_brain.git_canonical_brain_pkey": "p PRIMARY KEY (singleton)",+ "git_canonical_brain.git_canonical_brain_singleton_check": "c CHECK ((singleton = 1))",+ "git_canonical_brain.git_canonical_brain_strict_sources_check": "c CHECK ((strict_sources >= 0))","ingest_log.ingest_log_pkey": "p PRIMARY KEY (id)","link_edge_proposals.link_edge_proposals_a_to_page_id_fkey": "f FOREIGN KEY (a_to_page_id) REFERENCES pages(id) ON DELETE CASCADE","link_edge_proposals.link_edge_proposals_b_to_page_id_fkey": "f FOREIGN KEY (b_to_page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -388,6 +391,7 @@"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784","gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",+ "gbrain_count_git_canonical_sources()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ef162804d8f0946d3df6209096567f0ca4255e02fceeee0adc8e52c47806d6a0","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b","gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",@@ -396,7 +400,7 @@"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c393710877f69961517a5a820b741b9229ee9e20d045e736b191e8366170fedc"@@ -525,6 +529,9 @@"gbrain_cycle_locks": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "git_canonical_brain": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"ingest_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -873,6 +880,7 @@"files_pkey": "CREATE UNIQUE INDEX files_pkey ON public.files USING btree (id)","files_storage_path_key": "CREATE UNIQUE INDEX files_storage_path_key ON public.files USING btree (storage_path)","gbrain_cycle_locks_pkey": "CREATE UNIQUE INDEX gbrain_cycle_locks_pkey ON public.gbrain_cycle_locks USING btree (id)",+ "git_canonical_brain_pkey": "CREATE UNIQUE INDEX git_canonical_brain_pkey ON public.git_canonical_brain USING btree (singleton)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)","idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)","idx_chat_usage_log_model": "CREATE INDEX idx_chat_usage_log_model ON public.chat_usage_log USING btree (model, created_at)",@@ -1841,6 +1849,13 @@],"flags": "relkind=r rls=false force_rls=false"},+ "git_canonical_brain": {+ "columns": [+ "1 singleton integer/int4 NOT NULL DEFAULT 1",+ "2 strict_sources integer/int4 NOT NULL DEFAULT 0"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"ingest_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('ingest_log_id_seq'::regclass)",@@ -3196,6 +3211,9 @@"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","shared_skill_revisions.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_revisions FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","slug_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.slug_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "sources.git_canonical_sources_count_delete": "CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_insert": "CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON public.sources FOR EACH ROW WHEN (((new.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_update": "CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) IS DISTINCT FROM (new.config ->> 'canonical'::text))) EXECUTE FUNCTION gbrain_count_git_canonical_sources()","sources.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.sources FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex 64a06b07c3..8bdc1c4e77 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -85,6 +85,9 @@"files.files_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","files.files_storage_path_key": "u UNIQUE (storage_path)","gbrain_cycle_locks.gbrain_cycle_locks_pkey": "p PRIMARY KEY (id)",+ "git_canonical_brain.git_canonical_brain_pkey": "p PRIMARY KEY (singleton)",+ "git_canonical_brain.git_canonical_brain_singleton_check": "c CHECK ((singleton = 1))",+ "git_canonical_brain.git_canonical_brain_strict_sources_check": "c CHECK ((strict_sources >= 0))","ingest_log.ingest_log_pkey": "p PRIMARY KEY (id)","link_edge_proposals.link_edge_proposals_a_to_page_id_fkey": "f FOREIGN KEY (a_to_page_id) REFERENCES pages(id) ON DELETE CASCADE","link_edge_proposals.link_edge_proposals_b_to_page_id_fkey": "f FOREIGN KEY (b_to_page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -388,6 +391,7 @@"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784","gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",+ "gbrain_count_git_canonical_sources()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ef162804d8f0946d3df6209096567f0ca4255e02fceeee0adc8e52c47806d6a0","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b","gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",@@ -396,7 +400,7 @@"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"@@ -525,6 +529,9 @@"gbrain_cycle_locks": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "git_canonical_brain": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"ingest_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -873,6 +880,7 @@"files_pkey": "CREATE UNIQUE INDEX files_pkey ON public.files USING btree (id)","files_storage_path_key": "CREATE UNIQUE INDEX files_storage_path_key ON public.files USING btree (storage_path)","gbrain_cycle_locks_pkey": "CREATE UNIQUE INDEX gbrain_cycle_locks_pkey ON public.gbrain_cycle_locks USING btree (id)",+ "git_canonical_brain_pkey": "CREATE UNIQUE INDEX git_canonical_brain_pkey ON public.git_canonical_brain USING btree (singleton)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)","idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)","idx_chat_usage_log_model": "CREATE INDEX idx_chat_usage_log_model ON public.chat_usage_log USING btree (model, created_at)",@@ -1840,6 +1848,13 @@],"flags": "relkind=r rls=false force_rls=false"},+ "git_canonical_brain": {+ "columns": [+ "1 singleton integer/int4 NOT NULL DEFAULT 1",+ "2 strict_sources integer/int4 NOT NULL DEFAULT 0"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"ingest_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('ingest_log_id_seq'::regclass)",@@ -3195,6 +3210,9 @@"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","shared_skill_revisions.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_revisions FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","slug_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.slug_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "sources.git_canonical_sources_count_delete": "CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_insert": "CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON public.sources FOR EACH ROW WHEN (((new.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_update": "CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) IS DISTINCT FROM (new.config ->> 'canonical'::text))) EXECUTE FUNCTION gbrain_count_git_canonical_sources()","sources.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.sources FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.jsonindex 0e5483672d..7daef9d05a 100644--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json@@ -98,6 +98,9 @@"files.files_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","files.files_storage_path_key": "u UNIQUE (storage_path)","gbrain_cycle_locks.gbrain_cycle_locks_pkey": "p PRIMARY KEY (id)",+ "git_canonical_brain.git_canonical_brain_pkey": "p PRIMARY KEY (singleton)",+ "git_canonical_brain.git_canonical_brain_singleton_check": "c CHECK ((singleton = 1))",+ "git_canonical_brain.git_canonical_brain_strict_sources_check": "c CHECK ((strict_sources >= 0))","ingest_log.ingest_log_pkey": "p PRIMARY KEY (id)","link_edge_proposals.link_edge_proposals_a_to_page_id_fkey": "f FOREIGN KEY (a_to_page_id) REFERENCES pages(id) ON DELETE CASCADE","link_edge_proposals.link_edge_proposals_b_to_page_id_fkey": "f FOREIGN KEY (b_to_page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -397,6 +400,7 @@"enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784","gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5",+ "gbrain_count_git_canonical_sources()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ef162804d8f0946d3df6209096567f0ca4255e02fceeee0adc8e52c47806d6a0","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b","gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d","gbrain_guard_effect_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e8b5589dafd4a355106104daffdf57c7776d34fe18c5b5f5336a27de188688a1",@@ -405,7 +409,7 @@"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf","notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8",@@ -548,6 +552,9 @@"gbrain_cycle_locks": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "git_canonical_brain": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"ingest_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -894,6 +901,7 @@"files_pkey": "CREATE UNIQUE INDEX files_pkey ON public.files USING btree (id)","files_storage_path_key": "CREATE UNIQUE INDEX files_storage_path_key ON public.files USING btree (storage_path)","gbrain_cycle_locks_pkey": "CREATE UNIQUE INDEX gbrain_cycle_locks_pkey ON public.gbrain_cycle_locks USING btree (id)",+ "git_canonical_brain_pkey": "CREATE UNIQUE INDEX git_canonical_brain_pkey ON public.git_canonical_brain USING btree (singleton)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)","idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)","idx_chat_usage_log_model": "CREATE INDEX idx_chat_usage_log_model ON public.chat_usage_log USING btree (model, created_at)",@@ -1919,6 +1927,13 @@],"flags": "relkind=r rls=true force_rls=false"},+ "git_canonical_brain": {+ "columns": [+ "1 singleton integer/int4 NOT NULL DEFAULT 1",+ "2 strict_sources integer/int4 NOT NULL DEFAULT 0"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"ingest_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('ingest_log_id_seq'::regclass)",@@ -3257,6 +3272,9 @@"shared_skill_heads.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_heads FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","shared_skill_revisions.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_revisions FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()",+ "sources.git_canonical_sources_count_delete": "CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_insert": "CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON public.sources FOR EACH ROW WHEN (((new.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_update": "CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) IS DISTINCT FROM (new.config ->> 'canonical'::text))) EXECUTE FUNCTION gbrain_count_git_canonical_sources()","sources.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.sources FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 34ef89e510..17f78f1964 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -127,6 +127,9 @@"files.files_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","files.files_storage_path_key": "u UNIQUE (storage_path)","gbrain_cycle_locks.gbrain_cycle_locks_pkey": "p PRIMARY KEY (id)",+ "git_canonical_brain.git_canonical_brain_pkey": "p PRIMARY KEY (singleton)",+ "git_canonical_brain.git_canonical_brain_singleton_check": "c CHECK ((singleton = 1))",+ "git_canonical_brain.git_canonical_brain_strict_sources_check": "c CHECK ((strict_sources >= 0))","ingest_log.ingest_log_pkey": "p PRIMARY KEY (id)","link_edge_proposals.link_edge_proposals_a_to_page_id_fkey": "f FOREIGN KEY (a_to_page_id) REFERENCES pages(id) ON DELETE CASCADE","link_edge_proposals.link_edge_proposals_b_to_page_id_fkey": "f FOREIGN KEY (b_to_page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -523,6 +526,7 @@"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",+ "gbrain_count_git_canonical_sources()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ef162804d8f0946d3df6209096567f0ca4255e02fceeee0adc8e52c47806d6a0","gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=ff99709590deb4c83f0e16d30b3988ca2598018f5fd6f30d132acf31b1010174","gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c","gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=595b1e012edeb66edbec72a2a8b1d046a8360a386bfce2fd903e50e3f78af37b",@@ -540,7 +544,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -712,6 +716,9 @@"gbrain_cycle_locks": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "git_canonical_brain": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"ingest_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1141,6 +1148,7 @@"files_pkey": "CREATE UNIQUE INDEX files_pkey ON public.files USING btree (id)","files_storage_path_key": "CREATE UNIQUE INDEX files_storage_path_key ON public.files USING btree (storage_path)","gbrain_cycle_locks_pkey": "CREATE UNIQUE INDEX gbrain_cycle_locks_pkey ON public.gbrain_cycle_locks USING btree (id)",+ "git_canonical_brain_pkey": "CREATE UNIQUE INDEX git_canonical_brain_pkey ON public.git_canonical_brain USING btree (singleton)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)","idx_budget_reservations_expires": "CREATE INDEX idx_budget_reservations_expires ON public.budget_reservations USING btree (expires_at) WHERE (status = 'held'::text)","idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)",@@ -2454,6 +2462,13 @@],"flags": "relkind=r rls=true force_rls=false"},+ "git_canonical_brain": {+ "columns": [+ "1 singleton integer/int4 NOT NULL DEFAULT 1",+ "2 strict_sources integer/int4 NOT NULL DEFAULT 0"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"ingest_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('ingest_log_id_seq'::regclass)",@@ -4226,6 +4241,9 @@"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","shared_skill_revisions.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_revisions FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","slug_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.slug_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "sources.git_canonical_sources_count_delete": "CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_insert": "CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON public.sources FOR EACH ROW WHEN (((new.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_update": "CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) IS DISTINCT FROM (new.config ->> 'canonical'::text))) EXECUTE FUNCTION gbrain_count_git_canonical_sources()","sources.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.sources FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 6daaa770ef..52738dad21 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -127,6 +127,9 @@"files.files_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","files.files_storage_path_key": "u UNIQUE (storage_path)","gbrain_cycle_locks.gbrain_cycle_locks_pkey": "p PRIMARY KEY (id)",+ "git_canonical_brain.git_canonical_brain_pkey": "p PRIMARY KEY (singleton)",+ "git_canonical_brain.git_canonical_brain_singleton_check": "c CHECK ((singleton = 1))",+ "git_canonical_brain.git_canonical_brain_strict_sources_check": "c CHECK ((strict_sources >= 0))","ingest_log.ingest_log_pkey": "p PRIMARY KEY (id)","link_edge_proposals.link_edge_proposals_a_to_page_id_fkey": "f FOREIGN KEY (a_to_page_id) REFERENCES pages(id) ON DELETE CASCADE","link_edge_proposals.link_edge_proposals_b_to_page_id_fkey": "f FOREIGN KEY (b_to_page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -523,6 +526,7 @@"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",+ "gbrain_count_git_canonical_sources()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ef162804d8f0946d3df6209096567f0ca4255e02fceeee0adc8e52c47806d6a0","gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=ff99709590deb4c83f0e16d30b3988ca2598018f5fd6f30d132acf31b1010174","gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c","gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=595b1e012edeb66edbec72a2a8b1d046a8360a386bfce2fd903e50e3f78af37b",@@ -540,7 +544,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -712,6 +716,9 @@"gbrain_cycle_locks": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "git_canonical_brain": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"ingest_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1141,6 +1148,7 @@"files_pkey": "CREATE UNIQUE INDEX files_pkey ON public.files USING btree (id)","files_storage_path_key": "CREATE UNIQUE INDEX files_storage_path_key ON public.files USING btree (storage_path)","gbrain_cycle_locks_pkey": "CREATE UNIQUE INDEX gbrain_cycle_locks_pkey ON public.gbrain_cycle_locks USING btree (id)",+ "git_canonical_brain_pkey": "CREATE UNIQUE INDEX git_canonical_brain_pkey ON public.git_canonical_brain USING btree (singleton)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)","idx_budget_reservations_expires": "CREATE INDEX idx_budget_reservations_expires ON public.budget_reservations USING btree (expires_at) WHERE (status = 'held'::text)","idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)",@@ -2454,6 +2462,13 @@],"flags": "relkind=r rls=true force_rls=false"},+ "git_canonical_brain": {+ "columns": [+ "1 singleton integer/int4 NOT NULL DEFAULT 1",+ "2 strict_sources integer/int4 NOT NULL DEFAULT 0"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"ingest_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('ingest_log_id_seq'::regclass)",@@ -4226,6 +4241,9 @@"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","shared_skill_revisions.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_revisions FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","slug_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.slug_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "sources.git_canonical_sources_count_delete": "CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_insert": "CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON public.sources FOR EACH ROW WHEN (((new.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_update": "CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) IS DISTINCT FROM (new.config ->> 'canonical'::text))) EXECUTE FUNCTION gbrain_count_git_canonical_sources()","sources.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.sources FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 9ff262608d..580dbd5846 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -127,6 +127,9 @@"files.files_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","files.files_storage_path_key": "u UNIQUE (storage_path)","gbrain_cycle_locks.gbrain_cycle_locks_pkey": "p PRIMARY KEY (id)",+ "git_canonical_brain.git_canonical_brain_pkey": "p PRIMARY KEY (singleton)",+ "git_canonical_brain.git_canonical_brain_singleton_check": "c CHECK ((singleton = 1))",+ "git_canonical_brain.git_canonical_brain_strict_sources_check": "c CHECK ((strict_sources >= 0))","ingest_log.ingest_log_pkey": "p PRIMARY KEY (id)","link_edge_proposals.link_edge_proposals_a_to_page_id_fkey": "f FOREIGN KEY (a_to_page_id) REFERENCES pages(id) ON DELETE CASCADE","link_edge_proposals.link_edge_proposals_b_to_page_id_fkey": "f FOREIGN KEY (b_to_page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -523,6 +526,7 @@"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",+ "gbrain_count_git_canonical_sources()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ef162804d8f0946d3df6209096567f0ca4255e02fceeee0adc8e52c47806d6a0","gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=ff99709590deb4c83f0e16d30b3988ca2598018f5fd6f30d132acf31b1010174","gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c","gbrain_fact_normalize(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=595b1e012edeb66edbec72a2a8b1d046a8360a386bfce2fd903e50e3f78af37b",@@ -540,7 +544,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -712,6 +716,9 @@"gbrain_cycle_locks": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "git_canonical_brain": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"ingest_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1141,6 +1148,7 @@"files_pkey": "CREATE UNIQUE INDEX files_pkey ON public.files USING btree (id)","files_storage_path_key": "CREATE UNIQUE INDEX files_storage_path_key ON public.files USING btree (storage_path)","gbrain_cycle_locks_pkey": "CREATE UNIQUE INDEX gbrain_cycle_locks_pkey ON public.gbrain_cycle_locks USING btree (id)",+ "git_canonical_brain_pkey": "CREATE UNIQUE INDEX git_canonical_brain_pkey ON public.git_canonical_brain USING btree (singleton)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)","idx_budget_reservations_expires": "CREATE INDEX idx_budget_reservations_expires ON public.budget_reservations USING btree (expires_at) WHERE (status = 'held'::text)","idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)",@@ -2450,6 +2458,13 @@],"flags": "relkind=r rls=true force_rls=false"},+ "git_canonical_brain": {+ "columns": [+ "1 singleton integer/int4 NOT NULL DEFAULT 1",+ "2 strict_sources integer/int4 NOT NULL DEFAULT 0"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"ingest_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('ingest_log_id_seq'::regclass)",@@ -4222,6 +4237,9 @@"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","shared_skill_revisions.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_revisions FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","slug_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.slug_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "sources.git_canonical_sources_count_delete": "CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_insert": "CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON public.sources FOR EACH ROW WHEN (((new.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_update": "CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) IS DISTINCT FROM (new.config ->> 'canonical'::text))) EXECUTE FUNCTION gbrain_count_git_canonical_sources()","sources.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.sources FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 6901603e00..94e9f052ce 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1001,7 +1001,7 @@{"category": "ops","elapsed_ms": "<volatile>",- "message": "RLS enabled on 156/156 public tables",+ "message": "RLS enabled on 157/157 public tables","name": "rls","status": "ok"},@@ -1015,7 +1015,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "1357 column(s) verified against live schema",+ "message": "1359 column(s) verified against live schema","name": "schema_columns","status": "ok"},diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex e419515fc1..05155cde6d 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -124,6 +124,9 @@"files.files_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","files.files_storage_path_key": "u UNIQUE (storage_path)","gbrain_cycle_locks.gbrain_cycle_locks_pkey": "p PRIMARY KEY (id)",+ "git_canonical_brain.git_canonical_brain_pkey": "p PRIMARY KEY (singleton)",+ "git_canonical_brain.git_canonical_brain_singleton_check": "c CHECK ((singleton = 1))",+ "git_canonical_brain.git_canonical_brain_strict_sources_check": "c CHECK ((strict_sources >= 0))","ingest_log.ingest_log_pkey": "p PRIMARY KEY (id)","link_edge_proposals.link_edge_proposals_a_to_page_id_fkey": "f FOREIGN KEY (a_to_page_id) REFERENCES pages(id) ON DELETE CASCADE","link_edge_proposals.link_edge_proposals_b_to_page_id_fkey": "f FOREIGN KEY (b_to_page_id) REFERENCES pages(id) ON DELETE CASCADE",@@ -519,6 +522,7 @@"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",+ "gbrain_count_git_canonical_sources()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ef162804d8f0946d3df6209096567f0ca4255e02fceeee0adc8e52c47806d6a0","gbrain_count_modifications()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=9518c925621def19cafb2918da4d41e602ce94619af872eafa3c11b46c66296f","gbrain_fact_fingerprint(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=ff99709590deb4c83f0e16d30b3988ca2598018f5fd6f30d132acf31b1010174","gbrain_fact_fingerprint_v1(claim text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[] body_sha256=aa955a02d3c695f237e1771f0ffded2fa8e5c7b795c42b87f7fd239ae35e213c",@@ -537,7 +541,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae9883e69ac3121bc07689f68518c1d97a02a2788a64e496a26f12720300fe8a","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -705,6 +709,9 @@"gbrain_cycle_locks": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "git_canonical_brain": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"ingest_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1139,6 +1146,7 @@"files_pkey": "CREATE UNIQUE INDEX files_pkey ON public.files USING btree (id)","files_storage_path_key": "CREATE UNIQUE INDEX files_storage_path_key ON public.files USING btree (storage_path)","gbrain_cycle_locks_pkey": "CREATE UNIQUE INDEX gbrain_cycle_locks_pkey ON public.gbrain_cycle_locks USING btree (id)",+ "git_canonical_brain_pkey": "CREATE UNIQUE INDEX git_canonical_brain_pkey ON public.git_canonical_brain USING btree (singleton)","idx_access_tokens_hash": "CREATE INDEX idx_access_tokens_hash ON public.access_tokens USING btree (token_hash) WHERE (revoked_at IS NULL)","idx_budget_reservations_expires": "CREATE INDEX idx_budget_reservations_expires ON public.budget_reservations USING btree (expires_at) WHERE (status = 'held'::text)","idx_chat_usage_log_created": "CREATE INDEX idx_chat_usage_log_created ON public.chat_usage_log USING btree (created_at)",@@ -2442,6 +2450,13 @@],"flags": "relkind=r rls=false force_rls=false"},+ "git_canonical_brain": {+ "columns": [+ "1 singleton integer/int4 NOT NULL DEFAULT 1",+ "2 strict_sources integer/int4 NOT NULL DEFAULT 0"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"ingest_log": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('ingest_log_id_seq'::regclass)",@@ -4242,6 +4257,9 @@"shared_skill_packs.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_packs FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","shared_skill_revisions.gbrain_skill_publication": "CREATE TRIGGER gbrain_skill_publication BEFORE INSERT OR DELETE OR UPDATE ON public.shared_skill_revisions FOR EACH ROW EXECUTE FUNCTION gbrain_guard_skill_publication()","slug_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.slug_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "sources.git_canonical_sources_count_delete": "CREATE TRIGGER git_canonical_sources_count_delete AFTER DELETE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_insert": "CREATE TRIGGER git_canonical_sources_count_insert AFTER INSERT ON public.sources FOR EACH ROW WHEN (((new.config ->> 'canonical'::text) = 'git'::text)) EXECUTE FUNCTION gbrain_count_git_canonical_sources()",+ "sources.git_canonical_sources_count_update": "CREATE TRIGGER git_canonical_sources_count_update AFTER UPDATE ON public.sources FOR EACH ROW WHEN (((old.config ->> 'canonical'::text) IS DISTINCT FROM (new.config ->> 'canonical'::text))) EXECUTE FUNCTION gbrain_count_git_canonical_sources()","sources.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.sources FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","tags.tags_knowledge_revision": "CREATE TRIGGER tags_knowledge_revision AFTER INSERT OR DELETE OR UPDATE ON public.tags FOR EACH ROW EXECUTE FUNCTION gbrain_advance_tag_revision()",diff --git a/test/fixtures/goldens/pglite-upgrade-replay/repeat-boot-recreated-objects.json b/test/fixtures/goldens/pglite-upgrade-replay/repeat-boot-recreated-objects.jsonindex ea7bd0867c..4b5cd6fb0f 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/repeat-boot-recreated-objects.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/repeat-boot-recreated-objects.json@@ -20,6 +20,9 @@"trg:shared_skill_packs.gbrain_skill_publication","trg:shared_skill_revisions.gbrain_skill_publication","trg:slug_aliases.managed_writer_guard",+ "trg:sources.git_canonical_sources_count_delete",+ "trg:sources.git_canonical_sources_count_insert",+ "trg:sources.git_canonical_sources_count_update","trg:sources.managed_writer_guard","trg:tags.managed_writer_guard","trg:tags.tags_knowledge_revision",diff --git a/test/git-canonical-declared-g7a.test.ts b/test/git-canonical-declared-g7a.test.tsnew file mode 100644index 0000000000..bffbe0acda--- /dev/null+++ b/test/git-canonical-declared-g7a.test.ts@@ -0,0 +1,253 @@+/**+ * G7a, declared database-only classes of a git-canonical source (src/core/persistence/git-declared.ts). On a strict+ * source (`sources.config.canonical = "git"`, default off):+ * - a private or alias-private page, a page under a `storage.db_only` dir and a path Git ignores are declared: no+ * file, no door commit, no Git effect, and the row carries its class;+ * - a page turning private is the one exception to "no private bytes in Git": the door commits the removal of its file+ * (also when only HEAD still has it, Q7), and a later `sync --no-pull` keeps the page live and private (Q8);+ * - the private-commit backstop (forced probe): a publication whose page became lineage-private after it was prepared+ * is refused `git_private_commit_refused` with no commit and HEAD unchanged, a single put and a group alike;+ * - a file under a Git LFS rule commits only with `storage.git_lfs` and an LFS-configured checkout, as an LFS pointer;+ * - rows of a strict source take the managed writer guard's git fence (`git_protocol_required`) unless the writer+ * declares the protocol, and a writer with no file form refuses (`assertStrictGitHome`);+ * - the same writes on a source without the flag behave as before.+ * Runs on PGLite (publishMutation) and, with DATABASE_URL, on Postgres (publishGroup).+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { createHash } from 'node:crypto';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { importManagedFile } from '../src/core/persistence/import-mutations.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { assertStrictGitHome } from '../src/core/persistence/git-declared.ts';+import { preparePrivateTransition } from '../src/core/persistence/page-prepare.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { durableGitRepo, git } from './helpers/git-publication.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const putPage = operations.find(op => op.name === 'put_page')!;+const putPages = operations.find(op => op.name === 'put_pages')!;+const call = (ctx: OperationContext, name: string, params: Record<string, unknown>) => operations.find(op => op.name === name)!.handler(ctx, params) as Promise<Record<string, any>>;+const stateOf = (result: Record<string, any>) => result.state ?? result.receipt?.state;+const sha = (text: string) => createHash('sha256').update(text).digest('hex');+const page = (title: string, body: string, extra = '') => `---\ntype: note\ntitle: ${title}\n${extra}---\n\n${body}\n`;+const strict = (engine: BrainEngine) => engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id='default'`);+const put = (ctx: OperationContext, slug: string, content: string, requestId = randomUUID(), expectedRevision?: string) =>+ putPage.handler(ctx, { slug, content, request_id: requestId, wait_ms: 30_000, ...(expectedRevision ? { expected_revision: expectedRevision } : {}) }) as Promise<Record<string, any>>;+const outcome = (promise: Promise<unknown>) => promise.then(value => value as Record<string, any>, (error: { code?: string; message?: string }) => ({ thrown: error.code, message: error.message }));+const head = (root: string) => git(root, 'rev-parse', 'HEAD').trim();+const atHead = (root: string, rel: string) => git(root, 'ls-tree', '--name-only', 'HEAD', '--', rel).trim();+const row = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ live: boolean; reason: string | null; source_path: string | null; visibility: string | null }>(+ `SELECT deleted_at IS NULL AS live, database_only_reason AS reason, source_path, frontmatter->>'visibility' AS visibility FROM pages WHERE source_id='default' AND slug=$1`, [slug]))[0] ?? null;+const gitEffects = async (engine: BrainEngine, requestId: string) => (await engine.executeRaw(+ "SELECT 1 FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.request_id=$1::uuid AND e.kind='git'", [requestId])).length;+const makePrivate = (engine: BrainEngine, slug: string) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'],+ () => tx.executeRaw(`UPDATE pages SET frontmatter = frontmatter || '{"visibility":"private"}'::jsonb WHERE source_id='default' AND slug=$1`, [slug]), TEST_WRITE_ATTRIBUTION));+const setup = ({ root }: { root: string }) => {+ writeFileSync(join(root, '.gitignore'), 'archive/\n');+ writeFileSync(join(root, '.gitattributes'), 'lfs/** filter=lfs diff=lfs merge=lfs -text\n');+ durableGitRepo(root, ['.gitignore', '.gitattributes']);+};+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };++for (const backend of testBackends()) describe(`[${backend}] G7a: declared database-only classes of a strict source`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ afterEach(() => installFaultHook(undefined));++ test('declared classes publish database-only: no file, no commit, no Git effect, the row carries its class', () => managedBrain(async ({ engine, ctx, root }) => {+ writeFileSync(join(root, 'gbrain.yml'), 'storage:\n db_only:\n - cache/\n');+ mkdirSync(join(root, 'cache'));+ git(root, 'add', 'gbrain.yml'); git(root, 'commit', '-qm', 'db_only');+ await strict(engine);+ const before = head(root);+ const cases: Array<[string, string, string | null]> = [+ ['notes/secret', page('Secret', 'Private.', 'visibility: private\n'), 'private'],+ ['notes/from-secret', page('From secret', 'Lineage-private.', 'derived_from: notes/secret\n'), 'lineage_private'],+ ['notes/aliased', page('Aliased', 'Alias-private.', 'visibility: world\naccess: confidential\n'), 'alias_private'],+ ['archive/scan', page('Scan', 'Ignored path.'), 'git_ignored'],+ ['cache/derived', page('Cached', 'Under a db_only dir.'), null],+ ];+ for (const [slug, content, reason] of cases) {+ const requestId = randomUUID();+ expect(await put(ctx, slug, content, requestId)).toMatchObject({ state: 'committed' });+ expect(existsSync(join(root, `${slug}.md`))).toBe(false);+ expect(await gitEffects(engine, requestId)).toBe(0);+ expect(await row(engine, slug)).toMatchObject({ live: true, reason, source_path: null });+ }+ expect(head(root)).toBe(before);+ }, { databaseUrl, setup }), 120_000);++test('Q3: every strict writer is classified when it prepares; a managed import, which builds its own file target, is refused at publication', () => managedBrain(async ({ engine, ctx, root }) => {+ writeFileSync(join(root, 'gbrain.yml'), 'storage:\n db_only:\n - cache/\n');+ mkdirSync(join(root, 'cache'));+ git(root, 'add', 'gbrain.yml'); git(root, 'commit', '-qm', 'db_only');+ await strict(engine);+ const before = head(root);+ expect(await put(ctx, 'cache/put', page('Put', 'put_page.'))).toMatchObject({ state: 'committed' });+ expect(await putPages.handler(ctx, { request_id: randomUUID(), wait_ms: 30_000, pages: [{ slug: 'cache/batch-a', content: page('A', 'Batch a.') }, { slug: 'cache/batch-b', content: page('B', 'Batch b.') }] }))+ .toMatchObject({ state: 'committed' });+ expect(stateOf(await call(ctx, 'append_page', { slug: 'cache/put', text: 'Appended.', request_id: randomUUID() }))).toBe('committed');+ expect(stateOf(await call(ctx, 'takes_add', { slug: 'cache/put', claim: 'A cached claim.', kind: 'fact', holder: 'world', request_id: randomUUID() }))).toBe('committed');+ const text = page('Streamed', 'Uploaded in parts. '.repeat(200));+ const session = await call(ctx, 'begin_page_upload', { slug: 'cache/uploaded', mode: 'create', total_bytes: Buffer.byteLength(text), sha256: sha(text), request_id: randomUUID() });+ await call(ctx, 'upload_page_part', { upload_id: session.upload_id, part: 0, text, part_sha256: sha(text) });+ expect(stateOf(await call(ctx, 'commit_page_upload', { upload_id: session.upload_id, wait_ms: 30_000 }))).toBe('committed');+ for (const slug of ['cache/put', 'cache/batch-a', 'cache/batch-b', 'cache/uploaded']) {+ expect(existsSync(join(root, `${slug}.md`))).toBe(false);+ expect(await row(engine, slug)).toMatchObject({ live: true, source_path: null });+ }+ expect(head(root)).toBe(before);+ const input = join(root, '..', 'input'); mkdirSync(input);+ writeFileSync(join(input, 'cached.md'), page('Imported', 'Under a db_only dir.'));+ writeFileSync(join(input, 'secret.md'), page('Imported secret', 'Private.', 'visibility: private\n'));+ expect(await outcome(importManagedFile(engine, join(input, 'cached.md'), 'cache/imported.md', { sourceId: 'default', noEmbed: true }))).toMatchObject({ thrown: 'git_home_required' });+ expect(await outcome(importManagedFile(engine, join(input, 'secret.md'), 'notes/imported-secret.md', { sourceId: 'default', noEmbed: true }))).toMatchObject({ thrown: 'git_private_commit_refused' });+ expect(head(root)).toBe(before);+ for (const rel of ['cache/imported.md', 'notes/imported-secret.md']) expect(existsSync(join(root, rel))).toBe(false);+ expect(await row(engine, 'cache/imported')).toBeNull();+ expect(await row(engine, 'notes/imported-secret')).toBeNull();+ }, { databaseUrl, setup }), 120_000);++ test('a world page turning private: the door commits the removal of its file, the page stays live and private through sync --no-pull (Q8)', () => managedBrain(async ({ engine, ctx, root }) => {+ await strict(engine);+ const first = await put(ctx, 'notes/turning', page('Turning', 'Public first.'));+ expect(first).toMatchObject({ state: 'committed' });+ expect(atHead(root, 'notes/turning.md')).toBe('notes/turning.md');+ expect(await put(ctx, 'notes/turning', page('Turning', 'Private now.', 'visibility: private\n'), randomUUID(), first.revision)).toMatchObject({ state: 'committed' });+ expect(existsSync(join(root, 'notes/turning.md'))).toBe(false);+ expect(atHead(root, 'notes/turning.md')).toBe('');+ expect(git(root, 'log', '-1', '--format=%H', '--', 'notes/turning.md').trim()).toBe(head(root));+ expect(await row(engine, 'notes/turning')).toEqual({ live: true, reason: 'private', source_path: null, visibility: 'private' });+ await settleManagedGitEffects(engine);+ await performManagedSync(engine, OPTS);+ expect(await row(engine, 'notes/turning')).toEqual({ live: true, reason: 'private', source_path: null, visibility: 'private' });+ expect(git(root, 'status', '--porcelain').trim()).toBe('');+ }, { databaseUrl, setup }), 120_000);++ test('turning private when only HEAD still has the file (Q7): the removal goes through the door as a commit', () => managedBrain(async ({ engine, ctx, root }) => {+ await strict(engine);+ const first = await put(ctx, 'notes/half', page('Half', 'Public first.'));+ expect(first).toMatchObject({ state: 'committed' });+ rmSync(join(root, 'notes/half.md'));+ const before = head(root);+ expect(await put(ctx, 'notes/half', page('Half', 'Private now.', 'visibility: private\n'), randomUUID(), first.revision)).toMatchObject({ state: 'committed' });+ expect(head(root)).not.toBe(before);+ expect(atHead(root, 'notes/half.md')).toBe('');+ expect(await row(engine, 'notes/half')).toMatchObject({ live: true, reason: 'private', source_path: null });+ }, { databaseUrl, setup }), 120_000);++ test('preparePrivateTransition (for GBRA-60): the removal of a strict page file; nothing on a source without the flag', () => managedBrain(async ({ engine, ctx, root }) => {+ expect(await put(ctx, 'notes/concept', page('Concept', 'World first.'))).toMatchObject({ state: 'committed' });+ await settleManagedGitEffects(engine);+ const [binding] = await engine.executeRaw<{ worktree_id: string }>("SELECT worktree_id FROM persistence_source_bindings WHERE source_id='default'");+ const target = { source_id: 'default', worktree_id: binding!.worktree_id, slug: 'notes/concept' };+ const snapshot = (await engine.readPageSnapshot('notes/concept', { sourceId: 'default' }))!;+ expect(await preparePrivateTransition(engine, target, snapshot)).toBeUndefined();+ await strict(engine);+ expect(await preparePrivateTransition(engine, target, snapshot)).toMatchObject({ root, path: join(root, 'notes/concept.md'), content: null });+ }, { databaseUrl, setup }), 120_000);++ test('backstop (forced probe): a put whose page became lineage-private after it was prepared is refused, no commit', () => managedBrain(async ({ engine, ctx, root }) => {+ await strict(engine);+ expect(await put(ctx, 'notes/origin', page('Origin', 'Public origin.'))).toMatchObject({ state: 'committed' });+ const requestId = randomUUID();+ let flipped = false;+ installFaultHook(async (point, detail) => {+ if (point !== 'publication:prepared' || detail.requestId !== requestId || flipped) return;+ flipped = true;+ await makePrivate(engine, 'notes/origin');+ });+ const before = head(root);+ const result = await outcome(put(ctx, 'notes/digest', page('Digest', 'Written from the origin.', 'derived_from: notes/origin\n'), requestId));+ expect(flipped).toBe(true);+ expect(result).toMatchObject({ thrown: 'git_private_commit_refused', message: expect.stringContaining('lineage-private') });+ expect(head(root)).toBe(before);+ expect(existsSync(join(root, 'notes/digest.md'))).toBe(false);+ expect(await row(engine, 'notes/digest')).toBeNull();+ }, { databaseUrl, setup }), 120_000);++ test('backstop (forced probe): a group with one member turned private is refused whole; HEAD never holds that member, and the others then publish alone', () => managedBrain(async ({ engine, ctx, root }) => {+ await strict(engine);+ expect(await put(ctx, 'notes/origin', page('Origin', 'Public origin.'))).toMatchObject({ state: 'committed' });+ let flipped = false;+ installFaultHook(async (point, detail) => {+ if (point !== 'publication:prepared' || flipped) return;+ const [member] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM persistence_requests WHERE request_id=$1::uuid', [detail.requestId]);+ if (member?.slug !== 'notes/g-digest') return;+ flipped = true;+ await makePrivate(engine, 'notes/origin');+ });+ const before = head(root);+ const slugs = ['notes/g-a', 'notes/g-c', 'notes/g-digest'];+ const batch = await putPages.handler(ctx, { request_id: randomUUID(), wait_ms: 30_000, pages: [+ { slug: 'notes/g-a', content: page('A', 'Member a.') },+ { slug: 'notes/g-digest', content: page('Digest', 'From the origin.', 'derived_from: notes/origin\n') },+ { slug: 'notes/g-c', content: page('C', 'Member c.') },+ ] }) as Record<string, any>;+ expect(flipped).toBe(true);+ const rows = await engine.executeRaw<{ slug: string; state: string; error_code: string | null; error_message: string | null }>(+ "SELECT slug, state, error_code, error_message FROM persistence_requests WHERE source_id='default' AND slug = ANY($1::text[]) ORDER BY slug", [slugs]);+ expect(rows.find(r => r.slug === 'notes/g-digest')).toMatchObject({ state: 'failed', error_code: 'git_private_commit_refused' });+ expect(batch.counts).toMatchObject({ committed: 2, failed: 1 });+ expect(existsSync(join(root, 'notes/g-digest.md'))).toBe(false);+ expect(await row(engine, 'notes/g-digest')).toBeNull();+ // No commit since the refusal ever held the private member: the group's shared commit rolled back with its+ // transaction (Postgres publishes the batch as one group), and the existing fallback published each other member alone.+ expect(git(root, 'log', '--format=%H', `${before}..HEAD`, '--', 'notes/g-digest.md').trim()).toBe('');+ const touched = (rel: string) => git(root, 'log', '--format=%H', `${before}..HEAD`, '--', rel).trim();+ expect(touched('notes/g-a.md')).not.toBe('');+ expect(touched('notes/g-a.md')).not.toBe(touched('notes/g-c.md'));+ }, { databaseUrl, setup }), 120_000);++ test('a file under a Git LFS rule: refused while storage.git_lfs is off, committed as an LFS pointer once opted in', () => managedBrain(async ({ engine, ctx, root }) => {+ await strict(engine);+ const before = head(root);+ expect(await outcome(put(ctx, 'lfs/big', page('Big', 'Large body.')))).toMatchObject({ thrown: 'git_lfs_not_enabled', message: expect.stringContaining('storage.git_lfs is off') });+ await engine.setConfig('storage.git_lfs', 'true');+ expect(await outcome(put(ctx, 'lfs/big', page('Big', 'Large body.')))).toMatchObject({ thrown: 'git_lfs_not_enabled', message: expect.stringContaining('does not configure the LFS filter') });+ expect(head(root)).toBe(before);+ expect(existsSync(join(root, 'lfs/big.md'))).toBe(false);+ if (Bun.spawnSync(['git', 'lfs', 'version']).exitCode !== 0) return void console.warn('git-lfs is not installed: the LFS commit arm is skipped');+ git(root, 'lfs', 'install', '--local', '--skip-repo');+ expect(await put(ctx, 'lfs/big', page('Big', 'Large body.'))).toMatchObject({ state: 'committed' });+ expect(git(root, 'cat-file', '-p', 'HEAD:lfs/big.md')).toStartWith('version https://git-lfs.github.com/spec/v1');+ const objects = join(root, '.git', 'lfs', 'objects');+ expect(existsSync(objects) && readdirSync(objects, { recursive: true }).length > 0).toBe(true);+ expect(git(root, 'status', '--porcelain').trim()).toBe('');+ }, { databaseUrl, setup }), 120_000);++ test('the git fence: a strict source takes rows only from a writer declaring the git protocol; G4/G5 writers refuse', () => managedBrain(async ({ engine, ctx }) => {+ expect(await put(ctx, 'notes/fenced', page('Fenced', 'Body.'))).toMatchObject({ state: 'committed' });+ const legacy = (title: string) => engine.transaction(async tx => {+ await tx.executeRaw(`SELECT set_config('gbrain.write_sources','["default"]',true)`);+ await tx.executeRaw(`UPDATE pages SET title=$1 WHERE source_id='default' AND slug='notes/fenced'`, [title]);+ });+ await legacy('Before the flag');+ await expect(assertStrictGitHome(engine, { source_id: 'default', slug: 'notes/fenced' }, false)).resolves.toBeUndefined();+ await strict(engine);+ await expect(legacy('Under the flag')).rejects.toThrow(/git_protocol_required/);+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(`UPDATE pages SET title='Declared' WHERE source_id='default' AND slug='notes/fenced'`), TEST_WRITE_ATTRIBUTION));+ await expect(assertStrictGitHome(engine, { source_id: 'default', slug: 'notes/fenced' }, true)).rejects.toMatchObject({ code: 'git_home_required', reason: 'facts_lane' });+ }, { databaseUrl, setup }), 120_000);++ test('without the flag nothing changes: private, turned-private and LFS-rule writes publish their files as before', () => managedBrain(async ({ engine, ctx, root }) => {+ const slugs = ['notes/secret', 'notes/turning', 'lfs/big'];+ expect(await put(ctx, 'notes/secret', page('Secret', 'Private.', 'visibility: private\n'))).toMatchObject({ state: 'committed' });+ const first = await put(ctx, 'notes/turning', page('Turning', 'Public first.'));+ expect(first).toMatchObject({ state: 'committed' });+ expect(await put(ctx, 'notes/turning', page('Turning', 'Private now.', 'visibility: private\n'), randomUUID(), first.revision)).toMatchObject({ state: 'committed' });+ expect(await put(ctx, 'lfs/big', page('Big', 'Large body.'))).toMatchObject({ state: 'committed' });+ await settleManagedGitEffects(engine);+ for (const slug of slugs) {+ expect(existsSync(join(root, `${slug}.md`))).toBe(true);+ expect(atHead(root, `${slug}.md`)).toBe(`${slug}.md`);+ expect(await row(engine, slug)).toMatchObject({ live: true, reason: null, source_path: `${slug}.md` });+ }+ }, { databaseUrl, setup }), 120_000);+});diff --git a/test/git-door-strict-gbra133.test.ts b/test/git-door-strict-gbra133.test.tsindex dc15023751..dbcba4b78d 100644--- a/test/git-door-strict-gbra133.test.ts+++ b/test/git-door-strict-gbra133.test.ts@@ -149,16 +149,17 @@ for (const backend of testBackends()) describe(`[${backend}] G2: a strict sourceexpect(git(root, 'log', '--format=%H', '--', ...slugs.map(slug => `${slug}.md`)).split('\n').filter(Boolean).sort()).toEqual([...commits].sort());}, { databaseUrl, setup }), 120_000);- test('a commit Git refuses publishes nothing: the write fails and the file is never left behind', () => managedBrain(async ({ engine, ctx, root }) => {+ test('a path Git would refuse is never written or committed: G7a declares it git_ignored (database-only, no Git effect)', () => managedBrain(async ({ engine, ctx, root }) => {writeFileSync(join(root, '.gitignore'), 'notes/ignored.md\n');git(root, 'commit', '-qam', 'ignore one path');await strict(engine);const head = git(root, 'rev-parse', 'HEAD').trim();- const result = await put(ctx, 'notes/ignored', page('Ignored', 'Never published.')).then(value => value, (error: { code?: string }) => ({ thrown: error.code }));- expect(result).toMatchObject({ thrown: 'git_target_ignored' });+ const requestId = randomUUID();+ expect(await put(ctx, 'notes/ignored', page('Ignored', 'Never in Git.'), requestId)).toMatchObject({ state: 'committed' });expect(existsSync(join(root, 'notes/ignored.md'))).toBe(false);expect(git(root, 'rev-parse', 'HEAD').trim()).toBe(head);- expect(await engine.executeRaw("SELECT 1 FROM pages WHERE source_id='default' AND slug='notes/ignored' AND deleted_at IS NULL")).toHaveLength(0);+ expect(await engine.executeRaw("SELECT database_only_reason FROM pages WHERE source_id='default' AND slug='notes/ignored' AND deleted_at IS NULL")).toEqual([{ database_only_reason: 'git_ignored' }]);+ expect(await engine.executeRaw("SELECT 1 FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.request_id=$1::uuid AND e.kind='git'", [requestId])).toHaveLength(0);}, { databaseUrl, setup }), 120_000);test('without the flag nothing is committed before the row; the effect commits it later', () => managedBrain(async ({ engine, ctx, root }) => {diff --git a/test/git-gap-census.test.ts b/test/git-gap-census.test.tsindex 78258b7a41..70645f5c12 100644--- a/test/git-gap-census.test.ts+++ b/test/git-gap-census.test.ts@@ -289,8 +289,8 @@ for (const backend of testBackends()) describe(`git-gap census (git-canonical G1await engine.putPage('notes/secret', { type: 'note', title: 'Secret', compiled_truth: 'Secret.', timeline: '', frontmatter: { visibility: 'private' } });const [{ min, max }] = await engine.executeRaw<{ min: string; max: string }>('SELECT min(id)::text AS min, max(id)::text AS max FROM pages');expect(min.length).toBeLessThan(max.length);- expect(await censusGitGap(engine, 'default', { sample: 0 })).toMatchObject({ checkout: null, head: null, pages: 301, not_compared: 300, worktree: null,- states: { declared_database_only: 1, equal: 0 }, declared: { private: 1 } });+ expect(await censusGitGap(engine, 'default', { sample: 0 })).toMatchObject({ checkout: null, head: null, pages: 301, not_compared: 0, worktree: null,+ states: { declared_database_only: 301, equal: 0 }, declared: { database_only_source: 301, private: 0 } });expect((await censusGitGap(engine, 'default', { sample: 0, deadlineAt: Date.now() - 1 })).complete).toBe(false);}, 120000);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 6ae31ddb4e..f1f1719adf 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -78,6 +78,7 @@ test/file-drift-soft-delete-hold-release-gbra133.test.tstest/forecast-journal.test.tstest/frontmatter-reserved-keys-6454.test.tstest/get-chunks-paging.test.ts+test/git-canonical-declared-g7a.test.tstest/git-door-strict-gbra133.test.tstest/git-gap-census.test.tstest/google-connector-facts-fence-7292.test.ts