Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#7112): PG15-portable sources.config SQL, owner-exception database error text, Postgres 15 CI lane
garrytan133bd5cb4194
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex 462850d772..21d7a1bb31 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -571,6 +571,79 @@ jobs:if-no-files-found: warnoverwrite: true+ postgres15-compat:+ # #7112: gbrain supports Postgres 15, but PGLite runs 17 and every other+ # Postgres lane 16, so SQL only 16+ parses (IS JSON) shipped green and+ # wedged managed sync on 15. Runs the targeted write, sync, jobs and+ # migration files of scripts/e2e-postgres15.txt on a pg15 server wherever+ # the gated E2E jobs run, and gates e2e-status (so e2e-full-suite).+ name: Postgres 15 compatibility (#7112)+ needs: [prepare-e2e]+ if: ${{ needs.prepare-e2e.outputs.reuse != 'true' }}+ runs-on: ubicloud-standard-4-ubuntu-2404+ timeout-minutes: 20+ services:+ postgres:+ image: pgvector/pgvector:pg15+ env:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: gbrain_test+ ports:+ - 5432:5432+ options: >-+ --health-cmd pg_isready+ --health-interval 10s+ --health-timeout 5s+ --health-retries 5+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.3+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3+ with:+ path: ~/.bun/install/cache+ key: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}+ restore-keys: bun-cache-${{ runner.os }}-+ # PGLite snapshot (restore-only; test.yml's serial-tests job saves).+ # KEY: byte-identical with the homes in test.yml.+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3+ with:+ path: |+ test/fixtures/pglite-snapshot.tar+ test/fixtures/pglite-snapshot.version+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/ops/execution-prerequisites.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-body/schema.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts', 'src/core/belief/schema.ts', 'src/core/fence-repair/reasons.ts', 'src/core/fence-repair/measured.ts', 'src/core/ai/errors.ts') }}+ - name: Install dependencies (bounded, retried once)+ timeout-minutes: 8+ run: bun scripts/ci-bun-install.ts --frozen-lockfile+ - name: Require a Postgres 15 server+ run: |+ version=$(psql "postgresql://postgres:postgres@localhost:5432/gbrain_test" -Atc "SELECT current_setting('server_version_num')::int / 10000")+ echo "server major version: $version"+ if [ "$version" != 15 ]; then echo "::error::postgres15-compat must run on Postgres 15 (got $version)"; exit 1; fi+ - name: Run the Postgres 15 list+ shell: bash+ run: |+ export DATABASE_URL="postgresql://postgres:${PGPASSWORD}@localhost:5432/gbrain_test"+ mapfile -t files < <(grep -v -e '^#' -e '^$' scripts/e2e-postgres15.txt)+ bash scripts/run-e2e.sh "${files[@]}"+ env:+ PGPASSWORD: postgres+ GBRAIN_TEST_DB: '1'+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ GBRAIN_TEST_RECEIPT_LANE: postgres15-compat+ - name: Upload receipts+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-postgres15-compat+ path: ${{ runner.temp }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true+tier2:name: Tier 2 (LLM Skills)# Runs on every push/PR (promoted from schedule-only in v0.19.0), in@@ -1130,7 +1203,7 @@ jobs:# Named exception (docs/TESTING.md#event-parity): FULL_CORPUS adds the# full-corpus lanes to the aggregate on the nightly schedule only.e2e-status:- needs: [jsonb-parity, tier1, tier1-backend-matrix, tier2, prepare-e2e, selected-e2e, coverage-full-unit, coverage-full-serial, coverage-full-slow, coverage-full-e2e]+ needs: [jsonb-parity, tier1, tier1-backend-matrix, postgres15-compat, tier2, prepare-e2e, selected-e2e, coverage-full-unit, coverage-full-serial, coverage-full-slow, coverage-full-e2e]if: ${{ needs.prepare-e2e.outputs.reuse != 'true' && always() }}runs-on: ubicloud-standard-2-ubuntu-2404timeout-minutes: 5@@ -1143,6 +1216,7 @@ jobs:JSONB: ${{ needs.jsonb-parity.result }}TIER1: ${{ needs.tier1.result }}BACKEND_MATRIX: ${{ needs.tier1-backend-matrix.result }}+ POSTGRES15: ${{ needs.postgres15-compat.result }}TIER2: ${{ needs.tier2.result }}PREPARE: ${{ needs.prepare-e2e.result }}SELECTED: ${{ needs.selected-e2e.result }}@@ -1155,7 +1229,7 @@ jobs:GBRAIN_PAID_LANES: ${{ vars.GBRAIN_PAID_LANES }}run: |echo "event=$EVENT"- echo "jsonb-parity=$JSONB tier1=$TIER1 tier1-backend-matrix=$BACKEND_MATRIX tier2=$TIER2 prepare-e2e=$PREPARE selected-e2e=$SELECTED"+ echo "jsonb-parity=$JSONB tier1=$TIER1 tier1-backend-matrix=$BACKEND_MATRIX postgres15-compat=$POSTGRES15 tier2=$TIER2 prepare-e2e=$PREPARE selected-e2e=$SELECTED"if [ "$TIER2" = "skipped" ] && [ "$GBRAIN_PAID_LANES" = "0" ]; thenecho "tier2 skipped: paid lanes disabled by the repository variable GBRAIN_PAID_LANES='0' (not green coverage of Tier 2)"echo "::notice::Tier 2 (LLM Skills) skipped: paid lanes disabled by GBRAIN_PAID_LANES='0'"@@ -1165,7 +1239,7 @@ jobs:} >> "${GITHUB_STEP_SUMMARY:-/dev/null}"TIER2="success"fi- for r in "$JSONB" "$TIER1" "$BACKEND_MATRIX" "$TIER2" "$PREPARE" "$SELECTED"; do+ for r in "$JSONB" "$TIER1" "$BACKEND_MATRIX" "$POSTGRES15" "$TIER2" "$PREPARE" "$SELECTED"; doif [ "$r" != "success" ]; thenecho "✗ gated e2e job did not succeed (got $r) — E2E fail"exit 1diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fe1e05d299..ec0e92d830 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,32 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.325.0] - 2026-10-20++**Managed sync works on Postgres 15 again, and a database error in a write receipt now says what failed.** On a Postgres 15 brain every managed sync stopped at its checkpoint with `storage_error` (PostgreSQL 42601, `syntax_error`), run after run, because the statement that merges `sources.config` used the `IS JSON` predicate, which only Postgres 16 and newer parse. The receipt kept only the error class and SQLSTATE, so nobody could tell which statement failed. Both are fixed. A new CI lane now runs the write, sync, jobs and migration suites on Postgres 15 for every full run, and a unit-tier check refuses Postgres 16+ only SQL in `src/`.++### What changed++| Situation | Before | Now |+|---|---|---|+| Managed sync, put_page with a slug-root mode, source config updates, archive/restore and the shared-skills opt-out on Postgres 15 | every statement that merges `sources.config` failed to parse (42601); the managed sync checkpoint never committed | the merge uses `gbrain_try_jsonb(text)` (migration v263), which parses on Postgres 15, 16 and 17 and PGLite |+| Doctor `jsonb_integrity` and `gbrain repair-jsonb` on Postgres 15 | `pg_input_is_valid` (Postgres 16+) failed the check | the same `gbrain_try_jsonb` guard |+| A double-encoded config or dream-breaker map whose text is JSON but not jsonb (a `\u0000` escape) | passed `IS JSON`, then the cast raised and the whole update failed, on every server | reads as an empty object, like other unparseable text |+| A write that failed on an unexpected database error | the receipt named the class and SQLSTATE only | owner-side the receipt also keeps `error_text` (the server message, quoted values replaced by `…`), `statement` (the first line of the SQL, literals replaced, never parameters) and `position`; `gbrain write-request <id> --json` on the brain host prints `error_detail`, and the consumer log line carries the same fields |++### What to watch for after you upgrade++- On Postgres 15 the first sync after the upgrade publishes the checkpoint that kept failing. The failed checkpoint receipts from before then count as superseded and stop warning; nothing needs replaying.+- Remote and agent readers of a receipt see no new field. A PL/pgSQL `RAISE` (a trigger refusal) keeps no text, because it can carry page values.+- #6719's older `0A000` receipts were written before error text was stored, so their cause stays unknown; once a later checkpoint of the source commits they count as historical (since #6834). A new failure of that kind now records its statement.++### Itemized changes++- New SQL function `gbrain_try_jsonb(text) RETURNS jsonb` (schema.sql and migration v263), used by the `sources.config` normalizer (`src/core/source-config-sql.ts`), the dream-breaker reset, doctor `jsonb_integrity` and `gbrain repair-jsonb`.+- `ownerExceptionFailure` keeps a server-generated database error's redacted `error_text`, `statement` and `position`; `get_write_request` returns `error_detail` to trusted local callers only.+- CI: an E2E job `postgres15-compat` runs `scripts/e2e-postgres15.txt` on `pgvector/pgvector:pg15` wherever the gated E2E jobs run and gates `e2e-status` (so `e2e-full-suite`); `bun run ci:ubicloud --lanes pg-arms,e2e --pg-image pgvector/pgvector:pg15` reruns the whole corpus on Postgres 15 as a diagnostic; `test/postgres15-sql-compat-7112.test.ts` fails on Postgres 16+ only SQL in `src/`.+- Reported by @Justinn231 (#7112, who found the failing statement in the server log) and @Kkkkkuro (#6719).+## [0.60.324.0] - 2026-10-20**Agents can now add to a page without rewriting it, and write pages larger than one request.** Before, adding a line to a long conversation log meant sending the whole page back with put_page, which got slower as the page grew, and a remote or thin client could not write a page bigger than its connection's request limit at all. Now `append_page` adds text to the end of a page in time proportional to the text added, upload sessions carry a page of any size up to the page ceiling in parts, and `edit_page` can edit a very large page by rewriting only the stretch it changes.diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 35d348675b..fcf1e51c6d 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -1075,10 +1075,17 @@ at most 200 characters. When an unexpected exception in the owner failed awrite (`storage_error` with a generic public message; the class and frame stay owner-only),the line also carries `class=`, `errno=` and `frame=` (the top gbrain sourceframe, repo-relative, for example `src/core/persistence/page-prepare.ts:120`):-the owner diagnostics the receipt points at. The stored receipt keeps the same-identifiers (never the error message) owner-side in `error_detail`, with the-build that ran the attempt; `gbrain write-request <id>` names an owner on-another build than the CLI (`owner_build`) and the restart to run. Connection-wait evidence follows on Postgres:+the owner diagnostics the receipt points at. For a database server error it+adds `error_text=`, `statement=` and `position=` (#7112): the server's primary+message with every quoted value replaced by `…` (an object name such as a+column, a relation or the token a syntax error stopped at is kept), the first+line of the failing statement with its literals replaced, never its+parameters, and the error's character position. A PL/pgSQL `RAISE` keeps no+text, because it can carry page values. The stored receipt keeps the same+identifiers (never an application error's message) owner-side in `error_detail`, with the+build that ran the attempt; on the brain host `gbrain write-request <id> --json`+prints that `error_detail`, and names an owner on another build than the CLI+(`owner_build`) and the restart to run. Connection-wait evidence follows on Postgres:`first_conn_ms` is the time from phase start until the phase obtained aconnection; `checkout=not_observed conn_wait_ms=<n>` means it had not obtainedone after `n` milliseconds (a saturated pool or pooler, not a slow query); anddiff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 4244727fe8..02cdef892e 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -6,7 +6,7 @@- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values; #5966 (W14 P1.7) adds the `slug_rule_mismatch` verdict (a legacy unstamped file of a slug the path cannot derive, fix: `gbrain repair frontmatter`) read from `readReconcileState`'s refusal (`detail: slug_rule_mismatch` once the wave-13 `reconcile-state.ts` hunk lands; until then an `invalid_params` refusal on a non-fixed-point slug).-- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`. #5929: `ownerExceptionFailure` (the coordinator `requestError` fallback) keeps an unexpected exception's class, errno and top `src/...:line` frame as `origin: owner_exception` (never its message), so `withAttempt` stamps the build; `publicFailureDetail` is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, reason, stage, fence), so `error_class`/`errno`/`frame`, `sources` and `attempt` stay owner-only; `ownerBuildMismatch` drives the local `owner_build` receipt field (`ops/persistence.ts`) and the submit-time why/fix (`page-mutations.ts`), and `ownerExceptionLogText` the consumer log line. Wave 16 (GBRA-79, #6513 comments): an untyped refusal carries a CLOSED `reason` (`PUBLICATION_REASONS`: `attribution_unclassified_table` and `trust_unclassified_table` from the two stamp triggers' own "is not classified for table" raise, `graduation_in_progress` from the engine-graduation fence, which raises SQLSTATE 55000 and which `databaseRefusal` now recognizes, else `unknown`); the message decides nothing on its own (the same text from another raiser, or the fence's text under P0001, is `unknown`), the public message names only the enum (`Publication failed (P0001 in <raiser>: <reason>)`), and no part of the message is stored, owner-side included (#5974's rule). `publicFailureDetail` passes `reason` only as a member of the enum, whatever a stored detail holds. The projection rides the managed failure (`sync-failures.ts` `ManagedSyncFailure.write_error_detail`, recorded with the failure and re-read from the pending receipt by `readManagedSyncFailures`; `publicationDetailText` appends ` raiser= table= reason=` to `formatManagedSyncFailure`, so the ledger mirror and doctor carry it) and `gbrain sync status --json` (`last_error.write_error_detail`, `last_error.detail` = the reason, which `classifySyncFault` refines by: `graduation_in_progress` is `connection` / retry / no human in `sync-fault-class.ts`). Tests: `test/publication-failure-reason-6513.test.ts` (mapping, privacy negatives, allow-list), `test/sync-status-failure-detail-6513.test.ts` (both engines, a real operator trigger).+- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`. #5929: `ownerExceptionFailure` (the coordinator `requestError` fallback) keeps an unexpected exception's class, errno and top `src/...:line` frame as `origin: owner_exception` (never an application error's message), so `withAttempt` stamps the build; #7112: a server-generated database error (a five-character SQLSTATE and a severity, never a PL/pgSQL RAISE) also keeps `error_text` (its primary message, first line, at most 240 characters, a double-quoted token kept only after an object word such as `near`, `column` or `relation`, every other quoted run replaced by `…`), `statement` (the first line of the failing SQL, literals and dollar-quoted bodies replaced, at most 160 characters, never the parameters) and `position`, all owner-only; a trusted local `gbrain write-request <id>` returns the full `error_detail`; `publicFailureDetail` is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, reason, stage, fence), so `error_class`/`errno`/`frame`/`error_text`/`statement`/`position`, `sources` and `attempt` stay owner-only; `ownerBuildMismatch` drives the local `owner_build` receipt field (`ops/persistence.ts`) and the submit-time why/fix (`page-mutations.ts`), and `ownerExceptionLogText` the consumer log line. Wave 16 (GBRA-79, #6513 comments): an untyped refusal carries a CLOSED `reason` (`PUBLICATION_REASONS`: `attribution_unclassified_table` and `trust_unclassified_table` from the two stamp triggers' own "is not classified for table" raise, `graduation_in_progress` from the engine-graduation fence, which raises SQLSTATE 55000 and which `databaseRefusal` now recognizes, else `unknown`); the message decides nothing on its own (the same text from another raiser, or the fence's text under P0001, is `unknown`), the public message names only the enum (`Publication failed (P0001 in <raiser>: <reason>)`), and no part of the message is stored, owner-side included (#5974's rule). `publicFailureDetail` passes `reason` only as a member of the enum, whatever a stored detail holds. The projection rides the managed failure (`sync-failures.ts` `ManagedSyncFailure.write_error_detail`, recorded with the failure and re-read from the pending receipt by `readManagedSyncFailures`; `publicationDetailText` appends ` raiser= table= reason=` to `formatManagedSyncFailure`, so the ledger mirror and doctor carry it) and `gbrain sync status --json` (`last_error.write_error_detail`, `last_error.detail` = the reason, which `classifySyncFault` refines by: `graduation_in_progress` is `connection` / retry / no human in `sync-fault-class.ts`). Tests: `test/publication-failure-reason-6513.test.ts` (mapping, privacy negatives, allow-list), `test/sync-status-failure-detail-6513.test.ts` (both engines, a real operator trigger).- `src/core/cycle/extract-atoms-page-state.ts` — derived page scan/failure state keyed by source incarnation, stable page identity and content hash. Compare-and-swap stamps never update canonical frontmatter. Reviewed reconciliation can carry matching state across removal of legacy bookkeeping fields. Atom item completion still waits for all atoms and provenance links; managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex bb6114f26e..b188b331bc 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/repair-content.ts` — `gbrain repair content [--source <id>] [--only <path>]... [--skip <path>]... [--no-llm] [--max-usd <n>] [--diff] [--apply [--expect <h1>[,<h2>]]] [--json]` (#6377): the content-repair lane as one command. `content` is parsed by `repair.ts`'s strict flag grammar like a kind (`CONTENT_LANE`; `--only`/`--skip`/`--diff`, `--no-llm`, `--max-usd` and `--expect` are accepted for it, `--slug`, `--yes`, `--include-ambiguous` and `--all` refuse) and dispatched before the kind check; it is a lane, not a `RepairKind`: no registry entry, no cursor of its own, listed under "Lanes:" in `REPAIR_HELP`. `runRepairContentCommand` resolves the scope, runs `runContentLane` and prints each kind's result through `renderRepairResult` plus a lane line (spend, allowance left, each kind's hash, every stop, the apply command); `--json` prints `{ lane, scope, mode, kinds, results[] (with `paid`), preview_hashes, cost, stopped, paid_kinds, apply_command }`. A kind's stop sets exit verdict 1; a wrong `--expect` count is `invalid_params` with the preview as its fix. Test: `test/repair-content.test.ts`.- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--json] [--no-embed] [--yes] [--max-usd USD] [--repo PATH]`. W4.5: re-embedding is paid, so `runReindex(engine, args, { authorized?, interactive? })` calls `requireReindexConsent` (`src/core/reindex-consent.ts`) after the dry-run return and before the managed dispatch for every caller unless `--no-embed` or `authorized` (the upgrade path's TTY yes, the job handler's stored spend record); `src/cli/commands/reindex.ts` renders the exit-3 consent refusal and `cost_cap_exceeded`. The approved finite cap runs the inline pass (and the managed dispatch) under a `BudgetTracker` via `withBudgetTracker`; once it is exhausted (an import swallows the refused embedding) the loop stops at the next page and `reportBudgetStop` exits 1 with `budget_exhausted` in `--json`. `countPending` is exported for `jobs submit reindex` and the mode-switch prompt. The writer pool is sized once from the run's page target (pending, capped by `--limit`) through `resolveWorkersWithClamp`, so Postgres runs over 100 pages default to `DEFAULT_PARALLEL_WORKERS` while PGLite stays at one; `--workers` overrides and the used count is reported as `workers` in the result and JSON (pinned by `test/e2e/reindex-auto-workers-5181.test.ts`). Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled; `--no-embed` still stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`. #5377: on a managed brain (`managedPersistenceEnabled`) the `--markdown` sweep delegates to the projection repairs through `runRepair` (`safe-chunks`, then `contextual-mode` unless `--no-embed`), so it never takes the legacy writer and changes no page revision, journal request or canonical file; `--type` is refused there with the repair commands, and pages the repairs cannot rebuild are reported as `unsupported_pages`; a page the repairs held (`projection_unbuildable`) or failed per item is counted in `failed` (`--json` adds `failures`, exit 1) instead of failing the command. The doctor, upgrade and post-upgrade hints that name `gbrain reindex --markdown` therefore work on both brain modes (C-NEW-5).-- `src/commands/repair-jsonb.ts` — `gbrain repair-jsonb [--dry-run] [--json]`: rewrites `jsonb_typeof='string'` rows in place across 8 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter, subagent_messages.content_blocks, subagent_tool_executions.input, subagent_tool_executions.output). The subagent targets are `jsonPayloadOnly`: those columns can legitimately hold jsonb string scalars (persistToolExec binds a tool's pre-serialized string payload as-is), so their damage predicate additionally requires container-shaped content (`^\s*[\[{]`) that `pg_input_is_valid(..., 'jsonb')` (PG16+ floor, same as the IS JSON predicate `updateSourceConfig` relies on) actually parses — a plain-text value that merely starts with `[` or `{` is never flagged or corrupted. Targets whose table doesn't exist on the brain are skipped via `to_regclass` (brains without the subagent tables), and one target's failure is recorded on stderr while the run continues — earlier repairs are already committed and the v0_12_2 migration orchestrator JSON-parses stdout. `runDoctor`'s `jsonb_integrity` check counts damage with the same predicate over the same target list. Repairs double-encoded rows on Postgres; PGLite no-ops. Idempotent. Pinned by `test/repair-jsonb.test.ts` + `test/doctor.test.ts`.+- `src/commands/repair-jsonb.ts` — `gbrain repair-jsonb [--dry-run] [--json]`: rewrites `jsonb_typeof='string'` rows in place across 8 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter, subagent_messages.content_blocks, subagent_tool_executions.input, subagent_tool_executions.output). The subagent targets are `jsonPayloadOnly`: those columns can legitimately hold jsonb string scalars (persistToolExec binds a tool's pre-serialized string payload as-is), so their damage predicate additionally requires container-shaped content (`^\s*[\[{]`) that `gbrain_try_jsonb(...)` (jsonb or NULL; portable to Postgres 15, unlike the `pg_input_is_valid` it replaced, #7112) actually parses — a plain-text value that merely starts with `[` or `{` is never flagged or corrupted. Targets whose table doesn't exist on the brain are skipped via `to_regclass` (brains without the subagent tables), and one target's failure is recorded on stderr while the run continues — earlier repairs are already committed and the v0_12_2 migration orchestrator JSON-parses stdout. `runDoctor`'s `jsonb_integrity` check counts damage with the same predicate over the same target list. Repairs double-encoded rows on Postgres; PGLite no-ops. Idempotent. Pinned by `test/repair-jsonb.test.ts` + `test/doctor.test.ts`.- `src/commands/report.ts` — Structured report saver (audit trail for maintenance/enrichment). Pages carry `type: note` + `report_type: <name>` (a type the default pack declares; the dream drift report uses the same shape)diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex fd0e1db1bb..edb936d38a 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -43,7 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/resolver-filenames.ts` — central list of accepted routing filenames (`RESOLVER.md`, `AGENTS.md`). Shared by `findRepoRoot`, `check-resolvable`, and skillpack install so every code path walks the same fallback chain.-- `src/core/source-config-sql.ts` + `src/core/sources-load.ts` — canonical recovery for non-object `sources.config` values. The application reader unwraps nested JSON strings and merges recoverable array fragments left-to-right; the shared SQL expression mirrors that policy atomically for both engines, source config updates, archive/restore, and the paste-ready `source_config_shape` doctor repair. `localFederatedSourceIds` reads config through the same parser so stdio/CLI federation cannot silently disagree with `sources list`. `sourceConfigHasRemoteUrl` uses that parser for autopilot pull policy, including PGLite's JSON-string config shape. Invalid fragments degrade to `{}` rather than throwing. Pinned by `test/sources-load.test.ts`, `test/job-pull-policy.test.ts`, `test/list-all-sources.test.ts`, `test/local-federated-search-scope.test.ts`, `test/destructive-guard.test.ts`, and `test/doctor-source-config-shape.test.ts`.+- `src/core/source-config-sql.ts` + `src/core/sources-load.ts` — canonical recovery for non-object `sources.config` values. The application reader unwraps nested JSON strings and merges recoverable array fragments left-to-right; the shared SQL expression mirrors that policy atomically for both engines, source config updates, archive/restore, and the paste-ready `source_config_shape` doctor repair. `localFederatedSourceIds` reads config through the same parser so stdio/CLI federation cannot silently disagree with `sources list`. `sourceConfigHasRemoteUrl` uses that parser for autopilot pull policy, including PGLite's JSON-string config shape. Invalid fragments degrade to `{}` rather than throwing: each string layer goes through `gbrain_try_jsonb(text)` (v263; jsonb or NULL, never raises), portable to Postgres 15 unlike the `IS JSON` it replaced (#7112). `test/postgres15-sql-compat-7112.test.ts` pins the function on both engines and fails when Postgres 16+ only SQL appears in `src/`. Pinned by `test/sources-load.test.ts`, `test/job-pull-policy.test.ts`, `test/list-all-sources.test.ts`, `test/local-federated-search-scope.test.ts`, `test/destructive-guard.test.ts`, and `test/doctor-source-config-shape.test.ts`.- `src/core/source-health.ts` — per-source health metrics for `gbrain sources status` + doctor's `federation_health`. Commit-relative staleness: `newestCommitMs(localPath)` = HEAD committer time via `git log -1 --format=%ct` (fail-open null; NO working-tree mtime parsing — committed content only, robust against the porcelain-mtime bug farm); `lagFromContentMs(contentMs|null, lastSyncMs|null, nowMs, ceilingSeconds?)` = remote/column comparator (null lastSync → null; negative wall-clock → skew passthrough; `contentMs <= lastSync` → **`max(0, wallClock - ceiling)`**; else/null-content → wall-clock). Core logic is pure; only the DEFAULT `ceilingSeconds` reads env, via `resolveStalenessCeilingSeconds()` (`GBRAIN_STALENESS_CEILING_HOURS` overriding `GBRAIN_SYNC_FRESHNESS_FAIL_HOURS`, default 72) — pass the 4th arg for determinism. The caught-up branch RAMPS rather than returning a flat 0: a flat 0 meant a source whose clone vanished reported fresh forever (the dead-daemon class), while a hard step to the ceiling would trip `federation_health` (24h) and `sync_freshness` (24h/72h) in the same instant and skip the warn tier — the alert-storm shape the caught-up branch exists to prevent. Ramping keeps the escalation ordered. `computeAllSourceMetrics(engine, sources, {probeContent?})`: LOCAL (`probeContent:true`, `gbrain sources status`) → `isSourceUnchangedSinceSync(..., {requireCleanWorkingTree:'ignore-untracked'}) ? 0 : wall-clock` (live commit-hash catches HEAD moving to an old-dated commit a timestamp compare would miss); REMOTE (default, `federation_health` on the HTTP MCP path) → `lagFromContentMs(row.newest_content_at, ...)`, NO git subprocess (trust boundary). `commitTimeMs(localPath, sha)` is the `newestCommitMs` sibling pinned to an arbitrary commit (committer time via `git show -s --format=%ct <sha>`, fail-open null, execFileSync array args) — the resumable sync stamps `newest_content_at` against its pinned target commit, not whatever HEAD raced to. Pinned by `test/source-health.test.ts`. `loadSyncFreshnessSources(engine)` loads doctor `sync_freshness`'s sync-eligible sources with their upstream observation columns, falling back for brains without them.diff --git a/llms-full.txt b/llms-full.txtindex 8844e977f3..d135b6eff3 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -6361,10 +6361,17 @@ at most 200 characters. When an unexpected exception in the owner failed awrite (`storage_error` with a generic public message; the class and frame stay owner-only),the line also carries `class=`, `errno=` and `frame=` (the top gbrain sourceframe, repo-relative, for example `src/core/persistence/page-prepare.ts:120`):-the owner diagnostics the receipt points at. The stored receipt keeps the same-identifiers (never the error message) owner-side in `error_detail`, with the-build that ran the attempt; `gbrain write-request <id>` names an owner on-another build than the CLI (`owner_build`) and the restart to run. Connection-wait evidence follows on Postgres:+the owner diagnostics the receipt points at. For a database server error it+adds `error_text=`, `statement=` and `position=` (#7112): the server's primary+message with every quoted value replaced by `…` (an object name such as a+column, a relation or the token a syntax error stopped at is kept), the first+line of the failing statement with its literals replaced, never its+parameters, and the error's character position. A PL/pgSQL `RAISE` keeps no+text, because it can carry page values. The stored receipt keeps the same+identifiers (never an application error's message) owner-side in `error_detail`, with the+build that ran the attempt; on the brain host `gbrain write-request <id> --json`+prints that `error_detail`, and names an owner on another build than the CLI+(`owner_build`) and the restart to run. Connection-wait evidence follows on Postgres:`first_conn_ms` is the time from phase start until the phase obtained aconnection; `checkout=not_observed conn_wait_ms=<n>` means it had not obtainedone after `n` milliseconds (a saturated pool or pooler, not a slow query); anddiff --git a/scripts/ci-ubicloud.ts b/scripts/ci-ubicloud.tsindex b393b4113a..06fc0f8290 100755--- a/scripts/ci-ubicloud.ts+++ b/scripts/ci-ubicloud.ts@@ -18,6 +18,12 @@* gbrain-ci@latest is the prebaked machine image* scripts/ubicloud/build-ci-image.sh builds* --lanes a,b subset of gitleaks,verify,serial,slow,unit,pg-arms,e2e (default all)+ * --pg-image IMAGE Postgres server image of every slot (default+ * pgvector/pgvector:pg16). Another image needs --lanes and+ * is a diagnostic run, never gate evidence: run+ * --lanes pg-arms,e2e --pg-image pgvector/pgvector:pg15 to+ * audit Postgres 15 (#7112); the catalog goldens hold+ * Postgres 16 output and fail on 15 by design* --diff doc-only diffs run only the doc checks and gitleaks (ci:local --diff)* --record-weights write measured durations to scripts/ubicloud/weights.json* --keep leave the VMs running (destroy with ubi-runner.sh down NAME)@@ -116,6 +122,8 @@ interface Opts {/** A machine image (NAME@VERSION) or "stock". */image: string;lanes: Set<string>;+ /** The Postgres server image of every slot; empty keeps setup-ci-vm.sh's default. */+ pgImage: string;diff: boolean;recordWeights: boolean;keep: boolean;@@ -130,6 +138,7 @@ function parseArgs(argv: string[]): Opts {location: GATE_LOCATION,image: process.env.UBI_CI_IMAGE || "stock",lanes: new Set(ALL_LANES),+ pgImage: "",diff: false,recordWeights: false,keep: false,@@ -148,6 +157,7 @@ function parseArgs(argv: string[]): Opts {else if (arg === "--location") opts.location = value();else if (arg === "--image") opts.image = value();else if (arg === "--lanes") opts.lanes = new Set(value().split(","));+ else if (arg === "--pg-image") opts.pgImage = value();else if (arg === "--diff") opts.diff = true;else if (arg === "--record-weights") opts.recordWeights = true;else if (arg === "--keep") opts.keep = true;@@ -156,6 +166,8 @@ function parseArgs(argv: string[]): Opts {}for (const lane of opts.lanes) if (!(ALL_LANES as readonly string[]).includes(lane)) usage(`unknown lane ${lane}`);if (opts.location !== GATE_LOCATION && !argv.includes("--lanes")) usage(`a full gate runs only in ${GATE_LOCATION}. Test timeouts and the mined shard weights are calibrated there; on 2026-10-19 us-east-a2 ran about half as fast and timed out tests that pass in ${GATE_LOCATION}, so a full run in ${opts.location} is not gate evidence. Wait for ${GATE_LOCATION} capacity or run bun run ci:local (and report it as local). To run a diagnostic subset in ${opts.location}, pass --lanes.`);+ if (opts.pgImage && !/^[a-z0-9][a-z0-9._\/-]*(?::[A-Za-z0-9._-]+)?$/.test(opts.pgImage)) usage(`--pg-image ${opts.pgImage} is not an image reference`);+ if (opts.pgImage && !argv.includes("--lanes")) usage("a full gate runs on the default Postgres image; --pg-image is a diagnostic run, so pass --lanes (for example --lanes pg-arms,e2e).");if (!Number.isInteger(opts.ttlHours) || opts.ttlHours < 0 || opts.ttlHours > 8760) usage("--ttl-hours must be a whole number of hours from 0 (no expiry) to 8760");if (!Number.isInteger(opts.vms) || opts.vms < 0 || (opts.vms === 0 && argv.includes("--vms"))) usage("--vms must be a positive integer");// Three slots per eight vCPUs: each slot's bun process, its children and its@@ -169,7 +181,7 @@ function parseArgs(argv: string[]): Opts {function usage(message: string): never {console.error(`ci-ubicloud: ${message}`);- console.error("usage: bun run scripts/ci-ubicloud.ts [--vms N] [--size SIZE] [--slots N] [--location LOC] [--image IMAGE] [--lanes a,b] [--diff] [--record-weights] [--keep] [--ttl-hours N]");+ console.error("usage: bun run scripts/ci-ubicloud.ts [--vms N] [--size SIZE] [--slots N] [--location LOC] [--image IMAGE] [--lanes a,b] [--pg-image IMAGE] [--diff] [--record-weights] [--keep] [--ttl-hours N]");process.exit(2);}@@ -478,7 +490,7 @@ async function main() {vm.state = "setup";// System packages, Bun and image pulls need no checkout: setup starts now// and waits for the marker the upload writes when it lands.- const env = `SLOTS=${opts.slots} BUN_VERSION=${quote(bunVersion)} GITLEAKS=${opts.lanes.has("gitleaks") ? 1 : 0} CHECKOUT=${REMOTE_DIR} CHECKOUT_MARKER=${UNPACKED_MARKER}`;+ const env = `SLOTS=${opts.slots} BUN_VERSION=${quote(bunVersion)} GITLEAKS=${opts.lanes.has("gitleaks") ? 1 : 0} CHECKOUT=${REMOTE_DIR} CHECKOUT_MARKER=${UNPACKED_MARKER}${opts.pgImage ? ` PG_IMAGE=${quote(opts.pgImage)}` : ""}`;const setupRun = runner(["ssh", vm.name, `${env} bash -s`], { input: SETUP_SCRIPT, out: `${setupLog}.bootstrap`, timeoutMs: 15 * 60 * 1000 });const pack = await packed;if (pack.code !== 0) throw new Error(`packing the checkout failed: ${pack.stdout.trim().split("\n").slice(-3).join(" | ")}`);diff --git a/scripts/e2e-postgres15.txt b/scripts/e2e-postgres15.txtnew file mode 100644index 0000000000..60dc3c5a15--- /dev/null+++ b/scripts/e2e-postgres15.txt@@ -0,0 +1,29 @@+# Postgres 15 compatibility lane (#7112; e2e.yml job postgres15-compat).+#+# gbrain supports Postgres 15 (migration v011 refuses older servers), while+# PGLite runs Postgres 17 and every other Postgres lane runs 16, so SQL that+# only 16+ parses ships green everywhere else. This lane runs a targeted set of+# the write, sync, jobs and migration files against pgvector/pgvector:pg15.+# Every file applies the whole migration chain to a fresh database first.+#+# Left out on purpose: the catalog goldens (schema-catalog-golden,+# schema-migrations-replay) pin pg_get_viewdef text, which Postgres 16 deparses+# differently, so they hold Postgres 16 output by design.+#+# Format: one repo-relative path per line; # starts a comment.+test/e2e/postgres15-sql-compat-7112-postgres.test.ts+test/e2e/managed-sync-failures.test.ts+test/e2e/put-page-persistence-postgres.test.ts+test/e2e/persistence-publication-parity.test.ts+test/e2e/sync.test.ts+test/e2e/sync-reconcile-postgres.test.ts+test/e2e/sync-run-workers-postgres.test.ts+test/e2e/restore-source-config-jsonb-postgres.test.ts+test/e2e/op-checkpoint-jsonb-parity.test.ts+test/e2e/fact-fingerprint-search-path-postgres.test.ts+test/e2e/minions-resilience.test.ts+test/e2e/minions-concurrency.test.ts+test/e2e/jobs-agent-scope-postgres.test.ts+test/e2e/migrate-chain.test.ts+test/e2e/migration-flow.test.ts+test/e2e/doctor-revision-backfill-postgres.test.tsdiff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 9f05d0a5f3..e8d319d7d7 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -267,6 +267,7 @@ test/physical-root-birth-tolerance-6501.test.ts samePhysicalBirth (#6501) 5 readtest/postgres-driver-vendor.test.ts vendored Postgres driver packaging 5 readFileSynctest/postgres-engine.test.ts postgres-engine / search date filtering 2 source-surface-helpertest/postgres-engine.test.ts postgres-engine / search path timeout isolation 7 source-surface-helper+test/postgres15-sql-compat-7112.test.ts #7112: shipped SQL parses on every supported Postgres (15+) 2 readFileSynctest/private-visibility.test.ts shared private predicate lives once (#4352 remediation) 1 readFileSynctest/q2-typing-package.test.ts (file-level) 3 readFileSynctest/redos-hardening.test.ts #1569 --no-schema-pack + heartbeat wiring (structural) 2 readFileSync,source-surface-helperdiff --git a/scripts/ubicloud/setup-ci-vm.sh b/scripts/ubicloud/setup-ci-vm.shindex ede301a31c..3fe8f8f18d 100755--- a/scripts/ubicloud/setup-ci-vm.sh+++ b/scripts/ubicloud/setup-ci-vm.sh@@ -26,6 +26,8 @@## Knobs: SLOTS (default nproc), BUN_VERSION (default 1.4.3), GITLEAKS=0|1,# CHECKOUT (default .), CHECKOUT_MARKER (default: none, checkout present),+# PG_IMAGE (default pgvector/pgvector:pg16; ci-ubicloud.ts --pg-image, e.g.+# pgvector/pgvector:pg15 for the #7112 compatibility audit),# PREPARE_IMAGE=1 (install packages and pull images only, then reset# cloud-init so the stopped VM can be captured as a machine image).set -euo pipefail@@ -37,7 +39,7 @@ CHECKOUT="${CHECKOUT:-.}"CHECKOUT_MARKER="${CHECKOUT_MARKER:-}"GITLEAKS_VERSION=8.30.1APT_PACKAGES=(git ca-certificates python3 procps postgresql-client jq nodejs gcc libc6-dev)-PG_IMAGE=pgvector/pgvector:pg16+PG_IMAGE="${PG_IMAGE:-pgvector/pgvector:pg16}"PGBOUNCER_IMAGE=edoburu/pgbouncer:latest# Throwaway password of the loopback-only test servers (docker-compose.ci.yml uses the same).PG_PASSWORD=postgresdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 0e71e7f8e2..b50d5b1aa8 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1016,6 +1016,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.324.0', text: 'New `append_page` adds text to the end of a page in time proportional to the text added, idempotent by `request_id`; use it for conversation logs instead of re-putting the page. `expected_tail_sha256` (the `tail_sha256` that `get_page` with `body: \'none\'` returns) refuses `tail_changed` when another writer appended first. `gbrain append <slug> [--file f | stdin]` calls it.' },{ since: '0.60.324.0', text: 'New upload sessions (`begin_page_upload`, `upload_page_part`, `get_page_upload`, `commit_page_upload`, `abort_page_upload`) let remote and thin clients write pages larger than one request, up to the page ceiling; `gbrain put --file` and `gbrain capture --file` use them on remote brains. A session is bound to the principal, source and page that began it (any other caller gets `upload_not_found`), staged bytes count against `persistence.limits` upload quotas (`write_quota_exhausted`), and an idle session expires after an hour. Locally, `gbrain put --file` and `gbrain capture --file` stream a file over 24 MiB straight in.' },{ since: '0.60.324.0', text: '`edit_page` accepts `within` to restrict a match to a range returned by a window read (`edit_target`), and edits a page stored in segments by rewriting only the segments the match touches instead of reading the whole page back.' },+ // #7112 (Postgres 15 SQL compatibility, owner-exception error text). `since` is restamped at the merge slot.+ { since: 'TBD', text: 'Managed sync, put_page, source config updates, archive and restore, and the dream-breaker reset work again on Postgres 15: they used the Postgres 16+ `IS JSON` predicate (and doctor jsonb_integrity and `gbrain repair-jsonb` used `pg_input_is_valid`), a syntax error (42601) on Postgres 15 that failed every managed sync checkpoint. They now use a new `gbrain_try_jsonb(text)` function (migration v263) on every server. The same guard no longer fails a config merge or a dream-breaker reset whose stored text is JSON but not jsonb (a \\u0000 escape); that value now reads as an empty object, like other unparseable text.' },+ { since: 'TBD', text: 'A write that ends `storage_error` on an unexpected database server error now keeps, owner-side in the receipt, the server message with quoted values replaced by … (`error_text`), the first line of the failing statement with its literals replaced and never its parameters (`statement`), and the error position; a PL/pgSQL RAISE keeps no text. On the brain host `gbrain write-request <id> --json` now prints the receipt\'s `error_detail`, and the persistence consumer log line adds `error_text=`, `statement=` and `position=`. Remote readers see no new field.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.tsindex 42af247918..ee6154afd4 100644--- a/src/core/ops/persistence.ts+++ b/src/core/ops/persistence.ts@@ -128,6 +128,8 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: Woperation: row.operation, source_id: row.source_id, slug: row.slug,...await liveSearchable(ctx, { request_id: row.request_id, state: row.state, source_id: row.source_id, slug: row.slug, searchable: row.outcome?.searchable }),...(mismatch ? { owner_build: mismatch } : {}),+ // #7112: the owner-side detail (an owner exception's class, errno, frame, redacted database error text and statement) for a trusted local reader only.+ ...(ctx.remote === false && row.error_detail ? { error_detail: row.error_detail } : {}),...(diagnostic ? { write_error: row.error_code, write_error_message: diagnostic.message, write_error_reason: diagnostic.reason, suggestion: diagnostic.suggestion } : {}),...(terminal ? { diagnosis: { category: terminal.category, public_category: terminal.public_category, code: terminal.code, class: terminal.class, safe_actions: terminal.safe_actions, needs_human: terminal.needs_human,...(terminal.human_reason ? { human_reason: terminal.human_reason } : {}), escalate: terminal.escalate, historical: terminal.historical,diff --git a/src/core/persistence/connector-errors.ts b/src/core/persistence/connector-errors.tsindex a43800f4df..a1adef3756 100644--- a/src/core/persistence/connector-errors.ts+++ b/src/core/persistence/connector-errors.ts@@ -73,7 +73,7 @@ export const DATABASE_REFUSAL_HINT = 'This is not a content conflict: a gbrain p/** #5974: another database trigger (named in write_error_detail.raiser) refused the write. *//** #6719: an owner exception's recorded identity (class, errno, frame, build) does not name its cause; nothing proves the database refused it. */export const ownerExceptionHint = (requestId: string) => 'An unexpected owner exception ended this write and nothing was committed; its cause is unknown from the recorded identity alone. '- + `On the brain host run gbrain write-request ${requestId} --json and read error_detail (error_class, errno, frame, attempt.consumer_version) beside the persistence consumer log; `+ + `On the brain host run gbrain write-request ${requestId} --json and read error_detail (error_class, errno, frame, attempt.consumer_version, and for a database error its redacted error_text, statement and position) beside the persistence consumer log; `+ 'report that identity and the gbrain version on the issue tracker, and upgrade when a fix ships. Do not replay the old intent to diagnose it.';/** #6719: an origin that names no database refusal (or none at all) stays unknown rather than read as a trigger. */diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex 12b0935115..6c855ad60a 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -43,11 +43,14 @@ export interface PublicationFailureDetail {export type FenceRefusalDetail = FenceFailureDetail & Pick<PublicationFailureDetail, 'stage' | 'attempt'>;/*** #5929: an unexpected exception in the owner. Fixed identifiers only, never- * the message, SQL or values: the error class, its errno and the top gbrain- * source frame (repo-relative). All three are owner-only.+ * application error text or values: the error class, its errno and the top gbrain+ * source frame (repo-relative). #7112: a database server error also keeps its+ * redacted primary message, the first line of the failing statement and the+ * error position (`databaseErrorText`). All of it is owner-only.*/export interface OwnerExceptionDetail extends Pick<PublicationFailureDetail, 'stage' | 'attempt'> {origin: 'owner_exception'; error_class?: string; errno?: string; frame?: string;+ error_text?: string; statement?: string; position?: number;}/** A `fact_withdrawn` refusal's `withdrawn` object (`facts/withdrawal.ts`), plus the attempt stamp. */export type WithdrawalRefusalDetail = WithdrawalFailureDetail & Pick<PublicationFailureDetail, 'stage' | 'attempt'>;@@ -171,9 +174,54 @@ function gbrainFrame(stack: unknown): string | undefined {* #5929: the public message of an unexpected owner exception. Remote submitters read it, so it names no class,* errno or build; those stay in the owner-only detail, `gbrain write-request <id>` on the brain host and the consumer log.*/-export const OWNER_EXCEPTION_MESSAGE = 'Publication failed on an unexpected owner exception. On the brain host, gbrain write-request <request_id> and the persistence consumer log name its class, source frame and owner build.';+export const OWNER_EXCEPTION_MESSAGE = 'Publication failed on an unexpected owner exception. On the brain host, gbrain write-request <request_id> and the persistence consumer log name its class, database error text, statement, source frame and owner build.';-/** #5929: the bounded identity of an unexpected owner exception (class, errno, frame), kept owner-only. */+const ERROR_TEXT_MAX = 240;+const STATEMENT_MAX = 160;+/** The words after which a server message's double-quoted token names an object (or the token a syntax error stopped at), not a value. */+const IDENTIFIER_CONTEXT = /\b(?:near|column|relation|constraint|table|index|type|schema|function|sequence|role|database|extension|trigger|view|parameter|operator|policy|cursor|savepoint|prepared statement|portal)\s*$/i;++/**+ * The first non-blank line with every quoted run replaced: a single-quoted literal or dollar-quoted body becomes `'…'`+ * or `$…$`, a double-quoted token stays only when `keepQuoted` says it names an object, and an unterminated quote ends+ * the text. Control characters become spaces; at most `max` characters.+ */+function redactLine(text: string, max: number, keepQuoted: (inner: string, before: string) => boolean): string | undefined {+ const line = text.split('\n').map(part => part.trim()).find(part => part.length > 0);+ if (!line) return undefined;+ let out = '';+ for (let i = 0; i < line.length;) {+ const ch = line[i]!;+ const tag = ch === '$' ? /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/.exec(line.slice(i))?.[0] : undefined;+ if (ch !== "'" && ch !== '"' && !tag) { out += ch; i++; continue; }+ const open = tag ?? ch;+ let close = line.indexOf(open, i + open.length);+ while (!tag && close >= 0 && line[close + 1] === ch) close = line.indexOf(ch, close + 2);+ if (close < 0) { out += '…'; break; }+ const inner = line.slice(i + open.length, close);+ out += ch === '"' && keepQuoted(inner, out) ? `"${inner}"` : tag ? '$…$' : `${ch}…${ch}`;+ i = close + open.length;+ }+ const clean = out.replace(/[\x00-\x1f\x7f]/g, ' ');+ return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;+}++/**+ * #7112: what a database server error says, without the values it can carry. Only a server-generated error qualifies+ * (a five-character SQLSTATE and a severity); a PL/pgSQL RAISE carries caller text and is skipped, like `databaseRefusal`.+ * The message keeps a double-quoted token only where the server names an object or the token a syntax error stopped at;+ * the statement keeps its first line with literals replaced, never its parameters.+ */+function databaseErrorText(e: Record<string, unknown>): Pick<OwnerExceptionDetail, 'error_text' | 'statement' | 'position'> {+ if (typeof e.code !== 'string' || !/^[0-9A-Z]{5}$/.test(e.code) || typeof e.severity !== 'string' || e.routine === 'exec_stmt_raise') return {};+ const errorText = typeof e.message === 'string'+ ? redactLine(e.message, ERROR_TEXT_MAX, (inner, before) => IDENT.test(inner) && IDENTIFIER_CONTEXT.test(before.trimEnd())) : undefined;+ const statement = typeof e.query === 'string' ? redactLine(e.query, STATEMENT_MAX, inner => IDENT.test(inner)) : undefined;+ const position = Number(e.position);+ return { ...(errorText ? { error_text: errorText } : {}), ...(statement ? { statement } : {}), ...(Number.isInteger(position) && position > 0 ? { position } : {}) };+}++/** #5929: the bounded identity of an unexpected owner exception (class, errno, frame, and a database error's redacted text), kept owner-only. */export function ownerExceptionFailure(error: unknown): PublicationFailure {const e = (error && typeof error === 'object' ? error : {}) as { constructor?: { name?: unknown }; code?: unknown; errno?: unknown; stack?: unknown; osError?: unknown };const errorClass = ident(e.constructor?.name);@@ -182,14 +230,17 @@ export function ownerExceptionFailure(error: unknown): PublicationFailure {const errno = raw && ERRNO.test(raw) ? raw : undefined;const frame = gbrainFrame(e.stack);return { code: 'storage_error', message: OWNER_EXCEPTION_MESSAGE,- detail: { origin: 'owner_exception', ...(errorClass ? { error_class: errorClass } : {}), ...(errno ? { errno } : {}), ...(frame ? { frame } : {}) } };+ detail: { origin: 'owner_exception', ...(errorClass ? { error_class: errorClass } : {}), ...(errno ? { errno } : {}), ...(frame ? { frame } : {}),+ ...databaseErrorText(e as Record<string, unknown>) } };}-/** Owner-side text for the consumer log: the class and frame of an owner exception, else nothing. */+/** Owner-side text for the consumer log: the class, frame and database error text of an owner exception, else nothing. */export function ownerExceptionLogText(detail: unknown): string {const d = detail as Partial<OwnerExceptionDetail> | null;if (!d || d.origin !== 'owner_exception') return '';- return [d.error_class ? ` class=${d.error_class}` : '', d.errno ? ` errno=${d.errno}` : '', d.frame ? ` frame=${d.frame}` : ''].join('');+ return [d.error_class ? ` class=${d.error_class}` : '', d.errno ? ` errno=${d.errno}` : '', d.frame ? ` frame=${d.frame}` : '',+ d.error_text ? ` error_text=${JSON.stringify(d.error_text)}` : '', d.statement ? ` statement=${JSON.stringify(d.statement)}` : '',+ d.position ? ` position=${d.position}` : ''].join('');}/**diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex cc64b743b7..34ac28d9ea 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -32,7 +32,7 @@ CREATE TABLE IF NOT EXISTS sources ();CREATE OR REPLACE FUNCTION gbrain_try_jsonb(input text) RETURNS jsonb- LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog AS \$fn\$+ LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog, public AS \$fn\$BEGINRETURN input::jsonb;EXCEPTION WHEN data_exception THENdiff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex b901b4a438..defc56577d 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -66,7 +66,7 @@ CREATE TABLE IF NOT EXISTS sources (-- IS JSON and pg_input_is_valid() are Postgres 16+. Migration v263 installs it-- on existing brains.CREATE OR REPLACE FUNCTION gbrain_try_jsonb(input text) RETURNS jsonb- LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog AS \$fn\$+ LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog, public AS \$fn\$BEGINRETURN input::jsonb;EXCEPTION WHEN data_exception THENdiff --git a/src/core/schema-migrations/v263-try-jsonb-function.ts b/src/core/schema-migrations/v263-try-jsonb-function.tsindex c6c7c245a3..1c3e11bb1f 100644--- a/src/core/schema-migrations/v263-try-jsonb-function.ts+++ b/src/core/schema-migrations/v263-try-jsonb-function.ts@@ -1,7 +1,7 @@import type { Migration } from './types.ts';// Applied by src/core/migrate.ts on the next initSchema(); src/schema.sql-// carries the same function for fresh installs.+// carries the same function, byte for byte, for fresh installs.//// #7112: gbrain_try_jsonb(text) parses text as jsonb and returns NULL when it// is not valid jsonb, instead of raising. It replaces the SQL/JSON `IS JSON`@@ -15,12 +15,12 @@ export const v263: Migration = {name: 'try_jsonb_function',idempotent: true,sql: `- CREATE OR REPLACE FUNCTION gbrain_try_jsonb(input text) RETURNS jsonb- LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog AS $fn$- BEGIN- RETURN input::jsonb;- EXCEPTION WHEN data_exception THEN- RETURN NULL;- END $fn$;- `,+CREATE OR REPLACE FUNCTION gbrain_try_jsonb(input text) RETURNS jsonb+ LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog, public AS $fn$+BEGIN+ RETURN input::jsonb;+EXCEPTION WHEN data_exception THEN+ RETURN NULL;+END $fn$;+`,};diff --git a/src/schema.sql b/src/schema.sqlindex bb1456367d..b5cb777853 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -62,7 +62,7 @@ CREATE TABLE IF NOT EXISTS sources (-- IS JSON and pg_input_is_valid() are Postgres 16+. Migration v263 installs it-- on existing brains.CREATE OR REPLACE FUNCTION gbrain_try_jsonb(input text) RETURNS jsonb- LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog AS $fn$+ LANGUAGE plpgsql IMMUTABLE STRICT SET search_path = pg_catalog, public AS $fn$BEGINRETURN input::jsonb;EXCEPTION WHEN data_exception THENdiff --git a/test/e2e/postgres15-sql-compat-7112-postgres.test.ts b/test/e2e/postgres15-sql-compat-7112-postgres.test.tsnew file mode 100644index 0000000000..5bd78aeb02--- /dev/null+++ b/test/e2e/postgres15-sql-compat-7112-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../postgres15-sql-compat-7112.test.ts'));diff --git a/test/fixtures/fold-hook-noop-6712.json b/test/fixtures/fold-hook-noop-6712.jsonindex d66e124989..2cf51abf0c 100644--- a/test/fixtures/fold-hook-noop-6712.json+++ b/test/fixtures/fold-hook-noop-6712.json@@ -118,7 +118,7 @@"SELECT 1 FROM persistence_requests r WHERE r.source_id=$1 AND r.slug='__managed_sync_checkpoint__' AND r.intent IS NOT NULL AND NOT r.compacted AND r.operation='submit_job' AND r.intent->>'kind'='managed_sync_checkpoint' AND r.state IN ('failed','conflict','cancelled') AND NOT EXISTS (SELECT 1 FROM persistence_requests c WHERE (c.source_id=r.source_id AND c.slug=r.slug AND c.sequence>r.sequence AND ( (c.digest=r.digest AND c.state IN ('committed','failed','queued','running','recovering')) OR (c.state IN ('committed','queued','running','recovering') AND (c.operation IN ('delete_page','purge_page') OR r.operation='put_page')) OR (r.slug='__managed_sync_checkpoint__' AND r.operation='submit_job' AND c.state='committed' AND c.operation='submit_job' AND COALESCE((SELECT k.intent->>'kind' FROM persistence_requests k WHERE k.id=r.id),'managed_sync_checkpoint')='managed_sync_checkpoint' AND COALESCE(c.intent->>'kind','managed_sync_checkpoint')='managed_sync_checkpoint') OR (r.operation='put_page' AND c.state='failed' AND c.operation='put_page' AND COALESCE(NOT (c.intent ? 'kind'), false)) OR (r.operation='submit_job' AND c.operation='submit_job' AND c.state='committed' AND COALESCE(c.intent ? 'retryOf', false) AND EXISTS (SELECT 1 FROM persistence_requests k, persistence_requests cc WHERE k.id=r.id AND cc.sequence=c.sequence AND k.intent->>'kind' IN ('connector_v2_import','connector_v2_delete','connector_v2_checkpoint') AND cc.intent->>'kind'=k.intent->>'kind' AND cc.principal_kind=k.principal_kind AND cc.principal_id=k.principal_id AND cc.source_incarnation=k.source_incarnation AND EXISTS (WITH RECURSIVE lineage(request_id, sequence, intent, depth) AS ( SELECT cc.request_id, cc.sequence, cc.intent, 0 UNION ALL SELECT p.request_id, p.sequence, p.intent, l.depth+1 FROM lineage l JOIN persistence_requests p ON p.principal_kind=k.principal_kind AND p.principal_id=k.principal_id AND p.request_id=CASE WHEN l.intent->>'retryOf' ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$' THEN (l.intent->>'retryOf')::uuid END WHERE l.depth<32 AND p.sequence<l.sequence AND p.source_id=k.source_id AND p.source_incarnation=k.source_incarnation AND p.operation=k.operation AND p.slug=k.slug AND p.intent->>'kind'=k.intent->>'kind') SELECT 1 FROM lineage WHERE request_id=k.request_id)))))) LIMIT 1","SELECT p.id, p.slug, p.source_path, p.knowledge_revision::text AS revision, p.deleted_at IS NOT NULL AS deleted, p.revision_write_request_id::text AS request_id, c.fingerprint IS NOT NULL AS has_record, c.origin IS NOT DISTINCT FROM p.source_path AS rec_origin_same, CASE WHEN c.origin IS DISTINCT FROM p.source_path THEN c.origin END AS rec_origin, c.blob_oid AS rec_blob_oid, c.disk_blob_oid IS NOT DISTINCT FROM c.blob_oid AS rec_disk_same, CASE WHEN c.disk_blob_oid IS DISTINCT FROM c.blob_oid THEN c.disk_blob_oid END AS rec_disk_blob_oid, c.revision IS NULL AS rec_revision_null, NULLIF(c.revision, p.knowledge_revision::text) AS rec_revision, CASE WHEN c.parser IS DISTINCT FROM $4::jsonb THEN c.parser::text END AS rec_parser, c.parser = $4::jsonb AS rec_parser_expected, c.full_episode AS rec_full_episode, c.working AS rec_working FROM pages p LEFT JOIN (SELECT fingerprint, completed_keys->0->>'origin' AS origin, completed_keys->0->>'blob_oid' AS blob_oid, completed_keys->0->>'disk_blob_oid' AS disk_blob_oid, completed_keys->0->>'revision' AS revision, completed_keys->0->'parser' AS parser, completed_keys->0->>'full_episode' AS full_episode, (completed_keys->0->'working')::text AS working FROM op_checkpoints WHERE op=$2) c ON c.fingerprint=$3||p.id::text WHERE p.source_id=$1 AND p.source_path IS NOT NULL AND p.id = ANY($5::bigint[]) ORDER BY p.id","SELECT p.id::text AS id, r.intent->>'level' AS level, r.intent->>'path' AS path FROM pages p JOIN persistence_requests r ON r.id=p.revision_write_request_id WHERE p.source_id=$1 AND p.id = ANY($2::bigint[])",- "UPDATE sources SET last_commit=$3,last_sync_at=now(), config=jsonb_set(( WITH RECURSIVE root_layers(value, depth) AS ( SELECT COALESCE(config, '{}'::jsonb), 0 UNION ALL SELECT (value #>> '{}')::jsonb, depth + 1 FROM root_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND (value #>> '{}') IS JSON ), root(value) AS ( SELECT value FROM root_layers ORDER BY depth DESC LIMIT 1 ), fragment_seeds(ordinality, value) AS ( SELECT 0::bigint, value FROM root WHERE jsonb_typeof(value) = 'object' UNION ALL SELECT item.ordinality, item.value FROM root, LATERAL jsonb_array_elements( CASE WHEN jsonb_typeof(root.value) = 'array' THEN root.value ELSE '[]'::jsonb END ) WITH ORDINALITY AS item(value, ordinality) ), fragment_layers(ordinality, value, depth) AS ( SELECT ordinality, value, 0 FROM fragment_seeds UNION ALL SELECT ordinality, (value #>> '{}')::jsonb, depth + 1 FROM fragment_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND (value #>> '{}') IS JSON ), fragments AS ( SELECT DISTINCT ON (ordinality) ordinality, value FROM fragment_layers ORDER BY ordinality, depth DESC ) SELECT COALESCE( jsonb_object_agg(entry.key, entry.value ORDER BY fragments.ordinality), '{}'::jsonb ) FROM fragments CROSS JOIN LATERAL jsonb_each( CASE WHEN jsonb_typeof(fragments.value) = 'object' THEN fragments.value ELSE '{}'::jsonb END ) AS entry(key, value) ),'{slug_root_mode}',to_jsonb(CASE WHEN $6::boolean THEN COALESCE(config->>'slug_root_mode',$5::text) ELSE $5::text END)), newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL) WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR last_commit=$3) AND ($6::boolean OR config->>'slug_root_mode' IS NULL OR config->>'slug_root_mode'=$5) RETURNING id",+ "UPDATE sources SET last_commit=$3,last_sync_at=now(), config=jsonb_set(( WITH RECURSIVE root_layers(value, depth) AS ( SELECT COALESCE(config, '{}'::jsonb), 0 UNION ALL SELECT gbrain_try_jsonb(value #>> '{}'), depth + 1 FROM root_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND gbrain_try_jsonb(value #>> '{}') IS NOT NULL ), root(value) AS ( SELECT value FROM root_layers ORDER BY depth DESC LIMIT 1 ), fragment_seeds(ordinality, value) AS ( SELECT 0::bigint, value FROM root WHERE jsonb_typeof(value) = 'object' UNION ALL SELECT item.ordinality, item.value FROM root, LATERAL jsonb_array_elements( CASE WHEN jsonb_typeof(root.value) = 'array' THEN root.value ELSE '[]'::jsonb END ) WITH ORDINALITY AS item(value, ordinality) ), fragment_layers(ordinality, value, depth) AS ( SELECT ordinality, value, 0 FROM fragment_seeds UNION ALL SELECT ordinality, gbrain_try_jsonb(value #>> '{}'), depth + 1 FROM fragment_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND gbrain_try_jsonb(value #>> '{}') IS NOT NULL ), fragments AS ( SELECT DISTINCT ON (ordinality) ordinality, value FROM fragment_layers ORDER BY ordinality, depth DESC ) SELECT COALESCE( jsonb_object_agg(entry.key, entry.value ORDER BY fragments.ordinality), '{}'::jsonb ) FROM fragments CROSS JOIN LATERAL jsonb_each( CASE WHEN jsonb_typeof(fragments.value) = 'object' THEN fragments.value ELSE '{}'::jsonb END ) AS entry(key, value) ),'{slug_root_mode}',to_jsonb(CASE WHEN $6::boolean THEN COALESCE(config->>'slug_root_mode',$5::text) ELSE $5::text END)), newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL) WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR last_commit=$3) AND ($6::boolean OR config->>'slug_root_mode' IS NULL OR config->>'slug_root_mode'=$5) RETURNING id","INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES ($1, $2, jsonb_build_array(jsonb_strip_nulls(jsonb_build_object('run_id',$3::text,'at',now(),'changed',$4::int,'extract',$5::boolean,'since',$6::text))), now()) ON CONFLICT (op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=CASE WHEN jsonb_array_length(op_checkpoints.completed_keys)>=16 THEN (op_checkpoints.completed_keys-0)||EXCLUDED.completed_keys ELSE op_checkpoints.completed_keys||EXCLUDED.completed_keys END","SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND sequence > $3::bigint AND state='committed' AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence","INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now()) ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now() WHERE $4::boolean OR op_checkpoints.completed_keys->0->>'lease_token'=$5 RETURNING 1",@@ -250,7 +250,7 @@"(SELECT 'r:'||request_id::text AS id FROM persistence_requests WHERE state IN ('queued','running','recovering') AND (worktree_id=$1::uuid OR worktree_id IS NULL AND source_id=$4 AND source_incarnation=$5::uuid) AND request_id IS DISTINCT FROM $2::uuid LIMIT $3) UNION ALL (SELECT 'e:'||e.id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.worktree_id=$1::uuid AND e.kind='git' AND e.state IN ('queued','running') LIMIT $3)","SELECT p.id, p.slug, p.source_path, p.knowledge_revision::text AS revision, p.deleted_at IS NOT NULL AS deleted, p.revision_write_request_id::text AS request_id, c.fingerprint IS NOT NULL AS has_record, c.origin IS NOT DISTINCT FROM p.source_path AS rec_origin_same, CASE WHEN c.origin IS DISTINCT FROM p.source_path THEN c.origin END AS rec_origin, c.blob_oid AS rec_blob_oid, c.disk_blob_oid IS NOT DISTINCT FROM c.blob_oid AS rec_disk_same, CASE WHEN c.disk_blob_oid IS DISTINCT FROM c.blob_oid THEN c.disk_blob_oid END AS rec_disk_blob_oid, c.revision IS NULL AS rec_revision_null, NULLIF(c.revision, p.knowledge_revision::text) AS rec_revision, CASE WHEN c.parser IS DISTINCT FROM $4::jsonb THEN c.parser::text END AS rec_parser, c.parser = $4::jsonb AS rec_parser_expected, c.full_episode AS rec_full_episode, c.working AS rec_working FROM pages p LEFT JOIN (SELECT fingerprint, completed_keys->0->>'origin' AS origin, completed_keys->0->>'blob_oid' AS blob_oid, completed_keys->0->>'disk_blob_oid' AS disk_blob_oid, completed_keys->0->>'revision' AS revision, completed_keys->0->'parser' AS parser, completed_keys->0->>'full_episode' AS full_episode, (completed_keys->0->'working')::text AS working FROM op_checkpoints WHERE op=$2) c ON c.fingerprint=$3||p.id::text WHERE p.source_id=$1 AND p.source_path IS NOT NULL AND p.id = ANY($5::bigint[]) ORDER BY p.id","SELECT p.id::text AS id, r.intent->>'level' AS level, r.intent->>'path' AS path FROM pages p JOIN persistence_requests r ON r.id=p.revision_write_request_id WHERE p.source_id=$1 AND p.id = ANY($2::bigint[])",- "UPDATE sources SET last_commit=$3,last_sync_at=now(), config=jsonb_set(( WITH RECURSIVE root_layers(value, depth) AS ( SELECT COALESCE(config, '{}'::jsonb), 0 UNION ALL SELECT (value #>> '{}')::jsonb, depth + 1 FROM root_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND (value #>> '{}') IS JSON ), root(value) AS ( SELECT value FROM root_layers ORDER BY depth DESC LIMIT 1 ), fragment_seeds(ordinality, value) AS ( SELECT 0::bigint, value FROM root WHERE jsonb_typeof(value) = 'object' UNION ALL SELECT item.ordinality, item.value FROM root, LATERAL jsonb_array_elements( CASE WHEN jsonb_typeof(root.value) = 'array' THEN root.value ELSE '[]'::jsonb END ) WITH ORDINALITY AS item(value, ordinality) ), fragment_layers(ordinality, value, depth) AS ( SELECT ordinality, value, 0 FROM fragment_seeds UNION ALL SELECT ordinality, (value #>> '{}')::jsonb, depth + 1 FROM fragment_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND (value #>> '{}') IS JSON ), fragments AS ( SELECT DISTINCT ON (ordinality) ordinality, value FROM fragment_layers ORDER BY ordinality, depth DESC ) SELECT COALESCE( jsonb_object_agg(entry.key, entry.value ORDER BY fragments.ordinality), '{}'::jsonb ) FROM fragments CROSS JOIN LATERAL jsonb_each( CASE WHEN jsonb_typeof(fragments.value) = 'object' THEN fragments.value ELSE '{}'::jsonb END ) AS entry(key, value) ),'{slug_root_mode}',to_jsonb(CASE WHEN $6::boolean THEN COALESCE(config->>'slug_root_mode',$5::text) ELSE $5::text END)), newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL) WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR last_commit=$3) AND ($6::boolean OR config->>'slug_root_mode' IS NULL OR config->>'sl",+ "UPDATE sources SET last_commit=$3,last_sync_at=now(), config=jsonb_set(( WITH RECURSIVE root_layers(value, depth) AS ( SELECT COALESCE(config, '{}'::jsonb), 0 UNION ALL SELECT gbrain_try_jsonb(value #>> '{}'), depth + 1 FROM root_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND gbrain_try_jsonb(value #>> '{}') IS NOT NULL ), root(value) AS ( SELECT value FROM root_layers ORDER BY depth DESC LIMIT 1 ), fragment_seeds(ordinality, value) AS ( SELECT 0::bigint, value FROM root WHERE jsonb_typeof(value) = 'object' UNION ALL SELECT item.ordinality, item.value FROM root, LATERAL jsonb_array_elements( CASE WHEN jsonb_typeof(root.value) = 'array' THEN root.value ELSE '[]'::jsonb END ) WITH ORDINALITY AS item(value, ordinality) ), fragment_layers(ordinality, value, depth) AS ( SELECT ordinality, value, 0 FROM fragment_seeds UNION ALL SELECT ordinality, gbrain_try_jsonb(value #>> '{}'), depth + 1 FROM fragment_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND gbrain_try_jsonb(value #>> '{}') IS NOT NULL ), fragments AS ( SELECT DISTINCT ON (ordinality) ordinality, value FROM fragment_layers ORDER BY ordinality, depth DESC ) SELECT COALESCE( jsonb_object_agg(entry.key, entry.value ORDER BY fragments.ordinality), '{}'::jsonb ) FROM fragments CROSS JOIN LATERAL jsonb_each( CASE WHEN jsonb_typeof(fragments.value) = 'object' THEN fragments.value ELSE '{}'::jsonb END ) AS entry(key, value) ),'{slug_root_mode}',to_jsonb(CASE WHEN $6::boolean THEN COALESCE(config->>'slug_root_mode',$5::text) ELSE $5::text END)), newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL) WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR last_commit=$3) AND ($6::bo","INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES ($1, $2, jsonb_build_array(jsonb_strip_nulls(jsonb_build_object('run_id',$3::text,'at',now(),'changed',$4::int,'extract',$5::boolean,'since',$6::text))), now()) ON CONFLICT (op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=CASE WHEN jsonb_array_length(op_checkpoints.completed_keys)>=16 THEN (op_checkpoints.completed_keys-0)||EXCLUDED.completed_keys ELSE op_checkpoints.completed_keys||EXCLUDED.completed_keys END","SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND sequence > $3::bigint AND state='committed' AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence","INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now()) ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now() WHERE $4::boolean OR op_checkpoints.completed_keys->0->>'lease_token'=$5 RETURNING 1",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 57cc49c2d4..582c55accb 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -528,6 +528,7 @@"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",+ "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_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex a3bc6f9413..c24e21978b 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -528,6 +528,7 @@"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",+ "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_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=3ffbe1c80104ca23fb2581cfdb67541b31769cc5af9dcd1c8b84f8c3844275f4","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c393710877f69961517a5a820b741b9229ee9e20d045e736b191e8366170fedc"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 07a278725a..6a6095e121 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -528,6 +528,7 @@"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",+ "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_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex 50098fc050..d961e5c719 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -383,6 +383,7 @@"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_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"},"grants": {diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex 36e254cd6c..e00cd83152 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -383,6 +383,7 @@"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_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"},"grants": {diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex c5e6c1b1e0..bec1d2cc76 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -383,6 +383,7 @@"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_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"},"grants": {diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.jsonindex 0ab84505e5..80c8d46a27 100644--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json@@ -392,6 +392,7 @@"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_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","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 93d370b3b0..b482e71c74 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -531,6 +531,7 @@"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",+ "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","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 2173978614..9ea57a2ebc 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -531,6 +531,7 @@"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",+ "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","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=3ffbe1c80104ca23fb2581cfdb67541b31769cc5af9dcd1c8b84f8c3844275f4","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c393710877f69961517a5a820b741b9229ee9e20d045e736b191e8366170fedc"diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex f75e6f272e..dc450522e7 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -531,6 +531,7 @@"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",+ "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","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex ebaeb44ccf..0d27d340dd 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 257,+ "count": 258,"gaps": [17,18,@@ -72,7 +72,7 @@"tableRows": "906d2413b13d76a06d5910885e47ed5c544be4ff3a2266e83146715721b24270","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 262,+ "latest": 263,"records": [{"handler": {@@ -4175,6 +4175,19 @@"transaction": "absent","verify": "absent","version": 262+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "try_jsonb_function",+ "sql": {+ "length": 241,+ "sha256": "ca16373eb5df962e15b59ed33ebffd4469d09ee873039600929e1b9145638272"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 263}],"versions": [@@ -4434,7 +4447,8 @@259,260,261,- 262+ 262,+ 263]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/sql-text/sources.json b/test/fixtures/goldens/sql-text/sources.jsonindex 391abf0a8d..28e3adabf6 100644--- a/test/fixtures/goldens/sql-text/sources.json+++ b/test/fixtures/goldens/sql-text/sources.json@@ -23,8 +23,8 @@"json","string"],- "sql": "UPDATE sources SET config = ( WITH RECURSIVE root_layers(value, depth) AS ( SELECT COALESCE(config, '{}'::jsonb), 0 UNION ALL SELECT (value #>> '{}')::jsonb, depth + 1 FROM root_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND (value #>> '{}') IS JSON ), root(value) AS ( SELECT value FROM root_layers ORDER BY depth DESC LIMIT 1 ), fragment_seeds(ordinality, value) AS ( SELECT 0::bigint, value FROM root WHERE jsonb_typeof(value) = 'object' UNION ALL SELECT item.ordinality, item.value FROM root, LATERAL jsonb_array_elements( CASE WHEN jsonb_typeof(root.value) = 'array' THEN root.value ELSE '[]'::jsonb END ) WITH ORDINALITY AS item(value, ordinality) ), fragment_layers(ordinality, value, depth) AS ( SELECT ordinality, value, 0 FROM fragment_seeds UNION ALL SELECT ordinality, (value #>> '{}')::jsonb, depth + 1 FROM fragment_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND (value #>> '{}') IS JSON ), fragments AS ( SELECT DISTINCT ON (ordinality) ordinality, value FROM fragment_layers ORDER BY ordinality, depth DESC ) SELECT COALESCE( jsonb_object_agg(entry.key, entry.value ORDER BY fragments.ordinality), '{}'::jsonb ) FROM fragments CROSS JOIN LATERAL jsonb_each( CASE WHEN jsonb_typeof(fragments.value) = 'object' THEN fragments.value ELSE '{}'::jsonb END ) AS entry(key, value) ) || $1 WHERE id = $2",- "textSha256": "676e4a9c80fe88128a8cf2a3a550a06f0272d1194a9ac70e253b6bdde3486c5a"+ "sql": "UPDATE sources SET config = ( WITH RECURSIVE root_layers(value, depth) AS ( SELECT COALESCE(config, '{}'::jsonb), 0 UNION ALL SELECT gbrain_try_jsonb(value #>> '{}'), depth + 1 FROM root_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND gbrain_try_jsonb(value #>> '{}') IS NOT NULL ), root(value) AS ( SELECT value FROM root_layers ORDER BY depth DESC LIMIT 1 ), fragment_seeds(ordinality, value) AS ( SELECT 0::bigint, value FROM root WHERE jsonb_typeof(value) = 'object' UNION ALL SELECT item.ordinality, item.value FROM root, LATERAL jsonb_array_elements( CASE WHEN jsonb_typeof(root.value) = 'array' THEN root.value ELSE '[]'::jsonb END ) WITH ORDINALITY AS item(value, ordinality) ), fragment_layers(ordinality, value, depth) AS ( SELECT ordinality, value, 0 FROM fragment_seeds UNION ALL SELECT ordinality, gbrain_try_jsonb(value #>> '{}'), depth + 1 FROM fragment_layers WHERE depth < 10 AND jsonb_typeof(value) = 'string' AND gbrain_try_jsonb(value #>> '{}') IS NOT NULL ), fragments AS ( SELECT DISTINCT ON (ordinality) ordinality, value FROM fragment_layers ORDER BY ordinality, depth DESC ) SELECT COALESCE( jsonb_object_agg(entry.key, entry.value ORDER BY fragments.ordinality), '{}'::jsonb ) FROM fragments CROSS JOIN LATERAL jsonb_each( CASE WHEN jsonb_typeof(fragments.value) = 'object' THEN fragments.value ELSE '{}'::jsonb END ) AS entry(key, value) ) || $1 WHERE id = $2",+ "textSha256": "f60452bce6db5db7619b76b5f03ed2843641c13d35708bfbca459d0bf3468b8d"}]}diff --git a/test/paid-lanes-switch-5903.test.ts b/test/paid-lanes-switch-5903.test.tsindex 9da7cf601a..b398d06da2 100644--- a/test/paid-lanes-switch-5903.test.ts+++ b/test/paid-lanes-switch-5903.test.ts@@ -30,6 +30,7 @@ const GREEN = {JSONB: 'success',TIER1: 'success',BACKEND_MATRIX: 'success',+ POSTGRES15: 'success',TIER2: 'success',PREPARE: 'success',SELECTED: 'success',@@ -142,7 +143,7 @@ describe('#5903 e2e-status accepts a skipped tier2 only under GBRAIN_PAID_LANES=});test("the variable at '0' does not excuse any other skipped lane", () => {- for (const key of ['JSONB', 'TIER1', 'BACKEND_MATRIX', 'PREPARE', 'SELECTED'] as const) {+ for (const key of ['JSONB', 'TIER1', 'BACKEND_MATRIX', 'POSTGRES15', 'PREPARE', 'SELECTED'] as const) {const r = runAggregate({ [key]: 'skipped', GBRAIN_PAID_LANES: '0' });expect(r.status).toBe(1);expect(r.stdout).toContain('got skipped');diff --git a/test/postgres15-sql-compat-7112.test.ts b/test/postgres15-sql-compat-7112.test.tsnew file mode 100644index 0000000000..0806729461--- /dev/null+++ b/test/postgres15-sql-compat-7112.test.ts@@ -0,0 +1,93 @@+/**+ * #7112: every statement that normalizes `sources.config` used the SQL/JSON `IS JSON` predicate, and the doctor and+ * repair-jsonb damage probes used pg_input_is_valid(); both are Postgres 16+, so on Postgres 15 each of those statements+ * was a syntax error (42601) and managed sync could never publish its checkpoint. gbrain_try_jsonb (schema.sql, v263)+ * replaces both on every supported server. It also closes a hole IS JSON left open: text that is valid json but not+ * valid jsonb (a \\u0000 escape) passed the predicate and then failed the cast, so the guarded UPDATE raised anyway.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { resetDreamBreakerKey, DREAM_BREAKER_RESETS_KEY } from '../src/core/cycle/dream-breaker.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const SOURCE = 'cfg-7112';+const NUL_OBJECT = '{"label":"\\u0000"}';++for (const kind of testBackends()) describe(`portable jsonb guard (${kind})`, () => {+ let engine: BrainEngine;+ let close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; close = () => lite.disconnect(); }+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT (id) DO NOTHING', [SOURCE]);+ }, 120_000);+ afterAll(async () => { await close?.(); });++ async function configAfterPatch(stored: string): Promise<Record<string, unknown>> {+ await engine.executeRaw('UPDATE sources SET config=$2::text::jsonb WHERE id=$1', [SOURCE, stored]);+ expect(await engine.updateSourceConfig(SOURCE, { patched: true })).toBe(true);+ const [row] = await engine.executeRaw<{ config: Record<string, unknown> | string }>('SELECT config FROM sources WHERE id=$1', [SOURCE]);+ return typeof row!.config === 'string' ? JSON.parse(row!.config) : row!.config;+ }++ test('gbrain_try_jsonb parses valid jsonb and returns NULL for anything the jsonb cast refuses', async () => {+ const [row] = await engine.executeRaw<Record<string, unknown>>(+ `SELECT gbrain_try_jsonb('{"a":[1,"x"]}')::text AS object, gbrain_try_jsonb('"s"')::text AS scalar, gbrain_try_jsonb('[INFO] fetch complete') AS log_line,+ gbrain_try_jsonb($1) AS nul_escape, gbrain_try_jsonb(NULL) AS null_input`, [NUL_OBJECT]);+ expect(JSON.parse(row!.object as string)).toEqual({ a: [1, 'x'] });+ expect(JSON.parse(row!.scalar as string)).toBe('s');+ expect(row!.log_line).toBeNull();+ expect(row!.nul_escape).toBeNull();+ expect(row!.null_input).toBeNull();+ });++ test('a config merge unwraps a double-encoded object, merges array fragments and keeps going past unparseable text', async () => {+ expect(await configAfterPatch(JSON.stringify(JSON.stringify({ federated: true })))).toEqual({ federated: true, patched: true });+ expect(await configAfterPatch(JSON.stringify([{ a: 1 }, JSON.stringify({ b: 2 }), 'junk']))).toEqual({ a: 1, b: 2, patched: true });+ expect(await configAfterPatch(JSON.stringify('[INFO] not json'))).toEqual({ patched: true });+ });++ test('a double-encoded config that is json but not jsonb no longer fails the merge', async () => {+ expect(await configAfterPatch(JSON.stringify(NUL_OBJECT))).toEqual({ patched: true });+ });++ test('a dream-breaker reset over a stored value that is json but not jsonb starts a fresh map', async () => {+ await engine.executeRaw('INSERT INTO config(key,value) VALUES($1,$2) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value', [DREAM_BREAKER_RESETS_KEY, NUL_OBJECT]);+ await resetDreamBreakerKey(engine, 'synthesize:cfg-7112');+ const [row] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1', [DREAM_BREAKER_RESETS_KEY]);+ expect(Object.keys(JSON.parse(row!.value))).toEqual(['synthesize:cfg-7112']);+ });+});++describe('#7112: shipped SQL parses on every supported Postgres (15+)', () => {+ // Postgres 16+ syntax and functions: SQL/JSON predicates, constructors and query functions, ANY_VALUE, the error-safe+ // input functions, and MERGE ... RETURNING (17). PGLite runs Postgres 17 and CI's E2E lanes Postgres 16, so neither sees them fail.+ // The predicate is matched in upper case only, so English text such as "is not JSON" in an error message is not SQL.+ const PG16_PREDICATE = /\bIS\s+(?:NOT\s+)?JSON\b/;+ const PG16_FUNCTION = /\b(?:pg_input_is_valid|pg_input_error_info|JSON_ARRAY|JSON_OBJECT|JSON_ARRAYAGG|JSON_OBJECTAGG|JSON_SCALAR|JSON_SERIALIZE|JSON_EXISTS|JSON_QUERY|JSON_VALUE|JSON_TABLE|ANY_VALUE)\s*\(|\bMERGE\s+INTO\b[\s\S]{0,2000}?\bRETURNING\b/i;+ const pg16Only = (sql: string) => PG16_PREDICATE.test(sql) || PG16_FUNCTION.test(sql);+ const stripComments = (text: string) => text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:'"`\\])\/\/.*$/gm, '$1').replace(/^\s*--.*$/gm, '');+ function files(dir: string): string[] {+ return readdirSync(dir).flatMap(name => {+ const path = join(dir, name);+ return statSync(path).isDirectory() ? files(path) : /\.(ts|sql)$/.test(name) ? [path] : [];+ });+ }++ test('src/ holds no Postgres 16+ only SQL', () => {+ const offenders = files('src').filter(path => pg16Only(stripComments(readFileSync(path, 'utf8'))));+ expect(offenders).toEqual([]);+ });++ test('the guard catches the statement #7112 shipped', () => {+ expect(pg16Only(stripComments("AND (value #>> '{}') IS JSON\n"))).toBe(true);+ expect(pg16Only(stripComments("CASE WHEN config.value IS JSON OBJECT THEN"))).toBe(true);+ expect(pg16Only(stripComments("AND pg_input_is_valid(x, 'jsonb')"))).toBe(true);+ expect(pg16Only(stripComments('// unlike IS JSON\nSELECT 1'))).toBe(false);+ expect(pg16Only(stripComments("throw new Error('the reply is not JSON')"))).toBe(false);+ });+});diff --git a/test/publication-failure-owner-exception.test.ts b/test/publication-failure-owner-exception.test.tsindex e3bcc3c193..48049b50da 100644--- a/test/publication-failure-owner-exception.test.ts+++ b/test/publication-failure-owner-exception.test.ts@@ -162,3 +162,41 @@ describe('#6719 owner_exception diagnostics', () => {});});+describe('#7112 a database error keeps its redacted server text and statement, owner-only', () => {+ const serverError = async (sql: string, params: unknown[] = []): Promise<Error> => {+ try { await engine.executeRaw(sql, params); } catch (error) { return error as Error; }+ throw new Error('expected the statement to fail');+ };++ test('a syntax error names the token, the first statement line with literals replaced and the position; parameters never appear', async () => {+ const error = await serverError("SELECT id FROM sources\n WHERE name = $1 AND config->>'k' = 'secret-literal' AND (config #>> '{}') IS JSONX", ['secret-param']);+ const { row } = await failingWrite(error);+ expect(row.error_message).toBe(OWNER_EXCEPTION_MESSAGE);+ const detail = row.error_detail as Record<string, any>;+ expect(detail).toMatchObject({ origin: 'owner_exception', errno: '42601', statement: 'SELECT id FROM sources' });+ expect(detail.error_text).toMatch(/^syntax error at or near "[A-Z]+"$/);+ expect(detail.position).toBeGreaterThan(0);+ expect(JSON.stringify(row)).not.toContain('secret-literal');+ expect(JSON.stringify(row)).not.toContain('secret-param');+ expect((receiptFor(row) as Record<string, any>).write_error_detail).toEqual({ origin: 'owner_exception', stage: 'publication' });+ const receipt = await withEnv({ GBRAIN_HOME: join(dir, 'home') }, () =>+ operationsByName.get_write_request.handler(ctx(), { request_id: row.request_id })) as Record<string, any>;+ expect(receipt.error_detail).toMatchObject({ errno: '42601', error_text: detail.error_text, statement: 'SELECT id FROM sources', position: detail.position });+ });++ test('a value the server quotes into its message is replaced, an object it names is kept', async () => {+ const { row } = await failingWrite(await serverError("SELECT $1::uuid AS id WHERE 'alice-example' <> ''", ['alice-example-secret']));+ expect(row.error_detail).toMatchObject({ errno: '22P02', error_text: 'invalid input syntax for type uuid: "…"', statement: "SELECT $1::uuid AS id WHERE '…' <> '…'" });+ expect(JSON.stringify(row)).not.toContain('alice-example');+ const notNull = await failingWrite(await serverError("INSERT INTO sources(id, name) VALUES (NULL, 'alice-example')"));+ expect(notNull.row.error_detail).toMatchObject({ errno: '23502', error_text: 'null value in column "id" of relation "sources" violates not-null constraint' });+ });++ test('a PL/pgSQL RAISE keeps no text: it carries caller values', async () => {+ const { row } = await failingWrite(await serverError("DO $$ BEGIN RAISE EXCEPTION USING ERRCODE = '22023', MESSAGE = 'secret-title of a page'; END $$"));+ const detail = row.error_detail as Record<string, any>;+ expect(detail).toMatchObject({ origin: 'owner_exception', errno: '22023' });+ expect(detail.error_text).toBeUndefined();+ expect(JSON.stringify(row)).not.toContain('secret-title');+ });+});diff --git a/test/scripts/ci-gates.test.ts b/test/scripts/ci-gates.test.tsindex 5b715a7263..d357215cdf 100644--- a/test/scripts/ci-gates.test.ts+++ b/test/scripts/ci-gates.test.ts@@ -114,7 +114,7 @@ describe('CI execution evidence', () => {expect(e2e.jobs['e2e-status'].if).toBe("${{ needs.prepare-e2e.outputs.reuse != 'true' && always() }}");const needs = e2e.jobs['e2e-status'].needs as string[];const nightly = ['coverage-full-unit', 'coverage-full-serial', 'coverage-full-slow', 'coverage-full-e2e'];- expect(needs).toEqual(['jsonb-parity', 'tier1', 'tier1-backend-matrix', 'tier2', 'prepare-e2e', 'selected-e2e', ...nightly]);+ expect(needs).toEqual(['jsonb-parity', 'tier1', 'tier1-backend-matrix', 'postgres15-compat', 'tier2', 'prepare-e2e', 'selected-e2e', ...nightly]);for (const event of ['pull_request', 'push', 'workflow_dispatch']) {expect(aggregate(e2e, 'e2e-status', event, Object.fromEntries(nightly.map(job => [job, 'skipped'])))).toBe(0);}