Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): route every origin writer through the origin guard; regenerate goldens (#6948)

garrytan51fb4a66aabf
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 04f05dc02f..037017064f 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -4,6 +4,7 @@ src/core/persistence/activation.ts 0 coordinator Trusted private administration
src/core/persistence/canonical-projections.ts 10 coordinator Facts, takes, timeline, chunks and aliases install within the guarded canonical publication transaction before its receipt commits; a take whose claim changed in place loses its stored resolution there, and a fence row without resolution cells keeps it.
src/core/persistence/links-maintenance.ts 1 coordinator Managed extract --stale and post-sync extraction add only the coordinator's unrecorded canonical timeline tuples inside a revision-bound withCoordinatedWrite transaction that also replaces the page's derived links and stamps its watermark.
src/core/extract-takes-from-pages.ts 0 coordinator Managed bootstrap submits one revision-checked put_page per source page so its complete takes fence and projected rows commit together; unmanaged writes retain the md-first helper.
+src/core/persistence/origin-guard.ts 2 engine_guard #6948 bindOrigin records a page origin (and drops an origin_twin marker) only after assertOriginUnclaimed holds the origin advisory lock inside the caller's engine.transaction(); callers are the guarded publication applies and repairs.
src/core/persistence/takes-prepare.ts 4 coordinator Semantic takes apply only through the journal publication callback after current revision, holder and authority validation. takes_remove deletes the removed row inside the same coordinated apply (#5167).
src/commands/extract-timeline-db.ts 2 coordinator `gbrain extract timeline --source db` (#5904): on a managed brain the timeline retraction and insert run only inside the managed_maintenance_timeline_extract publication (prepareTimelineExtract; owner-checked by maintenancePreflight, page key locked, revision-bound); only an unmanaged brain retracts and batch-inserts directly, where no canonical writer enforcement applies.
src/commands/extract-conversation-facts.ts 4 coordinator On a managed brain each page's fact rows and outcome row are frozen into one database-only managed_maintenance_conversation_facts request (facts/conversation-publication.ts) after a maintenance preflight before provider work; the coordinator's preparer revalidates page identity, revision and parser-input snapshot under the page key. Unmanaged calls keep their direct engine writes behind the SQL guard (writeDerivedFacts refuses on a managed brain).
diff --git a/llms-full.txt b/llms-full.txt
index 9986a59b6b..05916f14f6 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -7508,6 +7508,8 @@ Every hold and error has three fields, from one table
| `purged_content` | page | none | yes | always: only the owner clears a purge tombstone |
| `write_gate_rejected` | page | none | yes | always: write_gate.external_mode=reject is the user's setting |
| `legacy_slug_conflict` | page | none | yes | always: only a person decides which legacy page the file takes over |
+| `origin_conflict` | page | repair | no | the hold carries a reason (the pages differ, ids conflict or none is the page the path names), or the heal is off |
+| `origin_conflict_decision` | page | none | yes | always: the pages differ, their ids conflict or none is the page the path names |
| `revision_conflict` | page | retry | no | the same path fails again after a rerun |
| `page_identity_changed` | page | retry | no | the same path fails again after a rerun |
| `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun |
diff --git a/package.json b/package.json
index 7db8008124..b0fe89c3aa 100644
--- a/package.json
+++ b/package.json
@@ -138,6 +138,7 @@
"check:pg-url-redaction": "bash scripts/check-pg-url-redaction.sh",
"check:source-scope-onboard": "bash scripts/check-source-scope-onboard.sh",
"check:getpage-scope": "node scripts/check-getpage-scoped-write.mjs",
+ "check:origin-assignment": "node scripts/check-origin-assignment.mjs",
"postinstall": "bun run scripts/postinstall.ts",
"prepublish:clawhub": "bun run build:all",
"publish:clawhub": "clawhub package publish . --family bundle-plugin",
diff --git a/scripts/check-origin-assignment.mjs b/scripts/check-origin-assignment.mjs
new file mode 100644
index 0000000000..61b69fd7ce
--- /dev/null
+++ b/scripts/check-origin-assignment.mjs
@@ -0,0 +1,67 @@
+#!/usr/bin/env node
+/**
+ * #6948 CI guard: every write that records a page origin (`pages.source_path`)
+ * goes through src/core/persistence/origin-guard.ts (`bindOrigin`, or
+ * `assertOriginUnclaimed` in the same transaction), so no writer can give a
+ * second live page of a source an origin another page already records.
+ *
+ * Flags, in non-test source files:
+ * (a) an `UPDATE pages ... SET` whose SET clause assigns `source_path` a value
+ * other than NULL (a clear is not an assignment);
+ * (b) an `INSERT INTO pages (...)` whose column list carries `source_path`;
+ * (c) an `UPDATE pages ... SET` that assigns `slug`: a rename carries the
+ * page's recorded origin to a new identity, so each such statement is
+ * reviewed and marked with why it adds no claimant.
+ * origin-guard.ts itself is exempt. A guarded site that must keep its SQL
+ * inline carries `origin-guard-ok: <reason>` on the statement's line or one
+ * of the three lines above it.
+ *
+ * Exit 0 = clean, 1 = violations. Runs under node or bun. Roots: argv
+ * (fixtures for the self-test) or src/.
+ */
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join, relative, sep } from 'node:path';
+
+const ROOTS = process.argv.slice(2).length > 0 ? process.argv.slice(2) : ['src'];
+const OWNER = 'src/core/persistence/origin-guard.ts';
+const MARKER = 'origin-guard-ok:';
+const UPDATE_RE = /UPDATE\s+pages\b(?:\s+(?:AS\s+)?(?!SET\b)[A-Za-z_]\w*)?\s+SET\b([\s\S]{0,2000}?)(?=\bWHERE\b|\bRETURNING\b|`|$)/gi;
+const INSERT_RE = /INSERT\s+INTO\s+pages\s*\(([^)]*)\)/gi;
+const ASSIGN_RE = /\bsource_path\s*=\s*(?!NULL\b)\S/i;
+const SLUG_RE = /\bslug\s*=/i;
+
+function files(path) {
+ const st = statSync(path);
+ if (st.isFile()) return path.endsWith('.ts') || path.endsWith('.mjs') ? [path] : [];
+ return readdirSync(path).sort().flatMap(entry => files(join(path, entry)));
+}
+
+const violations = [];
+for (const root of ROOTS) {
+ for (const file of files(root)) {
+ const rel = relative(process.cwd(), file).split(sep).join('/');
+ if (rel.endsWith(OWNER) || /\.test\.ts$/.test(file)) continue;
+ const src = readFileSync(file, 'utf8');
+ const lines = src.split('\n');
+ const report = (index, what) => {
+ const line = src.slice(0, index).split('\n').length;
+ const text = lines[line - 1].trim();
+ if (text.startsWith('*') || text.startsWith('//') || text.startsWith('/*')) return;
+ if (lines.slice(Math.max(0, line - 4), line).some(l => l.includes(MARKER))) return;
+ violations.push(`${rel}:${line}: ${what}`);
+ };
+ for (const m of src.matchAll(UPDATE_RE)) {
+ if (ASSIGN_RE.test(m[1])) report(m.index, 'UPDATE pages assigns source_path outside origin-guard.ts');
+ if (SLUG_RE.test(m[1])) report(m.index, 'UPDATE pages renames a slug, carrying its source_path, without the origin guard');
+ }
+ for (const m of src.matchAll(INSERT_RE)) if (/\bsource_path\b/i.test(m[1])) report(m.index, 'INSERT INTO pages carries source_path outside origin-guard.ts');
+ }
+}
+
+if (violations.length) {
+ console.error('check-origin-assignment: page origin writes that skip the origin guard (#6948):');
+ for (const v of violations) console.error(` ${v}`);
+ console.error(`Route the write through bindOrigin (src/core/persistence/origin-guard.ts), or run assertOriginUnclaimed in the same transaction and mark the statement \`${MARKER} <reason>\`.`);
+ process.exit(1);
+}
+console.log('check-origin-assignment: clean (every page origin write goes through the origin guard)');
diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsv
index 9c3a3352b8..1388960698 100644
--- a/scripts/guards-manifest.tsv
+++ b/scripts/guards-manifest.tsv
@@ -83,6 +83,7 @@ check-schema-migration-order.ts repostate exempt EO10: a migration origin/master
check-structural-manifest.sh buildfresh exempt regenerate+diff of structural-suites.tsv (classify-tests.ts); the diff IS the self-test
check-opencode-pin.sh repostate exempt pin-stamp drift check (OPENCODE-CLI-PIN.md stamps vs heavy-tests opencode-door env); own bun guard tests in test/check-bootstrap-guards.test.ts
check-pin-doc-privacy.sh repostate exempt PIN-doc placeholder discipline (no operator paths/key material/emails in docs/mcp/*-CLI-PIN.md); own bun guard tests in test/check-bootstrap-guards.test.ts
+check-origin-assignment.mjs scanner yes #6948: page origin writes (UPDATE pages SET source_path=<non-NULL>, INSERT INTO pages carrying source_path, UPDATE pages SET slug=<rename>) outside src/core/persistence/origin-guard.ts unless marked origin-guard-ok: <reason>; argv root override; fixtures under test/fixtures/guards/; also in verify CHECKS
check-getpage-scoped-write.mjs scanner yes unscoped-getPage + write co-occurrence scanner (source-isolation bug class); argv root override; fixtures under test/fixtures/guards/; also in verify CHECKS
check-core-guard-coverage.mjs scanner yes core memory write-path guard coverage: PreparedMutation builders route through preparePageMutation or a reasoned EXEMPT entry, wrappers forward exclusiveSources; argv/GBRAIN_GUARD_ROOT root override; in verify CHECKS
check-orphan-modules.mjs scanner yes runtime-reachability walk (static+dynamic relative imports) from cli/mcp/plugin/admin entrypoints + package.json exports; hard-fails untested orphans, requires a reasoned PERMITTED_TEST_ONLY entry per test-only module (stale entries fail); fixture root via argv/GBRAIN_GUARD_ROOT; knip v5 evaluated + rejected (crashes on repo layout — see script header)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 56937e8a21..478a1e8df9 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -20,8 +20,8 @@ src/core/engine.ts 2832 ratchet grown v0.46.26.0 megawave: relational/visibility
src/core/import-file.ts 2064 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)
-src/core/pglite-engine.ts 3080 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5
-src/core/postgres-engine.ts 3102 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5
+src/core/pglite-engine.ts 3082 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2
+src/core/postgres-engine.ts 3104 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
src/core/types.ts 2325 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index bf06fb9d24..59c46d4326 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -141,6 +141,7 @@ CHECKS=(
"check:fixture-privacy"
"check:source-scope-onboard"
"check:getpage-scope"
+ "check:origin-assignment"
"check:no-double-retry"
"check:batch-audit-site"
"check:engine-dynamic-import"
diff --git a/src/commands/sync/holds.ts b/src/commands/sync/holds.ts
index b0dfe5f465..12f3d2299d 100644
--- a/src/commands/sync/holds.ts
+++ b/src/commands/sync/holds.ts
@@ -31,6 +31,7 @@ import {
import { DEFAULT_SOURCE_ID, hasMalformedPathSegment, isCodeFilePath, resolveSlugForPath, sanitizePathForDisplay, slugifyPath } from '../../core/sync.ts';
import type { SyncActivePack } from './sync-run.ts';
import { isPathContained } from '../../core/path-confine.ts';
+import { bindOrigin } from '../../core/persistence/origin-guard.ts';
/** The file at a repo-relative path from git or a hold row, or null when it is missing or resolves outside the source root. */
function fileUnderRoot(root: string, path: string): string | null {
@@ -356,7 +357,7 @@ export async function moveHeldRenames(engine: BrainEngine, holds: LegacyHolds |
const slug = resolveSlugForPath(record.path);
await maintenanceBeliefTransaction(engine, { sourceId: holds.sourceId, slugs: [origin.slug, slug], op: 'sync_rename' }, async tx => {
if (await tx.updateSlug(origin.slug, slug, { sourceId: holds.sourceId }) === 0) return;
- await tx.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2 AND source_id=$3', [record.path, origin.pageId, holds.sourceId]);
+ await bindOrigin(tx, { sourceId: holds.sourceId, pageId: origin.pageId, sourcePath: record.path });
});
} catch { /* the walk imports the file as an ordinary add; the old page stays until a full walk proves it gone */ }
}
diff --git a/src/commands/sync/rename-collision.ts b/src/commands/sync/rename-collision.ts
index 0d4c3f251d..6a243a2b80 100644
--- a/src/commands/sync/rename-collision.ts
+++ b/src/commands/sync/rename-collision.ts
@@ -18,13 +18,15 @@ import { maintenanceTransaction } from '../../core/persistence/attribution.ts';
import { randomUUID } from 'node:crypto';
import { lockedBeliefBatch } from '../../core/belief/writers.ts';
import { markBeliefCommits } from '../../core/belief/append.ts';
+import { bindOrigin, classifyOriginUniqueViolation } from '../../core/persistence/origin-guard.ts';
export type RenameOutcome = 'renamed' | 'noop' | 'live_destination';
const UNIQUE_VIOLATION = '23505';
+/** A slug collision: any 23505 except the live-origin index (#6948), which is an origin refusal, not an occupied slug. */
export function isUniqueViolation(error: unknown): boolean {
- return typeof error === 'object' && error !== null && String((error as { code?: unknown }).code) === UNIQUE_VIOLATION;
+ return typeof error === 'object' && error !== null && String((error as { code?: unknown }).code) === UNIQUE_VIOLATION && !classifyOriginUniqueViolation(error);
}
/** The purge-style slug a merged tombstone keeps; `~` is outside the slug grammar, so no file or write can claim it. */
@@ -39,7 +41,7 @@ export async function renamePageOntoSlug(engine: BrainEngine, input: { sourceId:
// W1 #6783 §3: the moved row keeps its id, so its batch pairs both sides into one page.renamed on the same lifetime.
const move = (tx: BrainEngine) => lockedBeliefBatch(tx, { sourceId, slugs: [oldSlug, newSlug], publicationId, op: 'sync_rename', remote: false, report }, async () => {
const moved = await tx.updateSlug(oldSlug, newSlug, { sourceId });
- if (moved > 0) await tx.executeRaw('UPDATE pages SET source_path = $1 WHERE source_id = $2 AND slug = $3', [to, sourceId, newSlug]);
+ if (moved > 0) await bindOrigin(tx, { sourceId, slug: newSlug, sourcePath: to });
return moved;
});
const recorded = async <T>(outcome: T) => {
@@ -49,7 +51,7 @@ export async function renamePageOntoSlug(engine: BrainEngine, input: { sourceId:
try {
return recorded((await maintenanceTransaction(engine, move)) > 0 ? 'renamed' : 'noop');
} catch (error) {
- if (!isUniqueViolation(error)) throw error;
+ if (!isUniqueViolation(error)) throw classifyOriginUniqueViolation(error, { sourceId, sourcePath: to, slug: newSlug }) ?? error;
const [destination] = await engine.executeRaw<{ id: number | string; tombstone: boolean }>(
'SELECT id, deleted_at IS NOT NULL AS tombstone FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, newSlug]);
if (!destination) throw error;
@@ -59,6 +61,7 @@ export async function renamePageOntoSlug(engine: BrainEngine, input: { sourceId:
try {
return await recorded(await maintenanceTransaction(engine, async tx => {
await tx.lockPageKeys([{ sourceId, slug: oldSlug }, { sourceId, slug: newSlug }]);
+ // origin-guard-ok: rekeys a tombstone only (deleted_at IS NOT NULL), which claims no origin
const rekeyed = await tx.executeRaw<{ id: number }>(
'UPDATE pages SET slug = $1 WHERE id = $2 AND source_id = $3 AND deleted_at IS NOT NULL RETURNING id', [purgedSlug(newSlug, tombstoneId), tombstoneId, sourceId]);
if (!rekeyed.length) return 'live_destination' as const;
diff --git a/src/core/backup/quarantine.ts b/src/core/backup/quarantine.ts
index f08ded54ed..f31e09b94e 100644
--- a/src/core/backup/quarantine.ts
+++ b/src/core/backup/quarantine.ts
@@ -67,6 +67,7 @@ export async function quarantineRestoredExecution(tx: BrainEngine, options: {
let preserved = 0;
for (const page of pages) {
const rel = relativeBackupPath(source.local_path, page.source_path);
+ // origin-guard-ok: a restore rebases every origin of the source one-to-one onto the new root, so it creates no twin
if (rel) await tx.executeRaw('UPDATE pages SET source_path = $1 WHERE id = $2', [confinedPath(rebased, rel), page.id]);
else if (posix.isAbsolute(page.source_path) || win32.isAbsolute(page.source_path)) preserved++;
}
diff --git a/src/core/engine-sql/page-body.ts b/src/core/engine-sql/page-body.ts
index b8bff59765..a8f968ea43 100644
--- a/src/core/engine-sql/page-body.ts
+++ b/src/core/engine-sql/page-body.ts
@@ -267,6 +267,7 @@ function metaParams(meta: SegmentedPageMeta) {
export async function createSegmentedPageShell(exec: SqlExecutor, slug: string, meta: SegmentedPageMeta, opts: { sourceId: string }): Promise<{ id: number }> {
const m = metaParams(meta);
+ // origin-guard-ok: applySegmentedBody runs assertOriginUnclaimed in this transaction first
const { rows } = await exec.run<{ id: number }>(sqlFragment`
INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, updated_at, effective_date,
effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at,
@@ -324,6 +325,7 @@ export async function flipBodyGeneration(exec: SqlExecutor, input: BodyFlipInput
await tx.run(sqlFragment`UPDATE page_body_manifest SET staging_id = NULL WHERE page_id = ${input.pageId} AND staging_id = ${input.stagingId}::uuid`);
const m = metaParams(input.meta);
const b = input.body;
+ // origin-guard-ok: applySegmentedBody runs assertOriginUnclaimed in this transaction first
await tx.run(sqlFragment`UPDATE pages SET
body_storage = 'segmented', compiled_truth = NULL, timeline = NULL, body_generation = ${input.newGeneration}::bigint,
content_hash = ${b.content_hash}, body_bytes = ${b.body_bytes}::bigint, truth_bytes = ${b.truth_bytes}::bigint,
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index f40067ddce..f7b8dda574 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -35,6 +35,7 @@ import { stagingNeedsTextSql } from '../page-body/schema.ts';
import { createPageVersion } from '../page-state/versions.ts';
import { renderFragment, sqlFragment, trustedSql } from './fragment.ts';
import { quoteIdentifier, resolveWriteColumnFromConfigRows } from '../search/embedding-column.ts';
+import { pickCanonicalOrigin } from '../persistence/origin-guard.ts';
/**
* PGLite can return zero rows from `INSERT ... ON CONFLICT DO UPDATE ...
@@ -157,6 +158,7 @@ export async function putPage(
const crSet = cr ? sqlFragment`
contextual_retrieval_mode = EXCLUDED.contextual_retrieval_mode,
corpus_generation = EXCLUDED.corpus_generation,` : sqlFragment``;
+ // origin-guard-ok: both engines' putPage run assertOriginUnclaimed in this transaction first
const { rows } = await exec.run(sqlFragment`
INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at${crColumns})
VALUES (${sourceId}, ${slug}, ${page.type}, ${pageKind}, ${sanitizeText(page.title)}, ${sanitizeText(page.compiled_truth)}, ${sanitizeText(page.timeline || '')}, ${jsonbParam(frontmatter)}, ${hash}, now(), ${effectiveDate}, ${effectiveDateSource}, ${importFilename}, ${chunkerVersion}::smallint, ${sourcePath}, ${sourceKind}, ${sourceUri}, ${ingestedVia}, ${ingestedAt}${crValues})
@@ -219,7 +221,9 @@ export async function deletePages(exec: SqlExecutor, slugs: string[], opts: { so
/**
* v0.41.19.0 — batch path → slug resolution. See BrainEngine.resolveSlugsByPaths
- * JSDoc. Single SQL round-trip; folds rows into a Map.
+ * JSDoc. Single SQL round-trip. #6948: a path's live pages win over its tombstones;
+ * several pages resolve to the canonical one (`pickCanonicalOrigin`), and a path whose
+ * pages are ambiguous is left out (never an arbitrary twin).
*/
export async function resolveSlugsByPaths(
exec: LegacyUnscopedRead,
@@ -232,13 +236,19 @@ export async function resolveSlugsByPaths(
`resolveSlugsByPaths: input size ${paths.length} exceeds DELETE_BATCH_SIZE=${DELETE_BATCH_SIZE}. Caller must chunk.`,
);
}
- const { rows } = await exec.run<{ slug: string; source_path: string }>(sqlFragment`
- SELECT slug, source_path
+ const { rows } = await exec.run<{ slug: string; source_path: string; live: boolean }>(sqlFragment`
+ SELECT slug, source_path, deleted_at IS NULL AS live
FROM pages
WHERE source_path = ANY(${paths}::text[]) AND source_id = ${opts.sourceId}
+ ORDER BY source_path, slug
`);
const m = new Map<string, string>();
- for (const r of rows) m.set(r.source_path, r.slug);
+ for (const path of new Set(rows.map(r => r.source_path))) {
+ const claimants = rows.filter(r => r.source_path === path);
+ const live = claimants.filter(r => r.live);
+ const picked = pickCanonicalOrigin(live.length ? live : claimants, path);
+ if (picked && !('ambiguous' in picked)) m.set(path, picked.slug);
+ }
return m;
}
@@ -1027,6 +1037,7 @@ export async function revertToVersion(
export async function updateSlug(exec: SqlExecutor, tx: BrainEngine, oldSlug: string, newSlug: string, sourceId: string): Promise<number> {
const preimage = await tx.readPageSnapshot(oldSlug, { sourceId, includeDeleted: true });
if (preimage) await createPageVersion(tx, oldSlug, sourceId, preimage);
+ // origin-guard-ok: the moved row keeps its own origin and liveness, so it adds no claimant (#6948); callers that record a new path bind it with bindOrigin
const moved = await exec.executeRaw(
`UPDATE pages SET slug = $1, updated_at = now() WHERE slug = $2 AND source_id = $3 RETURNING id`,
[newSlug, oldSlug, sourceId],
diff --git a/src/core/fence-repair/repair-io.ts b/src/core/fence-repair/repair-io.ts
index 07cf38b1f4..2673b17c4f 100644
--- a/src/core/fence-repair/repair-io.ts
+++ b/src/core/fence-repair/repair-io.ts
@@ -52,6 +52,7 @@ import { legacyCommitStep, recordUncommittedFenceRepair } from './uncommitted.ts
import type { FenceRepairReceipt } from './receipt.ts';
import type { FenceCtx, FencePage } from './types.ts';
import { gitChildEnv } from '../git-env.ts';
+import { canonicalOriginPage, originConflictMessage } from '../persistence/origin-guard.ts';
export type FenceRepairMode = 'managed' | 'legacy' | 'db' | 'mirror';
@@ -128,7 +129,7 @@ export function pageSha(page: FencePage): string {
return sha256(`${page.compiled_truth ?? ''}\u0000${page.timeline ?? ''}`);
}
-export type TargetRead = { ok: true; target: FenceTarget } | { ok: false; reason: 'gone' | 'not_utf8' | 'unsafe_path' };
+export type TargetRead = { ok: true; target: FenceTarget } | { ok: false; reason: 'gone' | 'not_utf8' | 'unsafe_path' } | { ok: false; reason: 'origin_conflict'; message: string };
/** Reads a candidate as it is now. A held or walked file is read from the checkout; anything else is read from the page store. */
export async function readFenceTarget(engine: BrainEngine, src: FenceSource, cand: { key: string; path: string | null }): Promise<TargetRead> {
@@ -145,7 +146,8 @@ export async function readFenceTarget(engine: BrainEngine, src: FenceSource, can
const content = bytes.toString('utf8');
if (!Buffer.from(content, 'utf8').equals(bytes)) return { ok: false, reason: 'not_utf8' };
const sourcePath = hold?.source_path ?? cand.path;
- const [byOrigin] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND source_path=$2 AND deleted_at IS NULL LIMIT 1', [src.id, sourcePath]);
+ const byOrigin = await canonicalOriginPage(engine, src.id, sourcePath);
+ if (byOrigin && 'ambiguous' in byOrigin) return { ok: false, reason: 'origin_conflict', message: originConflictMessage(src.id, sourcePath, byOrigin.ambiguous) };
const slug = byOrigin?.slug ?? holdSlug ?? resolveSlugForPath(sourcePath);
const dbOnly = src.managed && isSourceDbOnlySlug(src.root, slug, 'not_db_only');
if (!dbOnly) {
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 2b1cd9bd97..163ac4bde1 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -65,6 +65,7 @@ import { abortSegmentedStaging, bodyStorageOf, demoteSegmentedPage, materialized
import type { SegmentedStagingOwner } from './page-body/ingest.ts';
import type { PageBodyPolicy } from './page-body/limits.ts';
import { parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning, replaceOrInsertFactsFence } from './facts-fence.ts';
+import { assertOriginUnclaimed, isOriginClaimRefusal } from './persistence/origin-guard.ts';
/**
* #2044 / #4548: row-level, visibility-aware fence merge for one page
@@ -209,12 +210,16 @@ async function refreshSourcePath(engine: BrainEngine, slug: string, sourceId: st
try {
// Keep this optional legacy repair inside a savepoint: a rejected SQL
// statement must not poison the surrounding canonical transaction.
- await engine.transaction(tx => tx.executeRaw(
- `UPDATE pages SET source_path = $1, source_uri = COALESCE($4::text, source_uri) WHERE source_id = $2 AND slug = $3
+ await engine.transaction(async tx => {
+ await assertOriginUnclaimed(tx, { sourceId: sourceId ?? 'default', slug, sourcePath });
+ // origin-guard-ok: assertOriginUnclaimed above, in the same savepoint
+ await tx.executeRaw(`UPDATE pages SET source_path = $1, source_uri = COALESCE($4::text, source_uri) WHERE source_id = $2 AND slug = $3
AND deleted_at IS NULL AND (source_path IS DISTINCT FROM $1 OR source_uri IS DISTINCT FROM COALESCE($4::text, source_uri))`,
- [sourcePath, sourceId ?? 'default', slug, originUri],
- ));
- } catch { /* bookkeeping only — never fail the import over it */ }
+ [sourcePath, sourceId ?? 'default', slug, originUri]);
+ });
+ } catch (error) {
+ if (isOriginClaimRefusal(error)) process.stderr.write(`[import] ${slug}: origin ${sourcePath} not recorded: ${(error as Error).message}\n`);
+ }
}
/** #6188 (E8): `importFromContent`'s fence options. */
diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.ts
index 9e5943020a..aad2518489 100644
--- a/src/core/persistence/file-repair.ts
+++ b/src/core/persistence/file-repair.ts
@@ -77,6 +77,7 @@ import type { PreparedMutation } from './coordinator.ts';
import { contentRepairCommit, fenceRepairCommit } from './effect-model.ts';
import { recordSlugLineAlias } from '../page-state/rename-alias.ts';
import type { WriteRequest } from './model.ts';
+import { bindOrigin } from './origin-guard.ts';
export interface ManagedFileRepairIntent extends Record<string, unknown> {
kind: 'managed_file_repair';
@@ -398,7 +399,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:
}
published = applied;
const installed = await applied.apply(tx);
- await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
+ await bindOrigin(tx, { sourceId: row.source_id, slug: row.slug, sourcePath: p.sourcePath });
// A body stored in segments was sealed by its import's apply when complete (sealSegmentedPage); the inline text seal reads the whole timeline.
if (!applied.noop) { await project(tx); if (!installed?.segmented) await sealPageTextProjection(tx, row.slug, row.source_id); }
const holdCleared = await clearGitHold(tx, { sourceId: row.source_id, incarnation: row.source_incarnation, path: p.path, observedAt: p.holdObservedAt ?? new Date().toISOString() });
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index f766cf6282..38c3c6ba1e 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -36,6 +36,7 @@ import type { WriteRequest } from './model.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
+import { bindOrigin } from './origin-guard.ts';
export type ImportPack = { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };
/** A Markdown file over the single-string ceiling, journaled by reference: the preparer streams and verifies it (Wave B). */
@@ -275,7 +276,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
file: { root, path, content: rendered, expectedBeforeHash: p.targetHash },
apply: async tx => {
const applied = await ready.apply(tx);
- await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
+ await bindOrigin(tx, { sourceId: row.source_id, slug: row.slug, sourcePath: p.sourcePath });
if (project) {
// The coordinator proved the base revision under its page guard (importFromContent `coordinated`); this is the
// one read of the page after its last page write (the projections and the seal leave its revision unchanged):
diff --git a/src/core/persistence/origin-guard.ts b/src/core/persistence/origin-guard.ts
new file mode 100644
index 0000000000..0c5c76e563
--- /dev/null
+++ b/src/core/persistence/origin-guard.ts
@@ -0,0 +1,177 @@
+/**
+ * #6948: the one owner of origin assignment. A page's origin is the file it
+ * records (`pages.source_id`, `pages.source_path`); two live pages of a source
+ * recording the same origin ("twins") make sync discovery refuse that file. The
+ * partial unique index `pages_live_origin_key` makes twins impossible where it
+ * exists; on a brain whose existing twins keep the migration from building it,
+ * this guard is the protection. Every write that makes a page a live claimant of
+ * an origin it did not live-claim before (an assignment, an insert carrying an
+ * origin, a tombstone revival) runs `assertOriginUnclaimed` in its own
+ * transaction, serialized on the origin by a transaction-scoped advisory lock.
+ * A write that keeps the page's own origin is not an assignment.
+ */
+import { existsSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { opError, type OperationError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import { resolveSlugForPath } from '../sync.ts';
+import { sameSyncOrigin, syncOriginPath, syncOriginScope, type SyncOriginScope } from './sync-origin.ts';
+
+export const ORIGIN_INDEX_NAME = 'pages_live_origin_key';
+
+type Exec = Pick<BrainEngine, 'executeRaw'>;
+
+/** The page a write targets (by id, else by slug; absent for an insert) and the origin it would record (null: it keeps its stored origin). */
+export interface OriginTarget {
+ sourceId: string;
+ sourcePath?: string | null;
+ pageId?: number | null;
+ slug?: string;
+ /** The write makes a soft-deleted target live again (putPage's ON CONFLICT, restorePage, a segmented flip). */
+ revive?: boolean;
+ /** The source's origin form when the caller has it; omitted, it is read from the source row; null skips the legacy spelling. */
+ scope?: SyncOriginScope | null;
+}
+
+interface TargetRow { id: number; slug: string; source_path: string | null; deleted_at: unknown }
+
+/** The read-only preview of the origin-twin repair, which names the page that keeps the file. */
+export function originTwinsFix(sourceId: string) {
+ return readFix(`Previews which page of source ${sourceId} keeps each shared origin; read-only.`, { argv: ['gbrain', 'repair', 'origin-twins', '--source', sourceId] });
+}
+
+export function originAlreadyClaimed(sourceId: string, sourcePath: string, holders: readonly string[], target?: string): OperationError {
+ const held = holders.length ? `Page ${holders.join(', ')} already records` : 'Another live page already records';
+ return opError('page_identity_changed', `Another live page of source ${sourceId} already records ${JSON.stringify(sourcePath)} as its origin.`,
+ `${held} ${JSON.stringify(sourcePath)} in source ${sourceId}, so ${target ? `page ${target}` : 'this page'} cannot become a second page of that file; nothing was written. `
+ + `Write to the page that records the file, or preview gbrain repair origin-twins --source ${sourceId} to see which page keeps it.`,
+ { detail: 'origin_already_claimed', fix: originTwinsFix(sourceId) });
+}
+
+/** A reader's refusal to pick one of several live pages recording a file (`origin_conflict`). */
+export function originConflictMessage(sourceId: string, sourcePath: string, slugs: readonly string[]): string {
+ return `${sourcePath} is recorded by several live pages of source ${sourceId} (${slugs.join(', ')}) and none is its canonical page, so nothing was written into either. `
+ + `Preview gbrain repair origin-twins --source ${sourceId}, apply the merge it proposes, then preview this repair again.`;
+}
+
+/** Whether `error` is the guard's refusal (or a mapped index violation). */
+export function isOriginClaimRefusal(error: unknown): boolean {
+ return typeof error === 'object' && error !== null && (error as { detail?: unknown }).detail === 'origin_already_claimed';
+}
+
+/** A 23505 on `pages_live_origin_key` (both engines' error shapes), as the guard's own refusal; null for anything else. */
+export function classifyOriginUniqueViolation(error: unknown, at?: { sourceId: string; sourcePath: string; slug?: string }): OperationError | null {
+ if (!error || typeof error !== 'object') return null;
+ const e = error as Record<string, unknown>;
+ if (String(e.code) !== '23505' || (e.constraint_name ?? e.constraint) !== ORIGIN_INDEX_NAME) return null;
+ const key = /=\((.*), (.*)\) already exists/.exec(typeof e.detail === 'string' ? e.detail : '');
+ return originAlreadyClaimed(at?.sourceId ?? key?.[1] ?? 'unknown', at?.sourcePath ?? key?.[2] ?? 'unknown', [], at?.slug);
+}
+
+function gitRootOf(path: string): string | null {
+ for (let dir = resolve(path); ; dir = dirname(dir)) {
+ if (existsSync(join(dir, '.git'))) return dir;
+ if (dirname(dir) === dir) return null;
+ }
+}
+
+/** The origin form of a source pinned to source-root slugs at a subdirectory of its repository; undefined otherwise. */
+async function originScopeOf(tx: Exec, sourceId: string): Promise<SyncOriginScope | undefined> {
+ const [source] = await tx.executeRaw<{ local_path: string | null; mode: string | null }>(
+ "SELECT local_path, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1", [sourceId]);
+ if (!source?.local_path || source.mode !== 'source-root' || !existsSync(source.local_path)) return undefined;
+ const gitRoot = gitRootOf(source.local_path);
+ return gitRoot ? syncOriginScope({ sourceId, root: source.local_path, gitRoot, slugMode: 'source-root' }) : undefined;
+}
+
+const originKey = (path: string) => process.platform === 'win32' ? path.replaceAll('\\', '/').toLowerCase() : path;
+/** The lock key of one spelling: `syncOriginPath`'s normal form folded as `originKey` compares it (a path it refuses keeps its raw spelling). */
+const lockKey = (path: string) => { try { return originKey(syncOriginPath(path)); } catch { return originKey(path); } };
+
+/** Whether `recorded` (stored on the page `recordedSlug`) names the same file as `origin`: the same spelling, or the legacy Git-root spelling of either. */
+function sameOrigin(recorded: string, recordedSlug: string | undefined, origin: string, originSlug: string | undefined, scope: SyncOriginScope | undefined): boolean {
+ if (originKey(recorded) === originKey(origin)) return true;
+ const prefix = scope?.slugMode === 'source-root' && scope.scope ? `${scope.scope}/` : null;
+ if (!prefix) return false;
+ try {
+ if (originKey(recorded) === originKey(prefix + origin)) return sameSyncOrigin(recorded, origin, scope, recordedSlug);
+ if (originKey(origin) === originKey(prefix + recorded)) return sameSyncOrigin(origin, recorded, scope, originSlug);
+ } catch {
+ return true;
+ }
+ return false;
+}
+
+/**
+ * Refuses (`page_identity_changed`, detail `origin_already_claimed`) when the target would become a live claimant of an
+ * origin another live page of its source records, in any spelling discovery reads as the same file. Runs inside the
+ * caller's `engine.transaction()` and holds the origin's advisory lock until it ends, so two writers assigning one origin
+ * to different pages serialize and the second sees the first.
+ */
+export async function assertOriginUnclaimed(tx: BrainEngine, target: OriginTarget): Promise<void> {
+ if (!(tx as { _heldPageKeys?: unknown })._heldPageKeys) throw new Error('assertOriginUnclaimed requires engine.transaction(): the origin lock and the write must commit together');
+ const [row] = target.pageId != null
+ ? await tx.executeRaw<TargetRow>('SELECT id, slug, source_path, deleted_at FROM pages WHERE id=$1 AND source_id=$2', [target.pageId, target.sourceId])
+ : target.slug ? await tx.executeRaw<TargetRow>('SELECT id, slug, source_path, deleted_at FROM pages WHERE source_id=$1 AND slug=$2', [target.sourceId, target.slug]) : [];
+ const origin = target.sourcePath ?? row?.source_path ?? null;
+ if (!origin || row && row.deleted_at != null && !target.revive) return;
+ const scope = target.scope === undefined ? await originScopeOf(tx, target.sourceId) : target.scope ?? undefined;
+ const slug = row?.slug ?? target.slug;
+ if (row && row.deleted_at == null && row.source_path != null && sameOrigin(row.source_path, row.slug, origin, slug, scope)) return;
+ const prefix = scope?.slugMode === 'source-root' && scope.scope ? `${scope.scope}/` : null;
+ const forms = [origin, ...(prefix ? [prefix + origin] : []), ...(prefix && origin.startsWith(prefix) ? [origin.slice(prefix.length)] : [])];
+ const spellings = [...new Set(forms.map(originKey))].sort();
+ for (const key of [...new Set(forms.map(lockKey))].sort()) {
+ await tx.executeRaw('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`gbrain:origin:${JSON.stringify([target.sourceId, key])}`]);
+ }
+ const pathSql = process.platform === 'win32' ? "lower(replace(source_path,chr(92),'/'))=ANY($2::text[])" : 'source_path=ANY($2::text[])';
+ const holders = (await tx.executeRaw<{ slug: string; source_path: string }>(
+ `SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND ${pathSql} AND id<>$3 ORDER BY slug`, [target.sourceId, spellings, row?.id ?? -1]))
+ .filter(holder => sameOrigin(holder.source_path, holder.slug, origin, slug, scope));
+ if (holders.length) throw originAlreadyClaimed(target.sourceId, origin, holders.map(holder => holder.slug), slug);
+}
+
+/**
+ * Records `sourcePath` as the target page's origin, guarded: the assignment statement every origin-assigning write that
+ * is not a page upsert uses. `onlyIfUnset` fills a missing origin only; `liveOnly` never touches a tombstone. A page that
+ * records the origin drops an `origin_twin` database-only marker (it gave an origin up to a twin and now has its own file
+ * again). Returns the number of rows whose origin changed.
+ */
+export async function bindOrigin(tx: BrainEngine, target: OriginTarget & { sourcePath: string; onlyIfUnset?: boolean; liveOnly?: boolean }): Promise<number> {
+ await assertOriginUnclaimed(tx, target);
+ const by = target.pageId != null ? 'id=$2' : 'slug=$2';
+ const params = [target.sourceId, target.pageId ?? target.slug, target.sourcePath];
+ try {
+ const changed = (await tx.executeRaw(`UPDATE pages SET source_path=$3 WHERE source_id=$1 AND ${by} AND ${target.onlyIfUnset ? 'source_path IS NULL' : 'source_path IS DISTINCT FROM $3'}`
+ + `${target.liveOnly ? ' AND deleted_at IS NULL' : ''} RETURNING id`, params)).length;
+ await tx.executeRaw(`UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND ${by} AND source_path=$3 AND database_only_reason='origin_twin'`, params);
+ return changed;
+ } catch (error) {
+ throw classifyOriginUniqueViolation(error, target) ?? error;
+ }
+}
+
+/** Every soft-deleted page `restorePage(slug, opts)` would revive, guarded (a restore without a source revives the slug in every source). */
+export async function assertRevivalUnclaimed(tx: BrainEngine, slug: string, sourceId?: string): Promise<void> {
+ const rows = await tx.executeRaw<{ id: number; source_id: string }>(
+ 'SELECT id, source_id FROM pages WHERE slug=$1 AND deleted_at IS NOT NULL AND ($2::text IS NULL OR source_id=$2) ORDER BY source_id', [slug, sourceId ?? null]);
+ for (const row of rows) await assertOriginUnclaimed(tx, { sourceId: row.source_id, pageId: Number(row.id), revive: true });
+}
+
+/**
+ * Of the live pages recording one origin, the one a reader or a repair may act on: the only one, else the one whose slug
+ * is the file's derived slug (`resolveSlugForPath`); several with none canonical are `{ ambiguous }` (never written into).
+ */
+export function pickCanonicalOrigin<T extends { slug: string }>(pages: readonly T[], sourcePath: string): T | { ambiguous: string[] } | null {
+ if (pages.length <= 1) return pages[0] ?? null;
+ const derived = resolveSlugForPath(sourcePath);
+ const canonical = pages.filter(page => page.slug === derived);
+ return canonical.length === 1 ? canonical[0]! : { ambiguous: pages.map(page => page.slug).sort() };
+}
+
+export async function canonicalOriginPage(engine: Exec, sourceId: string, sourcePath: string): Promise<{ id: number; slug: string } | { ambiguous: string[] } | null> {
+ const rows = await engine.executeRaw<{ id: number; slug: string }>(
+ 'SELECT id, slug FROM pages WHERE source_id=$1 AND source_path=$2 AND deleted_at IS NULL ORDER BY slug', [sourceId, sourcePath]);
+ return pickCanonicalOrigin(rows.map(row => ({ id: Number(row.id), slug: row.slug })), sourcePath);
+}
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 43b3800269..ff9d09af91 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -86,6 +86,7 @@ import { suppliedTrustMarkerView } from '../trust/channel.ts';
import { gateField, gateInput } from '../trust/gate-outcomes.ts';
import { PUSH_SCAN_MAX_FILE_BYTES } from '../page-size-policy.ts';
import { fileContentHash, FileBytes, isStreamedContent, LARGE_FILE_MIN_BYTES, StreamedFileContent } from './large-file.ts';
+import { bindOrigin } from './origin-guard.ts';
const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its pending, failed and recovering requests, read-only.`,
@@ -868,8 +869,7 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ
// Mandatory metadata shares publication rollback; exact no-ops never heal it. These, and the
// projections (facts, takes, timeline rows of the page the import just wrote live), are independent and sent together.
const [, pinned] = await pipelined(tx, [
- async () => { if (sourcePath && !snapshot?.page.source_path) await tx.executeRaw(`UPDATE pages SET source_path = $1
- WHERE source_id=$2 AND slug=$3 AND source_path IS NULL`, [sourcePath, row.source_id, row.slug]); },
+ async () => { if (sourcePath && !snapshot?.page.source_path) await bindOrigin(tx, { sourceId: row.source_id, slug: row.slug, sourcePath, onlyIfUnset: true }); },
async () => pinMode ? (await tx.executeRaw<{ mode: string | null }>(`UPDATE sources SET config=CASE WHEN config->>'slug_root_mode' IS NULL
THEN jsonb_set(${SOURCE_CONFIG_OBJECT_SQL},'{slug_root_mode}',to_jsonb($2::text)) ELSE config END WHERE id=$1 RETURNING config->>'slug_root_mode' AS mode`,
[row.source_id, pinMode]))[0] : undefined,
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index 0a35d66817..e94807af30 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -24,6 +24,7 @@ import { stabilizeSafetyAssessments } from './reconcile-safety.ts';
import { ABSENT_FILE_HASH, assertReconcilePins, readReconcileState, reconcileFileReading, reconcileReadOptions, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
import { verifyReconcileBackup } from './reconcile-backup.ts';
import { assertAutoDecisions } from './reconcile-additive.ts';
+import { bindOrigin } from './origin-guard.ts';
const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows page ${slug} in source ${sourceId} as stored now, with its revision, read-only.`,
{ argv: ['gbrain', 'get', '--source', sourceId, '--', slug] });
@@ -158,8 +159,7 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
apply: async tx => {
await ready.apply(tx);
if (state.originSourcePath) {
- await tx.executeRaw(`UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL
- AND source_path IS NULL`, [row.source_id, row.slug, state.originSourcePath]);
+ await bindOrigin(tx, { sourceId: row.source_id, slug: row.slug, sourcePath: state.originSourcePath, onlyIfUnset: true, liveOnly: true });
}
// The page has a canonical origin (adopted above, or already recorded, #6536): drop the #5254 database-only classification.
await tx.executeRaw(`UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL
diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.ts
index 044e42efc0..5eaa8db3fc 100644
--- a/src/core/persistence/segmented-apply.ts
+++ b/src/core/persistence/segmented-apply.ts
@@ -38,6 +38,7 @@ import { bodyStagingGoneError, LIVE_STAGING_STATES } from '../engine-sql/page-bo
import { segmentedPageSearchable } from './searchable.ts';
import { stableJson } from './digest.ts';
import { pageBodyOverCeilingError } from '../page-body/page-shape.ts';
+import { assertOriginUnclaimed } from './origin-guard.ts';
const BODY_KEYS = new Set(['compiled_truth', 'timeline', 'content']);
@@ -160,6 +161,7 @@ export async function sealSegmentedPage(tx: Pick<BrainEngine, 'executeRaw'>, pag
export async function applySegmentedBody(tx: BrainEngine, input: SegmentedApplyInput): Promise<SegmentedApplied> {
const { prepared } = input;
let pageId = input.pageId;
+ await assertOriginUnclaimed(tx, { sourceId: input.sourceId, slug: input.slug, pageId, sourcePath: input.meta.source_path ?? null, revive: true });
if (prepared.createRows) {
// A create inserts its manifest rows before the flip checks its staging: a staging a fact purge aborted (and whose
// claim-bearing texts it deleted) refuses here, not on the manifest's text foreign key.
diff --git a/src/core/persistence/sync-image.ts b/src/core/persistence/sync-image.ts
index 6759a2ae3e..47d45fa726 100644
--- a/src/core/persistence/sync-image.ts
+++ b/src/core/persistence/sync-image.ts
@@ -24,6 +24,7 @@ import { sha256 } from './digest.ts';
import type { PreparedMutation } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
import type { PreparedContentImport } from './prepared-import.ts';
+import { bindOrigin } from './origin-guard.ts';
/** The frozen intent fields of an image entry: the bytes as base64 and their hash (`rawHash` and `content` agree on a committed, clean file). */
export function frozenImageIntent(bytes: Buffer): { content: string; contentHash: string } {
@@ -94,7 +95,7 @@ export async function prepareManagedSyncImage(engine: BrainEngine, row: WriteReq
noop: ready.noop && !ctx.renamedFrom, contentUnchanged: ready.noop && !ctx.renamedFrom, deferEmbedding: true, apply: async tx => {
if (ctx.renamedFrom) { await tx.createVersion(ctx.renamedFrom.slug, { sourceId: row.source_id }); await tx.softDeletePage(ctx.renamedFrom.slug, { sourceId: row.source_id }); }
await ready.apply(tx);
- await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
+ await bindOrigin(tx, { sourceId: row.source_id, slug: row.slug, sourcePath: p.sourcePath, liveOnly: true });
await ctx.releaseHold(tx);
await ctx.recordProvenance(tx);
mutation.postimage = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 971bd62177..e8da8c67fa 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -60,6 +60,7 @@ import { describeFixes } from '../fence-repair/report.ts';
import { fenceFixesWire } from '../fence-repair/tier1.ts';
import type { FenceFix } from '../fence-repair/types.ts';
import { VERSION } from '../../version.ts';
+import { bindOrigin } from './origin-guard.ts';
/** The options that select a managed sync cursor (its key), recorded so a refusal can print the exact retry. */
export interface SyncCursorOptions { full: boolean; workingTree: boolean; srcSubpath: string | null; exclude: string[]; includeHidden: string[]; strategy: string | null }
@@ -766,7 +767,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
// A moved page is versioned from its own (rename source) read.
const installed = await applied.apply(tx, renamed ? undefined : preimage);
// Hash no-ops still repair a missing physical origin under the same guard (a page write records it itself).
- if (applied.noop) await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
+ if (applied.noop && p.sourcePath) await bindOrigin(tx, { sourceId: row.source_id, slug: row.slug, sourcePath: p.sourcePath, scope: originScope });
// #6536: the page now records this file as its origin, so it is no longer a #5254 database-only page.
await tx.executeRaw("UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND database_only_reason='unbound_source'", [row.source_id, row.slug]);
// #5984: the one read of the page after its last page write (the projections
diff --git a/src/core/persistence/sync-streamed.ts b/src/core/persistence/sync-streamed.ts
index c3c29f8efb..4189c7fd37 100644
--- a/src/core/persistence/sync-streamed.ts
+++ b/src/core/persistence/sync-streamed.ts
@@ -33,6 +33,7 @@ import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
import { recordSyncImportProvenance, type SyncImportProvenanceBase } from './sync-holds.ts';
import type { WriteRequest } from './model.ts';
import type { SyncIntent, SyncPreparedMutation } from './sync-prepare.ts';
+import { bindOrigin } from './origin-guard.ts';
/** A frozen Markdown file over the single-string ceiling: the bytes the owner streams and verifies. */
export interface SyncBodyRef { kind: 'git_blob' | 'input_file'; sha256: string; bytes: number; blob_oid: string }
@@ -124,7 +125,7 @@ export async function prepareManagedSyncStreamed(engine: BrainEngine, row: Write
await prepared.apply(tx);
// An unchanged body keeps its chunks (the no-op required a sealed page), so the move's new revision is sealed here.
if (renamed && prepared.noop) await sealSegmentedPage(tx, renamed.pageId);
- await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2 AND source_path IS DISTINCT FROM $3', [row.source_id, row.slug, p.sourcePath]);
+ await bindOrigin(tx, { sourceId: row.source_id, slug: row.slug, sourcePath: p.sourcePath });
await tx.executeRaw("UPDATE pages SET database_only_reason=NULL WHERE source_id=$1 AND slug=$2 AND database_only_reason='unbound_source'", [row.source_id, row.slug]);
const final = await tx.readPageSnapshot(row.slug, { ...source, includeDeleted: true });
await pipelined(tx, [
diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.ts
index 107b0be5f2..d7f0231059 100644
--- a/src/core/persistence/worktree-refresh.ts
+++ b/src/core/persistence/worktree-refresh.ts
@@ -38,6 +38,7 @@ import { startPersistenceConsumer } from './service.ts';
import { lockTopologyPrincipal, lockTopologyRows, topologyPrincipal, withTopologyLocks } from './topology-locks.ts';
import { ACTIVE_REFRESH_STATES_SQL, CHECKOUT_EFFECT_KINDS_SQL, type WorktreeRefreshState } from './worktree-refresh-schema.ts';
import { gitChildEnv } from '../git-env.ts';
+import { classifyOriginUniqueViolation } from './origin-guard.ts';
export interface WorktreeRefreshRow {
id: string; worktree_id: string; source_ids: string[]; principal_id: string; owner_epoch: string | number;
@@ -441,7 +442,7 @@ async function fenceDraining(engine: BrainEngine, sourceId: string, plan: Plan,
plan.oldHead, plan.targetHead, plan.upstreamRef, plan.preserved]);
return row;
})).catch(error => {
- if ((error as { code?: string }).code === '23505') throw refusal('refresh_in_progress', 'Another refresh of this worktree started first.', `gbrain sources refresh ${sourceId} --resume`);
+ if ((error as { code?: string }).code === '23505' && !classifyOriginUniqueViolation(error)) throw refusal('refresh_in_progress', 'Another refresh of this worktree started first.', `gbrain sources refresh ${sourceId} --resume`);
throw error;
});
}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index edcbd239b4..e291b48536 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -7,6 +7,7 @@ import { mutatePageTag } from './page-state/tags.ts';
import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } from './page-state/types.ts';
import type { GetVersionsOpts, PageVersionRows } from './page-state/version-types.ts';
import { assertPageRevision } from './page-state/types.ts';
+import { assertOriginUnclaimed, assertRevivalUnclaimed, classifyOriginUniqueViolation } from './persistence/origin-guard.ts';
import { lockUnheldPageKeys, withHeldPageKeys, type HeldPageKeys } from './page-state/guards.ts';
import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';
import { readPageSnapshotsBatch } from './page-snapshot-batch.ts';
@@ -1239,7 +1240,8 @@ export class PGLiteEngine implements BrainEngine {
if (opts?.expectedRevision !== undefined || opts?.force !== undefined) {
assertPageRevision(await tx.readPageSnapshot(slug, { sourceId, includeDeleted: true }), opts);
}
- return pagesImpl.putPage((tx as PGLiteEngine).engineSql, slug, page, opts, (s, src) => tx.getPage(s, { sourceId: src }));
+ await assertOriginUnclaimed(tx, { sourceId, slug, sourcePath: page.source_path ?? null, revive: true });
+ return pagesImpl.putPage((tx as PGLiteEngine).engineSql, slug, page, opts, (s, src) => tx.getPage(s, { sourceId: src })).catch(error => { throw classifyOriginUniqueViolation(error) ?? error; });
};
return opts?.inline && this._pageTransaction ? write(this) : this.transaction(write);
}
@@ -1287,7 +1289,7 @@ export class PGLiteEngine implements BrainEngine {
}
async restorePage(slug: string, opts?: { sourceId?: string }): Promise<boolean> {
- return pagesImpl.restorePage(this.engineSql, slug, opts);
+ return this.transaction(async tx => { await assertRevivalUnclaimed(tx, slug, opts?.sourceId); return pagesImpl.restorePage((tx as PGLiteEngine).engineSql, slug, opts); });
}
async purgeDeletedPages(
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 2e9f84b425..e23a2ee94c 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -5,6 +5,7 @@ import { mutatePageTag } from './page-state/tags.ts';
import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } from './page-state/types.ts';
import type { GetVersionsOpts, PageVersionRows } from './page-state/version-types.ts';
import { assertPageRevision } from './page-state/types.ts';
+import { assertOriginUnclaimed, assertRevivalUnclaimed, classifyOriginUniqueViolation } from './persistence/origin-guard.ts';
import { lockUnheldPageKeys, withHeldPageKeys, type HeldPageKeys } from './page-state/guards.ts';
import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';
import { readPageSnapshotsBatch } from './page-snapshot-batch.ts';
@@ -813,7 +814,8 @@ export class PostgresEngine implements BrainEngine {
if (opts?.expectedRevision !== undefined || opts?.force !== undefined) {
assertPageRevision(await tx.readPageSnapshot(slug, { sourceId, includeDeleted: true }), opts);
}
- return pagesImpl.putPage((tx as PostgresEngine).engineSql, slug, page, opts);
+ await assertOriginUnclaimed(tx, { sourceId, slug, sourcePath: page.source_path ?? null, revive: true });
+ return pagesImpl.putPage((tx as PostgresEngine).engineSql, slug, page, opts).catch(error => { throw classifyOriginUniqueViolation(error) ?? error; });
};
return opts?.inline && this._pageTransaction ? write(this) : this.transaction(write);
}
@@ -859,7 +861,7 @@ export class PostgresEngine implements BrainEngine {
}
async restorePage(slug: string, opts?: { sourceId?: string }): Promise<boolean> {
- return pagesImpl.restorePage(this.engineSql, slug, opts);
+ return this.transaction(async tx => { await assertRevivalUnclaimed(tx, slug, opts?.sourceId); return pagesImpl.restorePage((tx as PostgresEngine).engineSql, slug, opts); });
}
async purgeDeletedPages(
diff --git a/src/core/repair/fences.ts b/src/core/repair/fences.ts
index d437064a28..333825be49 100644
--- a/src/core/repair/fences.ts
+++ b/src/core/repair/fences.ts
@@ -291,7 +291,7 @@ export const fencesRepair: RepairHandler = {
}
const read = await readFenceTarget(engine, src, { key: cand.key, path: cand.path });
if (!read.ok) {
- if (read.reason !== 'gone') await keep({ item: name, reason: read.reason, tier: 'manual', resolution: read.reason === 'unsafe_path'
+ if (read.reason !== 'gone') await keep({ item: name, reason: read.reason, tier: 'manual', resolution: read.reason === 'origin_conflict' ? read.message : read.reason === 'unsafe_path'
? `${cand.path} is a symlink, sits under one, or resolves outside the source root; gbrain never writes through one. Replace it with the real file.`
: `${cand.path} is not valid UTF-8; re-save it as UTF-8 and preview again.` });
continue;
diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.ts
index 79419c69a7..fa1caacf90 100644
--- a/src/core/repair/file-drift.ts
+++ b/src/core/repair/file-drift.ts
@@ -68,6 +68,7 @@ import { ghostPageNow, scanGhostSource, type GhostOwner, type GhostPage } from '
import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed } from '../sync-reconcile.ts';
import { GHOST_PURGE_FUSE_HOURS, GHOST_REPAIR_LIMIT, ghostScanRefusal, massGhosts, massRefusal, retireGhost } from './ghost-pages.ts';
import { prepareReconcileResult } from '../persistence/reconcile-prepare.ts';
+import { canonicalOriginPage, originConflictMessage, originTwinsFix } from '../persistence/origin-guard.ts';
import { assertReconcileOutputPath, assertReconcileSize } from '../persistence/reconcile-backup.ts';
import { authorizeReconcile, runReconcileApply } from '../persistence/reconcile.ts';
import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';
@@ -277,6 +278,16 @@ async function survey(engine: BrainEngine, scope: RepairScope, opts: Pick<Repair
next_actions: next.length ? [...next.map(command => `Preview: ${command} (or --prefer database)`), 'Or preview single pages with --slug <slug>.'] : [] } };
}
+/** #6948: a page is repaired from a file only when it is that file's canonical page; a twin (or an ambiguous file) is refused `origin_conflict`. */
+async function refuseForeignOrigin(engine: BrainEngine, sourceId: string, slug: string, origin: string): Promise<void> {
+ const owner = await canonicalOriginPage(engine, sourceId, origin);
+ if (!owner || !('ambiguous' in owner) && owner.slug === slug) return;
+ throw opError('page_identity_changed', `Another live page of source ${sourceId} owns ${origin}, so ${slug} is not repaired from it.`,
+ 'ambiguous' in owner ? originConflictMessage(sourceId, origin, owner.ambiguous)
+ : `Page ${owner.slug} is the canonical page of ${origin}; repair it with --slug ${owner.slug}, or preview gbrain repair origin-twins --source ${sourceId} to merge ${slug} into it.`,
+ { detail: 'origin_conflict', fix: originTwinsFix(sourceId) });
+}
+
/**
* One drifted page resolved with `prefer` winning, as a ready reconcile preview: the preferred side's decisions over
* reconcile's protections, the size check, and the exceptions. Throws `invalid_params` when a path still needs a
@@ -285,10 +296,12 @@ async function survey(engine: BrainEngine, scope: RepairScope, opts: Pick<Repair
export async function prepareDriftPage(engine: BrainEngine, sourceId: string, slug: string, prefer: DriftSide, assessmentAt: string,
opts: { fileGone?: boolean } = {}): Promise<ArtifactPage> {
const snapshotRow = await engine.readPageSnapshot(slug, { sourceId });
+ if (snapshotRow?.page.source_path) await refuseForeignOrigin(engine, sourceId, slug, snapshotRow.page.source_path);
const adopt = !opts.fileGone && !!snapshotRow && !snapshotRow.page.source_path && !snapshotRow.page.source_uri;
const state = await readReconcileState(engine, sourceId, slug, assessmentAt, { adoptSlugPath: adopt, ...(opts.fileGone ? { fileGone: true } : {}) });
if (opts.fileGone && state.pins.raw_file_hash !== ABSENT_FILE_HASH) throw opError('source_changed', 'The canonical file reappeared during the preview.',
`Nothing was written. The canonical file of ${slug} in '${sourceId}' exists again; preview the page again.`);
+ if (adopt && state.originSourcePath) await refuseForeignOrigin(engine, sourceId, slug, state.originSourcePath);
const database = reconcileCanonical(state.snapshot.page, state.snapshot.tags);
const file = reconcileCanonical(state.file, state.file.tags);
const decisions = preferSideDecisions(state.file, database, prefer);
diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.ts
index c69aa4e826..fc65796a90 100644
--- a/src/core/repair/frontmatter.ts
+++ b/src/core/repair/frontmatter.ts
@@ -63,6 +63,7 @@ import { materializedSnapshot, segmentedOverCeiling } from '../persistence/segme
import { pageBodyOverCeilingError } from '../page-body/page-shape.ts';
import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';
import { gitChildEnv } from '../git-env.ts';
+import { bindOrigin, originConflictMessage, pickCanonicalOrigin } from '../persistence/origin-guard.ts';
type Mode = 'managed' | 'legacy';
type RepairClass = 'safe' | 'interpretive';
@@ -224,10 +225,13 @@ function markdownFiles(root: string): string[] {
interface PageRow { id: number; slug: string; source_path: string; revision: string; title: string; head: string }
-async function pagesByOrigin(engine: BrainEngine, sourceId: string): Promise<Map<string, PageRow>> {
+/** Each recorded origin's canonical live page (#6948: twins resolve to the page whose slug the file derives, else stay ambiguous). */
+async function pagesByOrigin(engine: BrainEngine, sourceId: string): Promise<Map<string, PageRow | { ambiguous: string[] }>> {
const rows = await engine.executeRaw<PageRow>(`SELECT id, slug, source_path, knowledge_revision::text AS revision, title, left(compiled_truth, 400) AS head
- FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL`, [sourceId]);
- return new Map(rows.map(row => [row.source_path, { ...row, id: Number(row.id) }]));
+ FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL ORDER BY slug`, [sourceId]);
+ const grouped = new Map<string, PageRow[]>();
+ for (const row of rows) grouped.set(row.source_path, [...grouped.get(row.source_path) ?? [], { ...row, id: Number(row.id) }]);
+ return new Map([...grouped].map(([path, pages]) => [path, pickCanonicalOrigin(pages, path)!]));
}
/**
@@ -289,7 +293,7 @@ interface Analysis {
review?: NeedsReview;
}
-interface FileContext { engine: BrainEngine; src: SourceRoot; includeAmbiguous: boolean; pages: Map<string, PageRow> }
+interface FileContext { engine: BrainEngine; src: SourceRoot; includeAmbiguous: boolean; pages: Map<string, PageRow | { ambiguous: string[] }> }
/** One file's proposal, pending interpretation, or manual fix; null when it needs nothing. */
async function analyzeFile(ctx: FileContext, path: string, hold: GitHoldRecord | undefined): Promise<Analysis | null> {
@@ -308,6 +312,7 @@ async function analyzeFile(ctx: FileContext, path: string, hold: GitHoldRecord |
if (!Buffer.from(content, 'utf8').equals(bytes)) return review(hold?.code ?? 'invalid_frontmatter', `${path} is not valid UTF-8, so gbrain will not rewrite it; re-save it as UTF-8, then preview again.`);
const sourcePath = hold?.source_path ?? path;
const page = ctx.pages.get(sourcePath);
+ if (page && 'ambiguous' in page) return review('origin_conflict', originConflictMessage(src.sourceId, sourcePath, page.ambiguous));
const slugCtx: SlugContext = { expectedSlug: resolveSlugForPath(sourcePath), slugExempt: declared => page?.source_path === sourcePath && declared === page.slug };
const found = inspect(content, path, slugCtx, size);
const heldBefore = hold && hold.page_id !== null && ['ambiguous_protected_key', 'ambiguous_identity_key'].includes(hold.meta.reason ?? '')
@@ -358,6 +363,7 @@ async function bindProposal(ctx: FileContext, path: string, hold: GitHoldRecord
const { engine, src } = ctx;
const sourcePath = hold?.source_path ?? path;
const page = ctx.pages.get(sourcePath);
+ if (page && 'ambiguous' in page) return { source_id: src.sourceId, path, code: 'origin_conflict', resolution: originConflictMessage(src.sourceId, sourcePath, page.ambiguous) };
const slug = page?.slug ?? (proposal.rename_from ? resolveSlugForPath(sourcePath) : hold?.slug ?? resolveSlugForPath(sourcePath));
const snapshot = await engine.readPageSnapshot(slug, { sourceId: src.sourceId, includeDeleted: true });
// Wave B decision #1: the re-import compares the stored body whole, which a page stored in segments allows up to 24 MiB.
@@ -567,7 +573,7 @@ async function applyRepair(ctx: OperationContext, repair: ApprovedRepair, select
const from = repair.rename_from;
await maintenanceTransaction(ctx.engine, async tx => {
if (await tx.updateSlug(from.slug, repair.slug, { sourceId: repair.source_id }) === 1) {
- await tx.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2 AND source_id=$3', [repair.source_path, from.pageId, repair.source_id]);
+ await bindOrigin(tx, { sourceId: repair.source_id, pageId: from.pageId, sourcePath: repair.source_path });
}
});
}
diff --git a/src/core/repair/missing-tables.ts b/src/core/repair/missing-tables.ts
index 87fb897ef5..8c9139b63d 100644
--- a/src/core/repair/missing-tables.ts
+++ b/src/core/repair/missing-tables.ts
@@ -18,6 +18,7 @@ import { relationExists } from '../persistence/rebuildable-cache.ts';
import { isLockTimeoutError } from '../retry-matcher.ts';
import { readMissingTables, recreateStep } from '../schema-missing-tables.ts';
import { afterCursor, type RepairHandler, type RepairItem, type RepairPlan } from './core.ts';
+import { classifyOriginUniqueViolation } from '../persistence/origin-guard.ts';
const PREVIEW = 'gbrain repair missing-tables';
const DOCS = 'docs/guides/repair.md#missing-tables';
@@ -71,7 +72,7 @@ export const missingTablesRepair: RepairHandler = {
throw new OperationError('schema_owner_required', `This database role may not create ${item.slug}, so nothing was recreated.`,
`Connect as the role that owns the brain tables (the one apply-migrations uses) and run: ${PREVIEW} --apply --expect ${opts?.expect ?? '<preview-hash>'}`, DOCS);
}
- if ((code === '23505' || code === '42P07') && await relationExists(ctx.engine, item.slug)) return { applied: false, outcome: 'already_present' };
+ if ((code === '23505' && !classifyOriginUniqueViolation(error) || code === '42P07') && await relationExists(ctx.engine, item.slug)) return { applied: false, outcome: 'already_present' };
if (ctx.engine.kind === 'postgres' && isLockTimeoutError(error)) {
throw schemaLockBlockedError({ step: `repair missing-tables (${item.slug})`, timeoutMs: resolveSchemaLockTimeoutMs(), sessions: null, sampledDuringWait: false });
}
diff --git a/src/core/repair/rename-identity.ts b/src/core/repair/rename-identity.ts
index aa8d1ea7e3..1c4dc4c12b 100644
--- a/src/core/repair/rename-identity.ts
+++ b/src/core/repair/rename-identity.ts
@@ -45,6 +45,7 @@ import { purgedSlug } from '../../commands/sync/rename-collision.ts';
import { IDENTITY_DOWNGRADE_OP, IDENTITY_HOLD_RELEASE, MANAGED_REMEDY_UNAVAILABLE, identityDowngradeReasonText, identityRemedyParts, identityRestoreArgv, listIdentityDowngrades,
renameIdentityPreviewArgv, settleIdentityDowngrade, withIdentityRemedies, type IdentityDowngrade, type IdentityRemedyDisposition, type IdentityRemedyParts } from '../sync-identity-downgrades.ts';
import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions } from './core.ts';
+import { assertOriginUnclaimed } from '../persistence/origin-guard.ts';
const DOCS = 'docs/guides/repair.md#rename-identity';
/** The restore alternative, named only where the source admits a restore (an unbound Postgres source with a checkout does not). */
@@ -254,8 +255,11 @@ async function carryIdentity(engine: BrainEngine, record: IdentityDowngrade, has
expired_at = n.expired_at, source = n.source, confidence = n.confidence, claim_metric = n.claim_metric, claim_value = n.claim_value, claim_unit = n.claim_unit,
claim_period = n.claim_period, event_type = n.event_type, attributed_to = n.attributed_to FROM facts n WHERE o.id = $1 AND n.id = $2`, [check.old_id, check.new_id]);
}
+ // origin-guard-ok: retires the provisional page to a tombstone, which claims no origin
await tx.executeRaw('UPDATE pages SET slug = $1, deleted_at = now(), updated_at = now() WHERE id = $2 AND source_id = $3', [retired, provisionalId, sourceId]);
if (await tx.updateSlug(oldSlug, newSlug, { sourceId }) !== 1) throw changedSincePreview(record, `page ${oldSlug} could not move to ${newSlug}`);
+ await assertOriginUnclaimed(tx, { sourceId, pageId: oldId, sourcePath: record.to, revive: true });
+ // origin-guard-ok: assertOriginUnclaimed above revives and assigns in the same transaction
await tx.executeRaw('UPDATE pages SET deleted_at = NULL, source_path = $1, updated_at = now() WHERE id = $2', [record.to, oldId]);
await movePageIdReferences(tx, provisionalId, oldId);
});
diff --git a/src/core/repair/slug-conflicts.ts b/src/core/repair/slug-conflicts.ts
index 3f9e462605..1811f60731 100644
--- a/src/core/repair/slug-conflicts.ts
+++ b/src/core/repair/slug-conflicts.ts
@@ -85,6 +85,7 @@ import { lineDiff } from './frontmatter.ts';
import { repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairPlanOptions, type RepairResult, type RepairScope } from './core.ts';
import { gitChildEnv } from '../git-env.ts';
import { recordSlugLineAlias } from '../page-state/rename-alias.ts';
+import { canonicalOriginPage, originConflictMessage } from '../persistence/origin-guard.ts';
type Tier = 'deterministic' | 'llm';
type DeterministicRule = 'absent_page' | 'different_type';
@@ -288,7 +289,7 @@ function slugPageMismatch(cand: Candidate, other: string, why: string): Analysis
+ `By hand: make the slug: line name ${cand.slug} exactly or move the file to the path that derives ${cand.slug}, commit, and run gbrain sync --source ${cand.src.id} --no-pull.` };
}
-async function readCandidate(engine: BrainEngine, src: FenceSource, path: string): Promise<{ ok: true; cand: Candidate } | { ok: false; reason: 'gone' | 'unsafe_path' | 'not_utf8' | 'no_checkout' }> {
+async function readCandidate(engine: BrainEngine, src: FenceSource, path: string): Promise<{ ok: true; cand: Candidate } | { ok: false; reason: 'gone' | 'unsafe_path' | 'not_utf8' | 'no_checkout' } | { ok: false; reason: 'origin_conflict'; message: string }> {
if (!src.root) return { ok: false, reason: 'no_checkout' };
const abs = join(src.root, path);
if (!existsSync(abs)) return { ok: false, reason: 'gone' };
@@ -301,7 +302,8 @@ async function readCandidate(engine: BrainEngine, src: FenceSource, path: string
if (!Buffer.from(content, 'utf8').equals(bytes)) return { ok: false, reason: 'not_utf8' };
const hold = await readGitHold(engine, src.id, src.incarnation, path);
const sourcePath = hold?.source_path ?? path;
- const [byOrigin] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND source_path=$2 AND deleted_at IS NULL LIMIT 1', [src.id, sourcePath]);
+ const byOrigin = await canonicalOriginPage(engine, src.id, sourcePath);
+ if (byOrigin && 'ambiguous' in byOrigin) return { ok: false, reason: 'origin_conflict', message: originConflictMessage(src.id, sourcePath, byOrigin.ambiguous) };
const slug = byOrigin?.slug ?? hold?.slug ?? resolveSlugForPath(sourcePath);
const snapshot = await engine.readPageSnapshot(slug, { sourceId: src.id, includeDeleted: true });
const declared = declaredSlug(content) ?? '';
@@ -446,7 +448,7 @@ export const slugConflictsRepair: RepairHandler = {
const read = await readCandidate(engine, src, path);
if (!read.ok) {
if (read.reason === 'gone' || read.reason === 'no_checkout') { skip(read.reason === 'gone' ? 'gone' : 'local_path_missing'); continue; }
- await keep({ reason: read.reason, tier: 'manual', resolution: read.reason === 'unsafe_path'
+ await keep({ reason: read.reason, tier: 'manual', resolution: read.reason === 'origin_conflict' ? read.message : read.reason === 'unsafe_path'
? `${path} is a symlink, sits under one, or resolves outside the source root; gbrain never writes through one. Replace it with the real file.`
: `${path} is not valid UTF-8; re-save it as UTF-8 and preview again.` });
continue;
diff --git a/src/core/sync-git.ts b/src/core/sync-git.ts
index 95837ae7fe..3142f63c97 100644
--- a/src/core/sync-git.ts
+++ b/src/core/sync-git.ts
@@ -31,34 +31,15 @@ export async function resolveSlugByPathOrSourcePath(
path: string,
sourceId?: string,
): Promise<string> {
- // v0.41.19.0 (D8): when sourceId is set, delegate to the new batch
- // resolveSlugsByPaths so single-call and batched paths share one SQL
- // owner + one fallback semantic. One Map allocation per single-call;
- // negligible cost. When sourceId is undefined (legacy unscoped callers),
- // a direct executeRaw runs instead — the batch method requires sourceId
- // to prevent the multi-source-bug-class on its new surface (D5). That
- // branch is NOT the historical unscoped query any more; see below.
+ // v0.41.19.0 (D8): the batch resolveSlugsByPaths is the one SQL owner and
+ // fallback semantic (#6948: the canonical page of the path, never an
+ // arbitrary twin). #3583 gate14: without a sourceId it is scoped to
+ // 'default', matching every WRITE the bare no-sourceId path performs
+ // (updateSlug, deletePage, the rename bookkeeping repair), so resolve and
+ // mutate agree on the scope.
try {
- if (sourceId) {
- const m = await engine.resolveSlugsByPaths([path], { sourceId });
- const slug = m.get(path);
- if (slug) return slug;
- } else {
- // #3583 gate14: scoped to 'default', matching every WRITE the bare
- // no-sourceId path performs (updateSlug, deletePage, the rename
- // bookkeeping repair — all default-scoped). The historical unscoped
- // form could hand back a row from ANOTHER source that happened to
- // share the source_path; the rename loop takes this return value
- // directly as its cheap-move target, so that foreign slug went to
- // updateSlug, the default-scoped move silently no-opped, and the
- // fallback import landed under a cross-source dedup. Resolve and
- // mutate must agree on the scope.
- const rows = await engine.executeRaw<{ slug: string }>(
- `SELECT slug FROM pages WHERE source_path = $1 AND source_id = $2 LIMIT 1`,
- [path, DEFAULT_SOURCE_ID],
- );
- if (rows.length > 0 && rows[0].slug) return rows[0].slug;
- }
+ const slug = (await engine.resolveSlugsByPaths([path], { sourceId: sourceId ?? DEFAULT_SOURCE_ID })).get(path);
+ if (slug) return slug;
} catch {
// Fall through — best-effort. Pre-migration brains or query errors
// shouldn't break delete/rename for path-derived pages.
@@ -74,6 +55,8 @@ export interface RefusedSlugResolution {
slug: string;
/** The DIFFERENT file the page at that slug records as its origin. */
originPath: string;
+ /** #6948: several live pages record the removed path and none is its canonical page; none is touched. */
+ claimants?: string[];
}
export interface RemovedPathSlugResolution {
@@ -90,6 +73,9 @@ function normalizeOriginPath(p: string): string {
/** One-line operator warning for a refused resolution (#3942). */
export function refusedRemovedPathMessage(r: RefusedSlugResolution): string {
+ if (r.claimants) {
+ return ` [sync] refusing to delete a page for removed path '${r.path}': ${r.claimants.join(', ')} all record it as their origin (preview gbrain repair origin-twins to choose the page that keeps it).`;
+ }
return (
` [sync] refusing to touch '${r.slug}' for removed path '${r.path}': ` +
`that page originates from '${r.originPath}' (#3942 — re-slugified paths ` +
@@ -164,8 +150,21 @@ export async function resolveSlugsForRemovedPaths(
}
}
+ const twins = new Map<string, string[]>();
+ const unresolved = paths.filter(p => !exact.has(p));
+ for (let i = 0; sourceId !== undefined && i < unresolved.length; i += DELETE_BATCH_SIZE) {
+ try {
+ const rows = await engine.executeRaw<{ source_path: string; slugs: string[] }>(`SELECT source_path, array_agg(slug ORDER BY slug) AS slugs FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND source_path = ANY($2::text[]) GROUP BY source_path HAVING count(*) > 1`, [sourceId, unresolved.slice(i, i + DELETE_BATCH_SIZE)]);
+ for (const row of rows) twins.set(row.source_path, row.slugs);
+ } catch {
+ // Best-effort, like phase 1.
+ }
+ }
const fallbacks: Array<{ path: string; slug: string }> = [];
for (const p of paths) {
+ const claimants = twins.get(p);
+ if (claimants) { refused.push({ path: p, slug: claimants[0]!, originPath: p, claimants }); continue; }
const hit = exact.get(p);
if (hit !== undefined) slugs.set(p, hit);
else fallbacks.push({ path: p, slug: resolveSlugForPath(p) });
diff --git a/src/core/sync-identity-downgrades.ts b/src/core/sync-identity-downgrades.ts
index 137c70fe3b..b6a7ba78de 100644
--- a/src/core/sync-identity-downgrades.ts
+++ b/src/core/sync-identity-downgrades.ts
@@ -20,6 +20,7 @@ import { getWorktreeBinding } from './persistence/ownership.ts';
import { readDatabaseOnlyActivatedSources } from './persistence/unbound-source.ts';
import { readManagedMode } from './persistence/managed-mode.ts';
import { previewHash } from './persistence/preview-approval.ts';
+import { canonicalOriginPage, pickCanonicalOrigin } from './persistence/origin-guard.ts';
import { resolveSlugForPath, type DowngradedRename, type RenameDowngradeReason } from './sync.ts';
export const IDENTITY_DOWNGRADE_OP = 'sync-identity-downgrade';
@@ -85,8 +86,8 @@ export async function recordIdentityDowngrades(engine: BrainEngine, sourceId: st
AND (source_path = $2 OR (source_path IS NULL AND slug = $3)) ORDER BY deleted_at DESC LIMIT 1`,
[sourceId, pair.from, resolveSlugForPath(pair.from)]);
if (!old) continue;
- const [fresh] = await engine.executeRaw<{ slug: string }>(
- 'SELECT slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND source_path = $2 LIMIT 1', [sourceId, pair.to]);
+ const owner = await canonicalOriginPage(engine, sourceId, pair.to);
+ const fresh = owner && !('ambiguous' in owner) ? owner : null;
const [counts] = await engine.executeRaw<{ facts: number | string; links: number | string; aliases: number | string }>(`SELECT
(SELECT count(*) FROM facts WHERE source_id = $1 AND entity_slug = $2) AS facts,
(SELECT count(*) FROM links WHERE from_page_id = $3 OR to_page_id = $3) AS links,
@@ -109,13 +110,17 @@ export async function recordIdentityDowngrades(engine: BrainEngine, sourceId: st
* `new_slug` is read live: the live page at the new path now (a held new file that was fixed later counts once it imports).
*/
export async function listIdentityDowngrades(engine: RestoreProbeEngine, sourceIds?: readonly string[]): Promise<IdentityDowngrade[]> {
- const rows = await engine.executeRaw<{ record: IdentityDowngrade | string; new_slug: string | null }>(
- `SELECT dg.completed_keys->0 AS record, np.slug AS new_slug FROM op_checkpoints dg JOIN pages p ON p.id::text = dg.fingerprint
- LEFT JOIN LATERAL (SELECT slug FROM pages WHERE source_id = p.source_id AND deleted_at IS NULL AND source_path = dg.completed_keys->0->>'to' LIMIT 1) np ON true
+ const rows = await engine.executeRaw<{ record: IdentityDowngrade | string; new_slugs: string[] | null }>(
+ `SELECT dg.completed_keys->0 AS record, np.slugs AS new_slugs FROM op_checkpoints dg JOIN pages p ON p.id::text = dg.fingerprint
+ LEFT JOIN LATERAL (SELECT array_agg(slug ORDER BY slug) AS slugs FROM pages WHERE source_id = p.source_id AND deleted_at IS NULL AND source_path = dg.completed_keys->0->>'to') np ON true
WHERE dg.op = $1 AND p.deleted_at IS NOT NULL AND ${identityDowngradeOpen('p')}
AND p.source_id = dg.completed_keys->0->>'source_id' AND ($2::text[] IS NULL OR p.source_id = ANY($2::text[]))
ORDER BY dg.completed_keys->0->>'recorded_at', dg.fingerprint`, [IDENTITY_DOWNGRADE_OP, sourceIds ? [...sourceIds] : null]);
- const records = rows.map(row => ({ ...(typeof row.record === 'string' ? JSON.parse(row.record) as IdentityDowngrade : row.record), new_slug: row.new_slug }));
+ const records = rows.map(row => {
+ const record = typeof row.record === 'string' ? JSON.parse(row.record) as IdentityDowngrade : row.record;
+ const owner = pickCanonicalOrigin((row.new_slugs ?? []).map(slug => ({ slug })), record.to);
+ return { ...record, new_slug: owner && !('ambiguous' in owner) ? owner.slug : null };
+ });
const restorable = new Map<string, boolean>();
for (const sourceId of new Set(records.map(record => record.source_id))) restorable.set(sourceId, await identityRestoreAvailable(engine, sourceId));
return records.map(record => ({ ...record, restore_available: restorable.get(record.source_id)! }));
diff --git a/src/core/write-through.ts b/src/core/write-through.ts
index 87ef80fe3c..ad95796fab 100644
--- a/src/core/write-through.ts
+++ b/src/core/write-through.ts
@@ -35,6 +35,7 @@ import {
isDurabilityHardened, commitWriteThroughFile, currentBranch, getLastPushOutcome,
type PushLogOutcome,
} from './brain-repo-durability.ts';
+import { bindOrigin } from './persistence/origin-guard.ts';
/** Minimal logger surface — structurally compatible with operations.ts `Logger`. */
export interface WriteThroughLogger {
@@ -474,18 +475,9 @@ export async function writePageThrough(
return { written: false, skipped: 'file_changed' };
}
+ await engine.transaction(tx => bindOrigin(tx, { sourceId, slug, sourcePath: sourcePathToBind, onlyIfUnset: true, liveOnly: true }));
assertSourceFilesystemActive();
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
-
- await engine.executeRaw(
- `UPDATE pages
- SET source_path = $1
- WHERE source_id = $2
- AND slug = $3
- AND deleted_at IS NULL
- AND source_path IS NULL`,
- [sourcePathToBind, sourceId, slug],
- );
assertSourceFilesystemActive();
atomicWriteFileSync(filePath, md, { verify: () => assertSourceFilesystemActive() });
diff --git a/test/check-origin-assignment.test.ts b/test/check-origin-assignment.test.ts
new file mode 100644
index 0000000000..f9786bb3a9
--- /dev/null
+++ b/test/check-origin-assignment.test.ts
@@ -0,0 +1,41 @@
+/**
+ * Self-test for scripts/check-origin-assignment.mjs, the #6948 guard that every
+ * page origin write goes through src/core/persistence/origin-guard.ts. Runs the
+ * scanner against the committed fixtures at
+ * test/fixtures/guards/check-origin-assignment.mjs/{bad,good}/ (the same
+ * fixtures guard-self-test.sh exercises) and against the real src/ tree.
+ */
+import { describe, expect, test } from 'bun:test';
+import { join } from 'node:path';
+
+const SCRIPT = join(import.meta.dir, '..', 'scripts', 'check-origin-assignment.mjs');
+const FIXTURES = join(import.meta.dir, 'fixtures', 'guards', 'check-origin-assignment.mjs');
+
+function runGuard(dir?: string): { code: number; out: string } {
+ const res = Bun.spawnSync([process.execPath, SCRIPT, ...(dir ? [dir] : [])], { cwd: join(import.meta.dir, '..') });
+ return { code: res.exitCode, out: res.stderr.toString() + res.stdout.toString() };
+}
+
+describe('check-origin-assignment guard', () => {
+ test('flags raw origin assignments, origin-carrying inserts, aliased SET clauses and unguarded slug renames', () => {
+ const { code, out } = runGuard(join(FIXTURES, 'bad'));
+ expect(code).toBe(1);
+ expect(out).toContain('fixture.ts:3: UPDATE pages assigns source_path');
+ expect(out).toContain('fixture.ts:7: INSERT INTO pages carries source_path');
+ expect(out).toContain('fixture.ts:11: UPDATE pages assigns source_path');
+ expect(out).toContain('fixture.ts:16: UPDATE pages renames a slug');
+ expect(out).toContain('bindOrigin');
+ });
+
+ test('passes clears, comparisons, origin-free inserts, marked guarded sites and renames, and doc comments', () => {
+ const { code, out } = runGuard(join(FIXTURES, 'good'));
+ expect(code).toBe(0);
+ expect(out).toContain('clean');
+ });
+
+ test('the real src/ tree is clean', () => {
+ const { code, out } = runGuard();
+ expect(code).toBe(0);
+ expect(out).toContain('clean');
+ }, 30_000);
+});
diff --git a/test/e2e/managed-sync-shared-origin-6517.test.ts b/test/e2e/managed-sync-shared-origin-6517.test.ts
index b7723eae7a..3628f364ef 100644
--- a/test/e2e/managed-sync-shared-origin-6517.test.ts
+++ b/test/e2e/managed-sync-shared-origin-6517.test.ts
@@ -68,8 +68,11 @@ for (const backend of testBackends()) describe(`[${backend}] #6517 managed sync
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };
expect((await sync(opts)).status).toBe('first_sync');
- await engine.transaction(tx => withCoordinatedWrite(tx, [id], () => tx.putPage('alpha-twin', { type: 'note', title: 'Twin', compiled_truth: 'A twin recording alpha.',
- timeline: '', frontmatter: {}, content_hash: 'twin', source_path: 'alpha.md' }, { sourceId: id }), TEST_WRITE_ATTRIBUTION));
+ // #6948: no writer records a held origin on a second page any more, so the twin's origin is set as legacy data left it.
+ await engine.transaction(tx => withCoordinatedWrite(tx, [id], async () => {
+ await tx.putPage('alpha-twin', { type: 'note', title: 'Twin', compiled_truth: 'A twin recording alpha.', timeline: '', frontmatter: {}, content_hash: 'twin' }, { sourceId: id });
+ await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [id, 'alpha-twin', 'alpha.md']);
+ }, TEST_WRITE_ATTRIBUTION));
return { id, root, file, opts };
}
diff --git a/test/e2e/origin-twins-6948.test.ts b/test/e2e/origin-twins-6948.test.ts
index c85e49d278..f90b81e76d 100644
--- a/test/e2e/origin-twins-6948.test.ts
+++ b/test/e2e/origin-twins-6948.test.ts
@@ -84,7 +84,9 @@ for (const backend of testBackends()) describe(`[${backend}] #6948 duplicate-ori
await write(id, async tx => {
await tx.executeRaw("SELECT set_config('gbrain.write_trust_tier', $1, true)", [alpha.trust_tier]);
await tx.putPage(twin.slug, { type: 'note', title: 'Example', compiled_truth: twin.same === false ? 'A different body.' : alpha.compiled_truth,
- timeline: alpha.timeline ?? '', frontmatter: twin.frontmatter ?? {}, content_hash: randomUUID(), source_path: 'alpha.md' }, { sourceId: id });
+ timeline: alpha.timeline ?? '', frontmatter: twin.frontmatter ?? {}, content_hash: randomUUID() }, { sourceId: id });
+ // Legacy data: no writer records a held origin on a second page any more, so the twin's origin is set directly.
+ await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [id, twin.slug, 'alpha.md']);
});
}
return { id, root, opts };
@@ -258,10 +260,14 @@ for (const backend of testBackends()) describe(`[${backend}] #6948 duplicate-ori
}
expect(await originIndexState(engine)).toBe('present');
expect(((await originTwinsEntry.run({ engine } as never)) as Array<{ status: string }>)[0]).toMatchObject({ status: 'ok' });
- // With the index present, a second live claim on an origin is refused by the database.
+ // With the index present, a second live claim on an origin is refused: by the writer guard, and by the database
+ // for a statement that skips the guard.
const refused = await write(f.id, tx => tx.putPage('alpha-third', { type: 'note', title: 'x', compiled_truth: 'x', timeline: '', frontmatter: {}, content_hash: 'x', source_path: 'alpha.md' }, { sourceId: f.id }))
.then(() => 'written', () => 'refused');
expect(refused).toBe('refused');
+ const unguarded = await engine.executeRaw("UPDATE pages SET source_path='alpha.md' WHERE source_id=$1 AND slug='beta'", [f.id])
+ .then(() => 'written', (error: { code?: unknown }) => String(error.code));
+ expect(unguarded).toBe('23505');
// The migration on a clean brain builds it (and is idempotent).
await v257.handler!(engine);
expect(await originIndexState(engine)).toBe('present');
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 62888f7e46..1e8d5d68e0 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -1288,6 +1288,7 @@
"pages_file_uri_name_idx": "CREATE INDEX pages_file_uri_name_idx ON public.pages USING btree (source_id, regexp_replace(source_uri, '^.*/'::text, ''::text)) WHERE (source_uri ~~ 'file:%'::text)",
"pages_generation_idx": "CREATE INDEX pages_generation_idx ON public.pages USING btree (generation)",
"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)",
+ "pages_live_origin_key": "CREATE UNIQUE INDEX pages_live_origin_key ON public.pages USING btree (source_id, source_path) WHERE ((deleted_at IS NULL) AND (source_path IS NOT NULL))",
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 887cda07a0..16f3aa169e 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -1288,6 +1288,7 @@
"pages_file_uri_name_idx": "CREATE INDEX pages_file_uri_name_idx ON public.pages USING btree (source_id, regexp_replace(source_uri, '^.*/'::text, ''::text)) WHERE (source_uri ~~ 'file:%'::text)",
"pages_generation_idx": "CREATE INDEX pages_generation_idx ON public.pages USING btree (generation)",
"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)",
+ "pages_live_origin_key": "CREATE UNIQUE INDEX pages_live_origin_key ON public.pages USING btree (source_id, source_path) WHERE ((deleted_at IS NULL) AND (source_path IS NOT NULL))",
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 6795e31c8f..cdeb10c34b 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -1284,6 +1284,7 @@
"pages_file_uri_name_idx": "CREATE INDEX pages_file_uri_name_idx ON public.pages USING btree (source_id, regexp_replace(source_uri, '^.*/'::text, ''::text)) WHERE (source_uri ~~ 'file:%'::text)",
"pages_generation_idx": "CREATE INDEX pages_generation_idx ON public.pages USING btree (generation)",
"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)",
+ "pages_live_origin_key": "CREATE UNIQUE INDEX pages_live_origin_key ON public.pages USING btree (source_id, source_path) WHERE ((deleted_at IS NULL) AND (source_path IS NOT NULL))",
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 916d6c4c50..beffd7b94a 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -1292,6 +1292,7 @@
"pages_file_uri_name_idx": "CREATE INDEX pages_file_uri_name_idx ON public.pages USING btree (source_id, regexp_replace(source_uri, '^.*/'::text, ''::text)) WHERE (source_uri ~~ 'file:%'::text)",
"pages_generation_idx": "CREATE INDEX pages_generation_idx ON public.pages USING btree (generation)",
"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)",
+ "pages_live_origin_key": "CREATE UNIQUE INDEX pages_live_origin_key ON public.pages USING btree (source_id, source_path) WHERE ((deleted_at IS NULL) AND (source_path IS NOT NULL))",
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 19742ce77c..92c6f5bed9 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -1292,6 +1292,7 @@
"pages_file_uri_name_idx": "CREATE INDEX pages_file_uri_name_idx ON public.pages USING btree (source_id, regexp_replace(source_uri, '^.*/'::text, ''::text)) WHERE (source_uri ~~ 'file:%'::text)",
"pages_generation_idx": "CREATE INDEX pages_generation_idx ON public.pages USING btree (generation)",
"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)",
+ "pages_live_origin_key": "CREATE UNIQUE INDEX pages_live_origin_key ON public.pages USING btree (source_id, source_path) WHERE ((deleted_at IS NULL) AND (source_path IS NOT NULL))",
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index f33f2ac2c8..0e11953cc1 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -1288,6 +1288,7 @@
"pages_file_uri_name_idx": "CREATE INDEX pages_file_uri_name_idx ON public.pages USING btree (source_id, regexp_replace(source_uri, '^.*/'::text, ''::text)) WHERE (source_uri ~~ 'file:%'::text)",
"pages_generation_idx": "CREATE INDEX pages_generation_idx ON public.pages USING btree (generation)",
"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)",
+ "pages_live_origin_key": "CREATE UNIQUE INDEX pages_live_origin_key ON public.pages USING btree (source_id, source_path) WHERE ((deleted_at IS NULL) AND (source_path IS NOT NULL))",
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index eaf1324610..f38a2a2088 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -88,7 +88,7 @@
" [INFO] supersession_calibration: Embeddings are off on this brain, so facts are only deduplicated by exact text; no supersession threshold applies.",
" [INFO] fact_admission_floors: Embeddings are off on this brain, so facts are admitted by keyword and named entity only; no cosine floor applies.",
" [OK] chat_fallback_chain: No chat_fallback_chain is set: every chat call uses only its own model.",
- " [OK] behavior_changes: Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.",
+ " [OK] behavior_changes: gbrain v0.60.296.0 changed 1 behavior on this brain. All stay on; this is a one-time disclosure, not a request for consent. (1) Managed sync no longer stops a whole source when several live pages record one file as their origin (duplicate-origin twins, #6948): only that file is held `origin_conflict` and the rest syncs. When the pages are verified duplicates (the page the path names, one body, a readable file, compatible ids, one visibility and trust tier, nothing the merge would lose), the sync merges the others into it right after the run: their links, relationship dates, timeline, raw data, user tags, aliases and facts move, their slugs become aliases, and they are soft-deleted without touching the file (restorable for 72 h; the receipt lists any frontmatter they carried that the file lacks). Opt out with `gbrain config set sync.origin_twins.auto_resolve false`. Any other group stays held for a person: `gbrain repair origin-twins --source <id>` previews every group, and `--slug <kept-slug>` detaches the others without deleting them. New index `pages_live_origin_key` makes a new twin unwritable; it is built only on a brain with no twins, so with twins the upgrade changes nothing and doctor `origin_twins` reports \"Index pending\" until the repair resolves them. gbrain doctor --only behavior_changes shows this again.",
" [OK] graph_coverage: Only 2 eligible entity pages (< 5) — coverage ratio not meaningful at this scale",
" [WARN] brain_score: Brain score 36/100 (embed 0/35, links 5/25, timeline density (entity and event pages) 15/15, orphans 6/15, dead-links 10/10)",
" Fix: gbrain doctor --remediation-plan --json --brain host",
@@ -203,6 +203,7 @@
" [OK] extract_atoms_held_failed: No managed atom page or transcript is held after repeated extraction failures.",
" [OK] extraction_input_truncated: Every page extraction read all of its input (no head-only, tail-window or size-skip receipts).",
" [OK] ghost_pages: No live page is missing its canonical file (5 page(s) inspected).",
+ " [OK] origin_twins: pages_live_origin_key is present: no two live pages can record one file.",
" [OK] rename_identity_downgrades: No rename that lost its page identity is waiting for a disposition.",
" [OK] purge_parked_pages: No soft-deleted page is parked by the managed purge.",
" [INFO] missing_recorded_files: Not applicable: no source is a classic checkout on this host (managed sources are checked by ghost_pages).",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 45979227c9..404da3e8b7 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -1147,8 +1147,34 @@
},
{
"category": "meta",
+ "details": {
+ "baseline": "<version>",
+ "shown": {
+ "cli": true,
+ "stdio": false
+ },
+ "since": "0.60.296.0"
+ },
"elapsed_ms": "<volatile>",
- "message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.",
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "behavior_changes",
+ "--json",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain doctor --only behavior_changes --json --brain host",
+ "consent": [],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/chat-fallback.md",
+ "next": "run",
+ "requires_exclusive": false,
+ "why": "Shows this disclosure again; read-only."
+ },
+ "message": "gbrain v0.60.296.0 changed 1 behavior on this brain. All stay on; this is a one-time disclosure, not a request for consent. (1) Managed sync no longer stops a whole source when several live pages record one file as their origin (duplicate-origin twins, #6948): only that file is held `origin_conflict` and the rest syncs. When the pages are verified duplicates (the page the path names, one body, a readable file, compatible ids, one visibility and trust tier, nothing the merge would lose), the sync merges the others into it right after the run: their links, relationship dates, timeline, raw data, user tags, aliases and facts move, their slugs become aliases, and they are soft-deleted without touching the file (restorable for 72 h; the receipt lists any frontmatter they carried that the file lacks). Opt out with `gbrain config set sync.origin_twins.auto_resolve false`. Any other group stays held for a person: `gbrain repair origin-twins --source <id>` previews every group, and `--slug <kept-slug>` detaches the others without deleting them. New index `pages_live_origin_key` makes a new twin unwritable; it is built only on a brain with no twins, so with twins the upgrade changes nothing and doctor `origin_twins` reports \"Index pending\" until the repair resolves them. gbrain doctor --only behavior_changes shows this again.",
"name": "behavior_changes",
"status": "ok"
},
@@ -3018,6 +3044,17 @@
"name": "ghost_pages",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#origin-twins",
+ "index": "present"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "pages_live_origin_key is present: no two live pages can record one file.",
+ "name": "origin_twins",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index ac76aab43d..639e2bd739 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -1207,8 +1207,34 @@
},
{
"category": "meta",
+ "details": {
+ "baseline": "<version>",
+ "shown": {
+ "cli": true,
+ "stdio": false
+ },
+ "since": "0.60.296.0"
+ },
"elapsed_ms": "<volatile>",
- "message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.",
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "behavior_changes",
+ "--json",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain doctor --only behavior_changes --json --brain host",
+ "consent": [],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/chat-fallback.md",
+ "next": "run",
+ "requires_exclusive": false,
+ "why": "Shows this disclosure again; read-only."
+ },
+ "message": "gbrain v0.60.296.0 changed 1 behavior on this brain. All stay on; this is a one-time disclosure, not a request for consent. (1) Managed sync no longer stops a whole source when several live pages record one file as their origin (duplicate-origin twins, #6948): only that file is held `origin_conflict` and the rest syncs. When the pages are verified duplicates (the page the path names, one body, a readable file, compatible ids, one visibility and trust tier, nothing the merge would lose), the sync merges the others into it right after the run: their links, relationship dates, timeline, raw data, user tags, aliases and facts move, their slugs become aliases, and they are soft-deleted without touching the file (restorable for 72 h; the receipt lists any frontmatter they carried that the file lacks). Opt out with `gbrain config set sync.origin_twins.auto_resolve false`. Any other group stays held for a person: `gbrain repair origin-twins --source <id>` previews every group, and `--slug <kept-slug>` detaches the others without deleting them. New index `pages_live_origin_key` makes a new twin unwritable; it is built only on a brain with no twins, so with twins the upgrade changes nothing and doctor `origin_twins` reports \"Index pending\" until the repair resolves them. gbrain doctor --only behavior_changes shows this again.",
"name": "behavior_changes",
"status": "ok"
},
@@ -3203,6 +3229,17 @@
"name": "ghost_pages",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#origin-twins",
+ "index": "present"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "pages_live_origin_key is present: no two live pages can record one file.",
+ "name": "origin_twins",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -5485,8 +5522,34 @@
},
{
"category": "meta",
+ "details": {
+ "baseline": "<version>",
+ "shown": {
+ "cli": true,
+ "stdio": false
+ },
+ "since": "0.60.296.0"
+ },
"elapsed_ms": "<volatile>",
- "message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.",
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "behavior_changes",
+ "--json",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain doctor --only behavior_changes --json --brain host",
+ "consent": [],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/chat-fallback.md",
+ "next": "run",
+ "requires_exclusive": false,
+ "why": "Shows this disclosure again; read-only."
+ },
+ "message": "gbrain v0.60.296.0 changed 1 behavior on this brain. All stay on; this is a one-time disclosure, not a request for consent. (1) Managed sync no longer stops a whole source when several live pages record one file as their origin (duplicate-origin twins, #6948): only that file is held `origin_conflict` and the rest syncs. When the pages are verified duplicates (the page the path names, one body, a readable file, compatible ids, one visibility and trust tier, nothing the merge would lose), the sync merges the others into it right after the run: their links, relationship dates, timeline, raw data, user tags, aliases and facts move, their slugs become aliases, and they are soft-deleted without touching the file (restorable for 72 h; the receipt lists any frontmatter they carried that the file lacks). Opt out with `gbrain config set sync.origin_twins.auto_resolve false`. Any other group stays held for a person: `gbrain repair origin-twins --source <id>` previews every group, and `--slug <kept-slug>` detaches the others without deleting them. New index `pages_live_origin_key` makes a new twin unwritable; it is built only on a brain with no twins, so with twins the upgrade changes nothing and doctor `origin_twins` reports \"Index pending\" until the repair resolves them. gbrain doctor --only behavior_changes shows this again.",
"name": "behavior_changes",
"status": "ok"
},
@@ -7481,6 +7544,17 @@
"name": "ghost_pages",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#origin-twins",
+ "index": "present"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "pages_live_origin_key is present: no two live pages can record one file.",
+ "name": "origin_twins",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index 8766be171c..86d9fc9f9b 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -1199,8 +1199,34 @@
},
{
"category": "meta",
+ "details": {
+ "baseline": "<version>",
+ "shown": {
+ "cli": true,
+ "stdio": false
+ },
+ "since": "0.60.296.0"
+ },
"elapsed_ms": "<volatile>",
- "message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.",
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "behavior_changes",
+ "--json",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain doctor --only behavior_changes --json --brain host",
+ "consent": [],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/chat-fallback.md",
+ "next": "run",
+ "requires_exclusive": false,
+ "why": "Shows this disclosure again; read-only."
+ },
+ "message": "gbrain v0.60.296.0 changed 1 behavior on this brain. All stay on; this is a one-time disclosure, not a request for consent. (1) Managed sync no longer stops a whole source when several live pages record one file as their origin (duplicate-origin twins, #6948): only that file is held `origin_conflict` and the rest syncs. When the pages are verified duplicates (the page the path names, one body, a readable file, compatible ids, one visibility and trust tier, nothing the merge would lose), the sync merges the others into it right after the run: their links, relationship dates, timeline, raw data, user tags, aliases and facts move, their slugs become aliases, and they are soft-deleted without touching the file (restorable for 72 h; the receipt lists any frontmatter they carried that the file lacks). Opt out with `gbrain config set sync.origin_twins.auto_resolve false`. Any other group stays held for a person: `gbrain repair origin-twins --source <id>` previews every group, and `--slug <kept-slug>` detaches the others without deleting them. New index `pages_live_origin_key` makes a new twin unwritable; it is built only on a brain with no twins, so with twins the upgrade changes nothing and doctor `origin_twins` reports \"Index pending\" until the repair resolves them. gbrain doctor --only behavior_changes shows this again.",
"name": "behavior_changes",
"status": "ok"
},
@@ -3206,6 +3232,17 @@
"name": "ghost_pages",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#origin-twins",
+ "index": "present"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "pages_live_origin_key is present: no two live pages can record one file.",
+ "name": "origin_twins",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
@@ -5478,8 +5515,34 @@
},
{
"category": "meta",
+ "details": {
+ "baseline": "<version>",
+ "shown": {
+ "cli": true,
+ "stdio": false
+ },
+ "since": "0.60.296.0"
+ },
"elapsed_ms": "<volatile>",
- "message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.",
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "behavior_changes",
+ "--json",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain doctor --only behavior_changes --json --brain host",
+ "consent": [],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/chat-fallback.md",
+ "next": "run",
+ "requires_exclusive": false,
+ "why": "Shows this disclosure again; read-only."
+ },
+ "message": "gbrain v0.60.296.0 changed 1 behavior on this brain. All stay on; this is a one-time disclosure, not a request for consent. (1) Managed sync no longer stops a whole source when several live pages record one file as their origin (duplicate-origin twins, #6948): only that file is held `origin_conflict` and the rest syncs. When the pages are verified duplicates (the page the path names, one body, a readable file, compatible ids, one visibility and trust tier, nothing the merge would lose), the sync merges the others into it right after the run: their links, relationship dates, timeline, raw data, user tags, aliases and facts move, their slugs become aliases, and they are soft-deleted without touching the file (restorable for 72 h; the receipt lists any frontmatter they carried that the file lacks). Opt out with `gbrain config set sync.origin_twins.auto_resolve false`. Any other group stays held for a person: `gbrain repair origin-twins --source <id>` previews every group, and `--slug <kept-slug>` detaches the others without deleting them. New index `pages_live_origin_key` makes a new twin unwritable; it is built only on a brain with no twins, so with twins the upgrade changes nothing and doctor `origin_twins` reports \"Index pending\" until the repair resolves them. gbrain doctor --only behavior_changes shows this again.",
"name": "behavior_changes",
"status": "ok"
},
@@ -7485,6 +7548,17 @@
"name": "ghost_pages",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#origin-twins",
+ "index": "present"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "pages_live_origin_key is present: no two live pages can record one file.",
+ "name": "origin_twins",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 519c3e0a75..71245accb8 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -1062,8 +1062,34 @@
},
{
"category": "meta",
+ "details": {
+ "baseline": "<version>",
+ "shown": {
+ "cli": false,
+ "stdio": false
+ },
+ "since": "0.60.296.0"
+ },
"elapsed_ms": "<volatile>",
- "message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.",
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "behavior_changes",
+ "--json",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain doctor --only behavior_changes --json --brain host",
+ "consent": [],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/chat-fallback.md",
+ "next": "run",
+ "requires_exclusive": false,
+ "why": "Shows this disclosure again; read-only."
+ },
+ "message": "gbrain v0.60.296.0 changed 1 behavior on this brain. All stay on; this is a one-time disclosure, not a request for consent. (1) Managed sync no longer stops a whole source when several live pages record one file as their origin (duplicate-origin twins, #6948): only that file is held `origin_conflict` and the rest syncs. When the pages are verified duplicates (the page the path names, one body, a readable file, compatible ids, one visibility and trust tier, nothing the merge would lose), the sync merges the others into it right after the run: their links, relationship dates, timeline, raw data, user tags, aliases and facts move, their slugs become aliases, and they are soft-deleted without touching the file (restorable for 72 h; the receipt lists any frontmatter they carried that the file lacks). Opt out with `gbrain config set sync.origin_twins.auto_resolve false`. Any other group stays held for a person: `gbrain repair origin-twins --source <id>` previews every group, and `--slug <kept-slug>` detaches the others without deleting them. New index `pages_live_origin_key` makes a new twin unwritable; it is built only on a brain with no twins, so with twins the upgrade changes nothing and doctor `origin_twins` reports \"Index pending\" until the repair resolves them. gbrain doctor --only behavior_changes shows this again.",
"name": "behavior_changes",
"status": "ok"
},
@@ -2758,6 +2784,17 @@
"name": "ghost_pages",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#origin-twins",
+ "index": "present"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "pages_live_origin_key is present: no two live pages can record one file.",
+ "name": "origin_twins",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 01dc71a4c3..a4e4140307 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -1118,8 +1118,34 @@
},
{
"category": "meta",
+ "details": {
+ "baseline": "<version>",
+ "shown": {
+ "cli": false,
+ "stdio": false
+ },
+ "since": "0.60.296.0"
+ },
"elapsed_ms": "<volatile>",
- "message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.",
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "behavior_changes",
+ "--json",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain doctor --only behavior_changes --json --brain host",
+ "consent": [],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/chat-fallback.md",
+ "next": "run",
+ "requires_exclusive": false,
+ "why": "Shows this disclosure again; read-only."
+ },
+ "message": "gbrain v0.60.296.0 changed 1 behavior on this brain. All stay on; this is a one-time disclosure, not a request for consent. (1) Managed sync no longer stops a whole source when several live pages record one file as their origin (duplicate-origin twins, #6948): only that file is held `origin_conflict` and the rest syncs. When the pages are verified duplicates (the page the path names, one body, a readable file, compatible ids, one visibility and trust tier, nothing the merge would lose), the sync merges the others into it right after the run: their links, relationship dates, timeline, raw data, user tags, aliases and facts move, their slugs become aliases, and they are soft-deleted without touching the file (restorable for 72 h; the receipt lists any frontmatter they carried that the file lacks). Opt out with `gbrain config set sync.origin_twins.auto_resolve false`. Any other group stays held for a person: `gbrain repair origin-twins --source <id>` previews every group, and `--slug <kept-slug>` detaches the others without deleting them. New index `pages_live_origin_key` makes a new twin unwritable; it is built only on a brain with no twins, so with twins the upgrade changes nothing and doctor `origin_twins` reports \"Index pending\" until the repair resolves them. gbrain doctor --only behavior_changes shows this again.",
"name": "behavior_changes",
"status": "ok"
},
@@ -2803,6 +2829,17 @@
"name": "ghost_pages",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#origin-twins",
+ "index": "present"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "pages_live_origin_key is present: no two live pages can record one file.",
+ "name": "origin_twins",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index f41abbea31..e7c62b7f11 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -1110,8 +1110,34 @@
},
{
"category": "meta",
+ "details": {
+ "baseline": "<version>",
+ "shown": {
+ "cli": false,
+ "stdio": false
+ },
+ "since": "0.60.296.0"
+ },
"elapsed_ms": "<volatile>",
- "message": "Nothing to disclose: this brain is a fresh install at v<version>, after every disclosed behavior change, so the one-time behavior-change notice does not apply.",
+ "fix": {
+ "actor": "agent",
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--only",
+ "behavior_changes",
+ "--json",
+ "--brain",
+ "host"
+ ],
+ "command": "gbrain doctor --only behavior_changes --json --brain host",
+ "consent": [],
+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/chat-fallback.md",
+ "next": "run",
+ "requires_exclusive": false,
+ "why": "Shows this disclosure again; read-only."
+ },
+ "message": "gbrain v0.60.296.0 changed 1 behavior on this brain. All stay on; this is a one-time disclosure, not a request for consent. (1) Managed sync no longer stops a whole source when several live pages record one file as their origin (duplicate-origin twins, #6948): only that file is held `origin_conflict` and the rest syncs. When the pages are verified duplicates (the page the path names, one body, a readable file, compatible ids, one visibility and trust tier, nothing the merge would lose), the sync merges the others into it right after the run: their links, relationship dates, timeline, raw data, user tags, aliases and facts move, their slugs become aliases, and they are soft-deleted without touching the file (restorable for 72 h; the receipt lists any frontmatter they carried that the file lacks). Opt out with `gbrain config set sync.origin_twins.auto_resolve false`. Any other group stays held for a person: `gbrain repair origin-twins --source <id>` previews every group, and `--slug <kept-slug>` detaches the others without deleting them. New index `pages_live_origin_key` makes a new twin unwritable; it is built only on a brain with no twins, so with twins the upgrade changes nothing and doctor `origin_twins` reports \"Index pending\" until the repair resolves them. gbrain doctor --only behavior_changes shows this again.",
"name": "behavior_changes",
"status": "ok"
},
@@ -2806,6 +2832,17 @@
"name": "ghost_pages",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#origin-twins",
+ "index": "present"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "pages_live_origin_key is present: no two live pages can record one file.",
+ "name": "origin_twins",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 8a3352efe5..e513bceabb 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6393,7 +6393,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_drift\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_read_incomplete\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_changed\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_drain_lease_held\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 32ac4d4e6c..5dcd78f578 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 251,
+ "count": 252,
"gaps": [
17,
18,
@@ -41,7 +41,8 @@
"analyzeAfterIndexBuild": "7c24d458f4d7c0c9055c6371d02375075f25e16de937bc44e2b0a94b9983f3e0",
"backfillChunkVectors": "1c8cc09a28aa3e906fe2f112b71cd3aa61f750a99984e35a029cff9458272aa1",
"backfillPageVectors": "a325a5eee3bab49723af311f21b38a1ee4a0eaff1fb3c7e1539aa4dcb287ed66",
- "buildIndexOnline": "c030c55bc9eada25805881aae82368f14a57e456a4b4298b3a316ef973d51cc6",
+ "buildIndexOnline": "aea86be06da261a76f6fad15def8f417cb5318c7991d2ded3cd86aeed82fb2cc",
+ "buildOriginIndexIfClean": "cc6d16f50a4b5e303b87338700b9cded9784fc9cc9391c795bdd755e32385e6c",
"checkpointKey": "337ef776b18f428542093e27c4d570249d6a5856e5a17e4499d26a22877af34b",
"chunkSearchVectorTriggerFnSql": "93ed4e29aa058949621b4198fe1ec317218f4b9ec0db0626ec6dc7001032047d",
"clampOAuthTokenTtls": "b1e94ea8f5b3c3870a56b0f6d00d0a274c2e9dcad912b828848aec250732645f",
@@ -54,6 +55,7 @@
"migrateConnectorCheckpoints": "5c13e69a334bfc5275c7d555c4e7b28e034569f086dd4bd70b4b78fa4770dc7a",
"migrateLegacyTokens": "6e4abe3670127e7a495b56ecbf9f5789edd3a7362d45704656c2210a85b27f4c",
"migrationNotice": "9a6607b26a9719ef1833571b137bc8ebfcd1e16d545e89ff8728cf3ccbcbb409",
+ "originTwinsRepairCommand": "fb3c721e48d9f2a98845ef91231836d4a37eb5929e9a9b62f8dfab5ce395c462",
"pageSearchVectorTriggerFnSql": "c78074a731ae571c508ca0a84c6bb19ac34a933a7f4ab2068b47124aabb87435",
"quietMigrationNotices": "4045c32034a8f46204dd5d89e185ff5c35e8073f560f14caa8b127f8a695957c",
"readExistingEmbeddingShape": "16d92d7cd52d8ebd7e89982f02e1bbdd8e8d08a6712a4ce57fbcf0952b7a6ca5",
@@ -65,7 +67,7 @@
"tableRows": "906d2413b13d76a06d5910885e47ed5c544be4ff3a2266e83146715721b24270",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
- "latest": 256,
+ "latest": 257,
"records": [
{
"handler": {
@@ -4004,6 +4006,28 @@
"transaction": false,
"verify": "absent",
"version": 256
+ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [
+ "buildOriginIndexIfClean",
+ "migrationNotice",
+ "originTwinsRepairCommand",
+ "quietMigrationNotices"
+ ],
+ "sha256": "9a476af6261b0466bcee14b083411ddd376cacf124d8bcbc2648077e62a8944e"
+ },
+ "idempotent": true,
+ "name": "pages_live_origin_key",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": "absent",
+ "transaction": false,
+ "verify": "absent",
+ "version": 257
}
],
"versions": [
@@ -4257,7 +4281,8 @@
253,
254,
255,
- 256
+ 256,
+ 257
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 7707b1bf2d..2962918637 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -1288,6 +1288,7 @@
"pages_file_uri_name_idx": "CREATE INDEX pages_file_uri_name_idx ON public.pages USING btree (source_id, regexp_replace(source_uri, '^.*/'::text, ''::text)) WHERE (source_uri ~~ 'file:%'::text)",
"pages_generation_idx": "CREATE INDEX pages_generation_idx ON public.pages USING btree (generation)",
"pages_links_extracted_at_idx": "CREATE INDEX pages_links_extracted_at_idx ON public.pages USING btree (source_id, links_extracted_at)",
+ "pages_live_origin_key": "CREATE UNIQUE INDEX pages_live_origin_key ON public.pages USING btree (source_id, source_path) WHERE ((deleted_at IS NULL) AND (source_path IS NOT NULL))",
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
diff --git a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json
index 4555248730..fb9efe46b5 100644
--- a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json
+++ b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json
@@ -282,15 +282,15 @@
"purgeDeletedPages#dryRun": {},
"putContradictionCacheEntry#default": {},
"putPage#blankBody": {
- "raw": 4,
+ "raw": 5,
"tx": 1
},
"putPage#default": {
- "raw": 4,
+ "raw": 5,
"tx": 1
},
"putPage#expectedRevision": {
- "raw": 4,
+ "raw": 5,
"tx": 1
},
"readEmbeddingStateCounts#full": {
@@ -335,8 +335,14 @@
"resolveSlugs#sourceIds": {},
"resolveSlugsByPaths#default": {},
"resolveTake#default": {},
- "restorePage#default": {},
- "restorePage#sourceId": {},
+ "restorePage#default": {
+ "raw": 1,
+ "tx": 1
+ },
+ "restorePage#sourceId": {
+ "raw": 1,
+ "tx": 1
+ },
"revertToVersion#default": {},
"revertToVersion#sourceId": {},
"searchKeyword#cjk": {
diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.json
index 2bdea97749..c4452a8752 100644
--- a/test/fixtures/goldens/rls-scope-inventory.json
+++ b/test/fixtures/goldens/rls-scope-inventory.json
@@ -2851,23 +2851,23 @@
},
"restorePage#default": {
"flagOffLanes": [
- "pool"
+ "tx"
],
- "flagOffOpensTransaction": false,
+ "flagOffOpensTransaction": true,
"flagOn": "unscoped",
"flagOnLanes": [
- "pool"
+ "tx"
],
"flagOnScopes": []
},
"restorePage#sourceId": {
"flagOffLanes": [
- "pool"
+ "tx"
],
- "flagOffOpensTransaction": false,
+ "flagOffOpensTransaction": true,
"flagOn": "unscoped",
"flagOnLanes": [
- "pool"
+ "tx"
],
"flagOnScopes": []
},
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 8b691c4c2a..5c72194657 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -3615,6 +3615,15 @@
},
"via": "unsafe"
},
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
{
"paramCount": 18,
"unsafeOptions": {
@@ -3662,6 +3671,15 @@
},
"via": "unsafe"
},
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
{
"paramCount": 18,
"unsafeOptions": {
@@ -3717,6 +3735,15 @@
},
"via": "unsafe"
},
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
{
"paramCount": 18,
"unsafeOptions": {
@@ -3920,6 +3947,15 @@
},
"restorePage": {
"default": [
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
{
"paramCount": 1,
"unsafeOptions": {
@@ -3931,6 +3967,15 @@
}
],
"sourceId": [
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
{
"paramCount": 2,
"unsafeOptions": {
diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json
index 32d7168dc8..b7a6397fc3 100644
--- a/test/fixtures/goldens/sql-text/pages.json
+++ b/test/fixtures/goldens/sql-text/pages.json
@@ -849,6 +849,15 @@
"sql": "SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE",
"textSha256": "6c2eb61492fe7470a32169e89b9f04d471f3311d55ff790ad08f4736af483a2c"
},
+ {
+ "lane": "tx",
+ "params": [
+ "string",
+ "string"
+ ],
+ "sql": "SELECT id, slug, source_path, deleted_at FROM pages WHERE source_id=$1 AND slug=$2",
+ "textSha256": "13e0824db40fa0938c1e53873667c76000adde55a7fa159fce8e1a5969bf1bb0"
+ },
{
"lane": "tx",
"params": [
@@ -880,8 +889,8 @@
"null",
"null"
],
- "sql": "INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now(), $10, $11, $12, $13::smallint, $14, $15, $16, $17, $18) ON CONFLICT (source_id, slug) DO UPDATE SET type = EXCLUDED.type, page_kind = EXCLUDED.page_kind, title = EXCLUDED.title, compiled_truth = EXCLUDED.compiled_truth, timeline = EXCLUDED.timeline, frontmatter = EXCLUDED.frontmatter, content_hash = EXCLUDED.content_hash, updated_at = now(), deleted_at = NULL, effective_date = COALESCE(EXCLUDED.effective_date, pages.effective_date), effective_date_source = COALESCE(EXCLUDED.effective_date_source, pages.effective_date_source), import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename), chunker_version = CASE WHEN pages.compiled_truth IS NOT DISTINCT FROM EXCLUDED.compiled_truth AND pages.timeline IS NOT DISTINCT FROM EXCLUDED.timeline THEN pages.chunker_version WHEN pages.chunker_version < 0 OR (CASE WHEN pages.body_storage = 'segmented' THEN pages.body_flags->>'has_protected' IS DISTINCT FROM 'false' ELSE (COALESCE(pages.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(pages.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->') END) OR COALESCE(EXCLUDED.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(EXCLUDED.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' THEN -1 ELSE LEAST(COALESCE(pages.chunker_version, 0), 3) END, source_path = COALESCE(EXCLUDED.source_path, pages.source_path), database_only_reason = CASE WHEN EXCLUDED.source_path IS NOT NULL AND pages.database_only_reason = 'detached' THEN NULL ELSE pages.database_only_reason END, source_kind = COALESCE(EXCLUDED.source_kind, pages.source_kind), source_uri = COALESCE(EXCLUDED.source_uri, pages.source_uri), ingested_via = COALESCE(EXCLUDED.ingested_via, pages.ingested_via), ingested_at = COALESCE(EXCLUDED.ingested_at, pages.ingested_at) RETURNING knowledge_revision, text_projection_revision, id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at",
- "textSha256": "c324c562921a1025b756c95252af6dc0adec5df49b286e4be407de3a96b15242"
+ "sql": "INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now(), $10, $11, $12, $13::smallint, $14, $15, $16, $17, $18) ON CONFLICT (source_id, slug) DO UPDATE SET type = EXCLUDED.type, page_kind = EXCLUDED.page_kind, title = EXCLUDED.title, compiled_truth = EXCLUDED.compiled_truth, timeline = EXCLUDED.timeline, frontmatter = EXCLUDED.frontmatter, content_hash = EXCLUDED.content_hash, updated_at = now(), deleted_at = NULL, effective_date = COALESCE(EXCLUDED.effective_date, pages.effective_date), effective_date_source = COALESCE(EXCLUDED.effective_date_source, pages.effective_date_source), import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename), chunker_version = CASE WHEN pages.compiled_truth IS NOT DISTINCT FROM EXCLUDED.compiled_truth AND pages.timeline IS NOT DISTINCT FROM EXCLUDED.timeline THEN pages.chunker_version WHEN pages.chunker_version < 0 OR (CASE WHEN pages.body_storage = 'segmented' THEN pages.body_flags->>'has_protected' IS DISTINCT FROM 'false' ELSE (COALESCE(pages.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(pages.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->') END) OR COALESCE(EXCLUDED.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(EXCLUDED.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' THEN -1 ELSE LEAST(COALESCE(pages.chunker_version, 0), 3) END, source_path = COALESCE(EXCLUDED.source_path, pages.source_path), database_only_reason = CASE WHEN EXCLUDED.source_path IS NOT NULL AND pages.database_only_reason IN ('detached', 'origin_twin') THEN NULL ELSE pages.database_only_reason END, source_kind = COALESCE(EXCLUDED.source_kind, pages.source_kind), source_uri = COALESCE(EXCLUDED.source_uri, pages.source_uri), ingested_via = COALESCE(EXCLUDED.ingested_via, pages.ingested_via), ingested_at = COALESCE(EXCLUDED.ingested_at, pages.ingested_at) RETURNING knowledge_revision, text_projection_revision, id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at",
+ "textSha256": "abe31a1d94feb3381dd47ed9184d401c99487afe2787905d9ff2f1a373fed95c"
},
{
"event": "commit",
@@ -928,6 +937,15 @@
"sql": "SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE",
"textSha256": "6c2eb61492fe7470a32169e89b9f04d471f3311d55ff790ad08f4736af483a2c"
},
+ {
+ "lane": "tx",
+ "params": [
+ "string",
+ "string"
+ ],
+ "sql": "SELECT id, slug, source_path, deleted_at FROM pages WHERE source_id=$1 AND slug=$2",
+ "textSha256": "13e0824db40fa0938c1e53873667c76000adde55a7fa159fce8e1a5969bf1bb0"
+ },
{
"lane": "tx",
"params": [
@@ -950,8 +968,8 @@
"null",
"null"
],
- "sql": "INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now(), $10, $11, $12, $13::smallint, $14, $15, $16, $17, $18) ON CONFLICT (source_id, slug) DO UPDATE SET type = EXCLUDED.type, page_kind = EXCLUDED.page_kind, title = EXCLUDED.title, compiled_truth = EXCLUDED.compiled_truth, timeline = EXCLUDED.timeline, frontmatter = EXCLUDED.frontmatter, content_hash = EXCLUDED.content_hash, updated_at = now(), deleted_at = NULL, effective_date = COALESCE(EXCLUDED.effective_date, pages.effective_date), effective_date_source = COALESCE(EXCLUDED.effective_date_source, pages.effective_date_source), import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename), chunker_version = CASE WHEN pages.compiled_truth IS NOT DISTINCT FROM EXCLUDED.compiled_truth AND pages.timeline IS NOT DISTINCT FROM EXCLUDED.timeline THEN pages.chunker_version WHEN pages.chunker_version < 0 OR (CASE WHEN pages.body_storage = 'segmented' THEN pages.body_flags->>'has_protected' IS DISTINCT FROM 'false' ELSE (COALESCE(pages.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(pages.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->') END) OR COALESCE(EXCLUDED.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(EXCLUDED.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' THEN -1 ELSE LEAST(COALESCE(pages.chunker_version, 0), 3) END, source_path = COALESCE(EXCLUDED.source_path, pages.source_path), database_only_reason = CASE WHEN EXCLUDED.source_path IS NOT NULL AND pages.database_only_reason = 'detached' THEN NULL ELSE pages.database_only_reason END, source_kind = COALESCE(EXCLUDED.source_kind, pages.source_kind), source_uri = COALESCE(EXCLUDED.source_uri, pages.source_uri), ingested_via = COALESCE(EXCLUDED.ingested_via, pages.ingested_via), ingested_at = COALESCE(EXCLUDED.ingested_at, pages.ingested_at) RETURNING knowledge_revision, text_projection_revision, id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at",
- "textSha256": "c324c562921a1025b756c95252af6dc0adec5df49b286e4be407de3a96b15242"
+ "sql": "INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now(), $10, $11, $12, $13::smallint, $14, $15, $16, $17, $18) ON CONFLICT (source_id, slug) DO UPDATE SET type = EXCLUDED.type, page_kind = EXCLUDED.page_kind, title = EXCLUDED.title, compiled_truth = EXCLUDED.compiled_truth, timeline = EXCLUDED.timeline, frontmatter = EXCLUDED.frontmatter, content_hash = EXCLUDED.content_hash, updated_at = now(), deleted_at = NULL, effective_date = COALESCE(EXCLUDED.effective_date, pages.effective_date), effective_date_source = COALESCE(EXCLUDED.effective_date_source, pages.effective_date_source), import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename), chunker_version = CASE WHEN pages.compiled_truth IS NOT DISTINCT FROM EXCLUDED.compiled_truth AND pages.timeline IS NOT DISTINCT FROM EXCLUDED.timeline THEN pages.chunker_version WHEN pages.chunker_version < 0 OR (CASE WHEN pages.body_storage = 'segmented' THEN pages.body_flags->>'has_protected' IS DISTINCT FROM 'false' ELSE (COALESCE(pages.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(pages.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->') END) OR COALESCE(EXCLUDED.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(EXCLUDED.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' THEN -1 ELSE LEAST(COALESCE(pages.chunker_version, 0), 3) END, source_path = COALESCE(EXCLUDED.source_path, pages.source_path), database_only_reason = CASE WHEN EXCLUDED.source_path IS NOT NULL AND pages.database_only_reason IN ('detached', 'origin_twin') THEN NULL ELSE pages.database_only_reason END, source_kind = COALESCE(EXCLUDED.source_kind, pages.source_kind), source_uri = COALESCE(EXCLUDED.source_uri, pages.source_uri), ingested_via = COALESCE(EXCLUDED.ingested_via, pages.ingested_via), ingested_at = COALESCE(EXCLUDED.ingested_at, pages.ingested_at) RETURNING knowledge_revision, text_projection_revision, id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at",
+ "textSha256": "abe31a1d94feb3381dd47ed9184d401c99487afe2787905d9ff2f1a373fed95c"
},
{
"event": "commit",
@@ -1009,6 +1027,15 @@
"sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, wd.snapshot_withdrawals, wd.snapshot_global_purges, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_body, CASE WHEN wd.snapshot_withdrawals <> '[]'::jsonb OR (wd.snapshot_global_purges->>'count')::int > 0 THEN (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) END AS fingerprint_timeline FROM chosen p CROSS JOIN LATERAL (SELECT COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) || COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',x.visibility,'fact_hash',x.fact_hash,'withdrawn_at',x.purged_at,'purged',true) ORDER BY x.visibility,x.fact_hash) FROM (SELECT visibility,fact_hash,min(purged_at) AS purged_at FROM fact_purges WHERE source_id=p.source_id AND subject=p.slug GROUP BY visibility,fact_hash) x), '[]'::jsonb) AS snapshot_withdrawals, (SELECT jsonb_build_object('count',count(*),'latest',max(g.purged_at)) FROM fact_purges g WHERE g.source_id=p.source_id AND g.subject='*' ) AS snapshot_global_purges) wd",
"textSha256": "d49abdfac0d474258cc62de6b765f6c2bd3d4dc6f1098394ab26b05e48e8bc1c"
},
+ {
+ "lane": "tx",
+ "params": [
+ "string",
+ "string"
+ ],
+ "sql": "SELECT id, slug, source_path, deleted_at FROM pages WHERE source_id=$1 AND slug=$2",
+ "textSha256": "13e0824db40fa0938c1e53873667c76000adde55a7fa159fce8e1a5969bf1bb0"
+ },
{
"lane": "tx",
"params": [
@@ -1031,8 +1058,8 @@
"null",
"null"
],
- "sql": "INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now(), $10, $11, $12, $13::smallint, $14, $15, $16, $17, $18) ON CONFLICT (source_id, slug) DO UPDATE SET type = EXCLUDED.type, page_kind = EXCLUDED.page_kind, title = EXCLUDED.title, compiled_truth = EXCLUDED.compiled_truth, timeline = EXCLUDED.timeline, frontmatter = EXCLUDED.frontmatter, content_hash = EXCLUDED.content_hash, updated_at = now(), deleted_at = NULL, effective_date = COALESCE(EXCLUDED.effective_date, pages.effective_date), effective_date_source = COALESCE(EXCLUDED.effective_date_source, pages.effective_date_source), import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename), chunker_version = CASE WHEN pages.compiled_truth IS NOT DISTINCT FROM EXCLUDED.compiled_truth AND pages.timeline IS NOT DISTINCT FROM EXCLUDED.timeline THEN pages.chunker_version WHEN pages.chunker_version < 0 OR (CASE WHEN pages.body_storage = 'segmented' THEN pages.body_flags->>'has_protected' IS DISTINCT FROM 'false' ELSE (COALESCE(pages.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(pages.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->') END) OR COALESCE(EXCLUDED.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(EXCLUDED.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' THEN -1 ELSE LEAST(COALESCE(pages.chunker_version, 0), 3) END, source_path = COALESCE(EXCLUDED.source_path, pages.source_path), database_only_reason = CASE WHEN EXCLUDED.source_path IS NOT NULL AND pages.database_only_reason = 'detached' THEN NULL ELSE pages.database_only_reason END, source_kind = COALESCE(EXCLUDED.source_kind, pages.source_kind), source_uri = COALESCE(EXCLUDED.source_uri, pages.source_uri), ingested_via = COALESCE(EXCLUDED.ingested_via, pages.ingested_via), ingested_at = COALESCE(EXCLUDED.ingested_at, pages.ingested_at) RETURNING knowledge_revision, text_projection_revision, id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at",
- "textSha256": "c324c562921a1025b756c95252af6dc0adec5df49b286e4be407de3a96b15242"
+ "sql": "INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now(), $10, $11, $12, $13::smallint, $14, $15, $16, $17, $18) ON CONFLICT (source_id, slug) DO UPDATE SET type = EXCLUDED.type, page_kind = EXCLUDED.page_kind, title = EXCLUDED.title, compiled_truth = EXCLUDED.compiled_truth, timeline = EXCLUDED.timeline, frontmatter = EXCLUDED.frontmatter, content_hash = EXCLUDED.content_hash, updated_at = now(), deleted_at = NULL, effective_date = COALESCE(EXCLUDED.effective_date, pages.effective_date), effective_date_source = COALESCE(EXCLUDED.effective_date_source, pages.effective_date_source), import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename), chunker_version = CASE WHEN pages.compiled_truth IS NOT DISTINCT FROM EXCLUDED.compiled_truth AND pages.timeline IS NOT DISTINCT FROM EXCLUDED.timeline THEN pages.chunker_version WHEN pages.chunker_version < 0 OR (CASE WHEN pages.body_storage = 'segmented' THEN pages.body_flags->>'has_protected' IS DISTINCT FROM 'false' ELSE (COALESCE(pages.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(pages.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->') END) OR COALESCE(EXCLUDED.compiled_truth, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' OR COALESCE(EXCLUDED.timeline, '') ~ '<!--- gbrain:(facts|takes):(begin|end) -->' THEN -1 ELSE LEAST(COALESCE(pages.chunker_version, 0), 3) END, source_path = COALESCE(EXCLUDED.source_path, pages.source_path), database_only_reason = CASE WHEN EXCLUDED.source_path IS NOT NULL AND pages.database_only_reason IN ('detached', 'origin_twin') THEN NULL ELSE pages.database_only_reason END, source_kind = COALESCE(EXCLUDED.source_kind, pages.source_kind), source_uri = COALESCE(EXCLUDED.source_uri, pages.source_uri), ingested_via = COALESCE(EXCLUDED.ingested_via, pages.ingested_via), ingested_at = COALESCE(EXCLUDED.ingested_at, pages.ingested_at) RETURNING knowledge_revision, text_projection_revision, id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at",
+ "textSha256": "abe31a1d94feb3381dd47ed9184d401c99487afe2787905d9ff2f1a373fed95c"
},
{
"event": "commit",
@@ -1246,31 +1273,67 @@
"array<string>",
"string"
],
- "sql": "SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2",
- "textSha256": "eb7db9ec7a9b853b93f4d475f715a6a72fd1ee4b48da9bbf9217deac299ebfff"
+ "sql": "SELECT slug, source_path, deleted_at IS NULL AS live FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2 ORDER BY source_path, slug",
+ "textSha256": "bee87a5adc9be889a362de92ea6380595113f9360e8c720aada24a4e9a3e44d5"
}
]
},
"restorePage": {
"default": [
{
- "lane": "pool",
+ "event": "begin",
+ "lane": "tx"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "string",
+ "null",
+ "null"
+ ],
+ "sql": "SELECT id, source_id FROM pages WHERE slug=$1 AND deleted_at IS NOT NULL AND ($2::text IS NULL OR source_id=$3) ORDER BY source_id",
+ "textSha256": "8d4bea0f03c96cfdea2bad6a82c4050073b3cad615d0115bb66cf05aaa9f9300"
+ },
+ {
+ "lane": "tx",
"params": [
"string"
],
"sql": "UPDATE pages SET deleted_at = NULL, updated_at = now() WHERE slug = $1 AND deleted_at IS NOT NULL RETURNING slug",
"textSha256": "e657e4a81c518ed0669a4f80ce47e3114b42aaa4aa13667cdc35bb516e4d37cd"
+ },
+ {
+ "event": "commit",
+ "lane": "tx"
}
],
"sourceId": [
{
- "lane": "pool",
+ "event": "begin",
+ "lane": "tx"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "string",
+ "string",
+ "string"
+ ],
+ "sql": "SELECT id, source_id FROM pages WHERE slug=$1 AND deleted_at IS NOT NULL AND ($2::text IS NULL OR source_id=$3) ORDER BY source_id",
+ "textSha256": "8d4bea0f03c96cfdea2bad6a82c4050073b3cad615d0115bb66cf05aaa9f9300"
+ },
+ {
+ "lane": "tx",
"params": [
"string",
"string"
],
"sql": "UPDATE pages SET deleted_at = NULL, updated_at = now() WHERE slug = $1 AND deleted_at IS NOT NULL AND source_id = $2 RETURNING slug",
"textSha256": "d36ab3e3d4968ce3e210fbbc3a1e9247e4d6065537b380001da3285a3dc6054b"
+ },
+ {
+ "event": "commit",
+ "lane": "tx"
}
]
},
diff --git a/test/fixtures/guards/check-origin-assignment.mjs/bad/fixture.ts b/test/fixtures/guards/check-origin-assignment.mjs/bad/fixture.ts
new file mode 100644
index 0000000000..a6bb13e471
--- /dev/null
+++ b/test/fixtures/guards/check-origin-assignment.mjs/bad/fixture.ts
@@ -0,0 +1,17 @@
+// BAD: a raw origin assignment, no guard.
+export async function assign(tx: any): Promise<void> {
+ await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', ['default', 'notes/note-example', 'notes/note-example.md']);
+}
+// BAD: an insert that carries an origin.
+export async function insert(tx: any): Promise<void> {
+ await tx.executeRaw(`INSERT INTO pages (source_id, slug, source_path) VALUES ($1, $2, $3)`, ['default', 'notes/note-example', 'notes/note-example.md']);
+}
+// BAD: an aliased multi-column SET that also assigns the origin.
+export async function aliased(tx: any): Promise<void> {
+ await tx.executeRaw(`UPDATE pages p SET title = $1,
+ source_path = COALESCE($2::text, p.source_path) WHERE p.id = $3`, ['T', 'notes/note-example.md', 1]);
+}
+// BAD: a slug rename that carries the page's origin to a new identity unguarded.
+export async function rename(tx: any): Promise<void> {
+ await tx.executeRaw('UPDATE pages SET slug = $1, updated_at = now() WHERE slug = $2 AND source_id = $3', ['notes/new-example', 'notes/note-example', 'default']);
+}
diff --git a/test/fixtures/guards/check-origin-assignment.mjs/good/fixture.ts b/test/fixtures/guards/check-origin-assignment.mjs/good/fixture.ts
new file mode 100644
index 0000000000..29e8b75122
--- /dev/null
+++ b/test/fixtures/guards/check-origin-assignment.mjs/good/fixture.ts
@@ -0,0 +1,30 @@
+// GOOD: a clear is not an assignment.
+export async function clear(tx: any): Promise<void> {
+ await tx.executeRaw('UPDATE pages SET source_path = NULL WHERE id = $1', [1]);
+}
+// GOOD: source_path only compared, never assigned.
+export async function compare(tx: any): Promise<void> {
+ await tx.executeRaw('UPDATE pages SET title=$1 WHERE source_id=$2 AND source_path=$3', ['T', 'default', 'notes/note-example.md']);
+}
+// GOOD: an insert without an origin.
+export async function insert(tx: any): Promise<void> {
+ await tx.executeRaw('INSERT INTO pages (source_id, slug) VALUES ($1, $2)', ['default', 'notes/note-example']);
+}
+// GOOD: a guarded site that keeps its SQL inline, marked.
+export async function guarded(tx: any, assertOriginUnclaimed: (tx: any) => Promise<void>): Promise<void> {
+ await assertOriginUnclaimed(tx);
+ // origin-guard-ok: assertOriginUnclaimed above, in the same transaction
+ await tx.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2', ['notes/note-example.md', 1]);
+}
+// GOOD: a marked rename (the origin guard ran in the same transaction).
+export async function rename(tx: any, assertOriginUnclaimed: (tx: any) => Promise<void>): Promise<void> {
+ await assertOriginUnclaimed(tx);
+ // origin-guard-ok: assertOriginUnclaimed (rebind) above
+ await tx.executeRaw('UPDATE pages SET slug = $1 WHERE slug = $2 AND source_id = $3', ['notes/new-example', 'notes/note-example', 'default']);
+}
+// GOOD: a slug only compared, never assigned.
+export async function seal(tx: any): Promise<void> {
+ await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE slug = $2', [1, 'notes/note-example']);
+}
+/** A doc comment naming UPDATE pages SET source_path = $1 is not a statement. */
+export const documented = true;
diff --git a/test/origin-guard-6948.test.ts b/test/origin-guard-6948.test.ts
new file mode 100644
index 0000000000..c37ebfeee1
--- /dev/null
+++ b/test/origin-guard-6948.test.ts
@@ -0,0 +1,399 @@
+/**
+ * #6948: duplicate-origin twins can no longer be written. Every write that makes
+ * a page a live claimant of an origin another live page of its source records
+ * (putPage, restorePage, write-through, put_page, importFile's origin refresh,
+ * a rename that binds its destination path, the segmented and repair binders
+ * through bindOrigin) refuses `page_identity_changed` / `origin_already_claimed`
+ * and writes nothing; a write that keeps its own origin keeps working while an
+ * unrelated twin exists; the legacy `<scope>/<origin>` spelling of a source-root
+ * source counts as the same origin; readers and repairs pick the canonical page
+ * (the slug the file derives) and refuse `origin_conflict` when none is.
+ * Postgres adds the races: concurrent assignments serialize on the origin lock
+ * (two spellings included), and once `pages_live_origin_key` exists a raced
+ * insert's 23505 maps to the same refusal and is never read as a slug collision.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { dropOriginIndex } from './helpers/origin-index.ts';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { writePageThrough, _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
+import { resolveSlugsForRemovedPaths } from '../src/core/sync-git.ts';
+import { readFenceTarget, type FenceSource } from '../src/core/fence-repair/repair-io.ts';
+import { prepareDriftPage } from '../src/core/repair/file-drift.ts';
+import { isUniqueViolation, renamePageOntoSlug } from '../src/commands/sync/rename-collision.ts';
+import { resolveRepairScope } from '../src/core/repair/core.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import type { FrontmatterPreviewDetails } from '../src/core/repair/frontmatter.ts';
+import * as guard from '../src/core/persistence/origin-guard.ts';
+
+const backends = testBackends();
+const home = mkdtempSync(join(tmpdir(), 'gbrain-origin-guard-6948-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const engines: Array<[string, BrainEngine]> = [];
+let engine: PGLiteEngine;
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ engines.push(['pglite', engine]);
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(['postgres', pg.engine]);
+ closePostgres = pg.close;
+ }
+ // The guard is what protects a brain whose pages_live_origin_key index is pending (it holds legacy twins); the
+ // unique-index cases build the index themselves.
+ for (const [, e] of engines) await dropOriginIndex(e);
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ _resetWriteThroughCacheForTest();
+});
+
+const NOTE = 'notes/note-example.md';
+const quiet = { info() {}, warn() {}, error() {} };
+
+async function source(e: BrainEngine, localPath: string | null = null, config: Record<string, unknown> = {}): Promise<string> {
+ const id = `og-${randomUUID().slice(0, 8)}`;
+ await e.executeRaw('INSERT INTO sources (id, name, local_path, config) VALUES ($1, $1, $2, $3::text::jsonb)', [id, localPath, JSON.stringify(config)]);
+ return id;
+}
+
+/** A page row as an older writer left it (raw SQL: the guard is what these tests are about). */
+async function row(e: BrainEngine, sourceId: string, slug: string, sourcePath: string | null, deleted = false): Promise<number> {
+ const [r] = await e.executeRaw<{ id: number }>(`INSERT INTO pages (source_id, slug, type, title, compiled_truth, source_path, deleted_at)
+ VALUES ($1, $2, 'note', $2, $3, $4, CASE WHEN $5::boolean THEN now() END) RETURNING id`, [sourceId, slug, `Body of ${slug}.`, sourcePath, deleted]);
+ return Number(r!.id);
+}
+
+async function pages(e: BrainEngine, sourceId: string) {
+ return e.executeRaw<{ slug: string; source_path: string | null; live: boolean }>(
+ 'SELECT slug, source_path, deleted_at IS NULL AS live FROM pages WHERE source_id = $1 ORDER BY slug', [sourceId]);
+}
+
+async function liveClaimants(e: BrainEngine, sourceId: string, sourcePath: string): Promise<string[]> {
+ return (await e.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id = $1 AND source_path = $2 AND deleted_at IS NULL ORDER BY slug',
+ [sourceId, sourcePath])).map(r => r.slug);
+}
+
+async function refusal(run: () => Promise<unknown>): Promise<Error & { code?: string; detail?: string }> {
+ try { await run(); } catch (error) { return error as Error & { code?: string; detail?: string }; }
+ throw new Error('expected the write to be refused, but it succeeded');
+}
+
+const claimed = { code: 'page_identity_changed', detail: 'origin_already_claimed' };
+
+/** The issue's shape: a legacy page with no origin, and the live canonical page that records the file. */
+async function issueShape(e: BrainEngine, localPath: string | null = null) {
+ const sourceId = await source(e, localPath);
+ await row(e, sourceId, 'notes/note-example', NOTE);
+ await row(e, sourceId, 'ideas/note-example', null);
+ return sourceId;
+}
+
+function each(name: string, run: (e: BrainEngine) => Promise<void>, timeout = 60_000) {
+ for (const [backend] of [['pglite'], ...(backends.includes('postgres') ? [['postgres']] : [])]) {
+ test(`${name} (${backend})`, async () => {
+ const e = engines.find(([b]) => b === backend)![1];
+ await withEnv(env, () => run(e));
+ }, timeout);
+ }
+}
+
+describe('writers refuse a second live claimant of an origin', () => {
+ each('putPage giving the legacy page the held origin refuses and leaves it without one', async e => {
+ const sourceId = await issueShape(e);
+ const error = await refusal(() => e.putPage('ideas/note-example', { type: 'note', title: 'Idea', compiled_truth: 'Moved.', source_path: NOTE }, { sourceId }));
+ expect(error).toMatchObject(claimed);
+ expect(error.message).toContain(NOTE);
+ expect(await liveClaimants(e, sourceId, NOTE)).toEqual(['notes/note-example']);
+ expect((await e.getPage('ideas/note-example', { sourceId }))?.compiled_truth).toBe('Body of ideas/note-example.');
+ });
+
+ each('putPage inserting a new page with the held origin refuses and inserts nothing', async e => {
+ const sourceId = await issueShape(e);
+ expect(await refusal(() => e.putPage('fresh/note-example', { type: 'note', title: 'Fresh', compiled_truth: 'New.', source_path: NOTE }, { sourceId }))).toMatchObject(claimed);
+ expect(await e.getPage('fresh/note-example', { sourceId })).toBeNull();
+ });
+
+ each('a write that keeps its own origin works while an unrelated twin exists', async e => {
+ const sourceId = await issueShape(e);
+ await row(e, sourceId, 'other/twin-a', 'other/twin.md');
+ await row(e, sourceId, 'other/twin-b', 'other/twin.md');
+ await e.putPage('notes/note-example', { type: 'note', title: 'Kept', compiled_truth: 'Rewritten.', source_path: NOTE }, { sourceId });
+ await e.putPage('other/twin-a', { type: 'note', title: 'Twin', compiled_truth: 'Still its own origin.' }, { sourceId });
+ expect((await e.getPage('notes/note-example', { sourceId }))?.compiled_truth).toBe('Rewritten.');
+ expect(await liveClaimants(e, sourceId, 'other/twin.md')).toEqual(['other/twin-a', 'other/twin-b']);
+ });
+
+ each('putPage reviving a tombstone whose origin another live page now holds refuses and keeps it deleted', async e => {
+ const sourceId = await issueShape(e);
+ await row(e, sourceId, 'old/note-example', NOTE, true);
+ expect(await refusal(() => e.putPage('old/note-example', { type: 'note', title: 'Back', compiled_truth: 'Revived.' }, { sourceId }))).toMatchObject(claimed);
+ expect((await pages(e, sourceId)).find(p => p.slug === 'old/note-example')).toMatchObject({ live: false });
+ });
+
+ each('restorePage of a tombstone whose origin another live page now holds refuses', async e => {
+ const sourceId = await issueShape(e);
+ await row(e, sourceId, 'old/note-example', NOTE, true);
+ expect(await refusal(() => e.restorePage('old/note-example', { sourceId }))).toMatchObject(claimed);
+ expect(await liveClaimants(e, sourceId, NOTE)).toEqual(['notes/note-example']);
+ });
+
+ each('write-through (write-through.ts) binding a held slug path refuses before the file is written', async e => {
+ const root = mkdtempSync(join(home, 'wt-'));
+ const sourceId = await source(e, root);
+ await row(e, sourceId, 'ideas/note-example', null);
+ await row(e, sourceId, 'ideas/note-example-old', 'ideas/note-example.md');
+ const result = await writePageThrough(e, 'ideas/note-example', { sourceId });
+ expect(result.written).toBe(false);
+ expect(result.error).toContain('ideas/note-example.md');
+ expect(existsSync(join(root, 'ideas', 'note-example.md'))).toBe(false);
+ expect(await liveClaimants(e, sourceId, 'ideas/note-example.md')).toEqual(['ideas/note-example-old']);
+ });
+
+ test('put_page (page-prepare.ts write-through binding, classic PGLite brain) refuses a page whose file another page records', () => withEnv(env, async () => {
+ const e = engine;
+ const root = mkdtempSync(join(home, 'put-'));
+ const sourceId = await source(e, root);
+ await row(e, sourceId, 'notes/note-example-old', NOTE);
+ const ctx: OperationContext = { engine: e, config: { engine: e.kind } as never, logger: quiet, dryRun: false, remote: false, sourceId };
+ const put = operations.find(o => o.name === 'put_page')!;
+ const error = await refusal(() => put.handler(ctx, { slug: 'notes/note-example', content: '---\ntitle: Note\ntype: note\n---\n\nA synthetic note.\n' }));
+ expect(error).toMatchObject({ code: 'page_identity_changed', message: expect.stringContaining(`already records "${NOTE}"`) });
+ expect(await e.getPage('notes/note-example', { sourceId })).toBeNull();
+ expect(existsSync(join(root, NOTE))).toBe(false);
+ expect(await liveClaimants(e, sourceId, NOTE)).toEqual(['notes/note-example-old']);
+ }), 60_000);
+
+ each('importFile\'s origin refresh (import-file.ts) logs the refusal and records no origin', async e => {
+ const sourceId = await source(e);
+ const content = '---\ntitle: Idea\ntype: note\n---\n\nA synthetic idea.\n';
+ await importFromContent(e, 'ideas/note-example', content, { sourceId, noEmbed: true });
+ await row(e, sourceId, 'notes/note-example', NOTE);
+ const logged: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ process.stderr.write = ((chunk: string | Uint8Array) => { logged.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ try { await importFromContent(e, 'ideas/note-example', content, { sourceId, noEmbed: true, sourcePath: NOTE }); } finally { process.stderr.write = write; }
+ expect((await e.getPage('ideas/note-example', { sourceId }))?.source_path ?? null).toBeNull();
+ expect(await liveClaimants(e, sourceId, NOTE)).toEqual(['notes/note-example']);
+ expect(logged.join('')).toContain(`origin ${NOTE} not recorded`);
+ });
+
+ each('a sync rename (rename-collision.ts) whose destination path another page records refuses the bind and the move', async e => {
+ const sourceId = await issueShape(e);
+ await row(e, sourceId, 'drafts/note-example', 'drafts/note-example.md');
+ const error = await refusal(() => renamePageOntoSlug(e, { sourceId, oldSlug: 'drafts/note-example', newSlug: 'ideas/renamed', to: NOTE }));
+ expect(error).toMatchObject(claimed);
+ expect(isUniqueViolation(error)).toBe(false);
+ expect(await liveClaimants(e, sourceId, NOTE)).toEqual(['notes/note-example']);
+ expect(await e.getPage('drafts/note-example', { sourceId })).not.toBeNull();
+ });
+
+ each('updateSlug keeps the page\'s own origin, so it never adds a claimant', async e => {
+ const sourceId = await issueShape(e);
+ expect(await e.updateSlug('notes/note-example', 'notes/renamed-example', { sourceId })).toBe(1);
+ expect(await liveClaimants(e, sourceId, NOTE)).toEqual(['notes/renamed-example']);
+ });
+
+ each('bindOrigin, the binder of the repair and sync publications, refuses and needs a transaction', async e => {
+ const sourceId = await issueShape(e);
+ expect(await refusal(() => e.transaction(tx => guard.bindOrigin(tx, { sourceId, slug: 'ideas/note-example', sourcePath: NOTE })))).toMatchObject(claimed);
+ expect(await refusal(() => guard.bindOrigin(e, { sourceId, slug: 'ideas/note-example', sourcePath: NOTE }))).toMatchObject({ message: expect.stringContaining('engine.transaction()') });
+ expect(await liveClaimants(e, sourceId, NOTE)).toEqual(['notes/note-example']);
+ });
+
+ each('bindOrigin clears an origin_twin database-only marker when the page records an origin again', async e => {
+ const sourceId = await issueShape(e);
+ await e.executeRaw("UPDATE pages SET database_only_reason='origin_twin' WHERE source_id=$1 AND slug='ideas/note-example'", [sourceId]);
+ expect(await e.transaction(tx => guard.bindOrigin(tx, { sourceId, slug: 'ideas/note-example', sourcePath: 'ideas/note-example.md' }))).toBe(1);
+ const [page] = await e.executeRaw<{ reason: string | null; source_path: string }>("SELECT database_only_reason AS reason, source_path FROM pages WHERE source_id=$1 AND slug='ideas/note-example'", [sourceId]);
+ expect(page).toEqual({ reason: null, source_path: 'ideas/note-example.md' });
+ });
+
+ each('the legacy <scope>/<origin> spelling of a scoped source-root source is the same origin', async e => {
+ const repo = mkdtempSync(join(home, 'repo-'));
+ mkdirSync(join(repo, '.git'));
+ mkdirSync(join(repo, 'sub'));
+ const sourceId = await source(e, join(repo, 'sub'), { slug_root_mode: 'source-root' });
+ await row(e, sourceId, 'note-example', 'sub/note-example.md');
+ const error = await refusal(() => e.putPage('ideas/note-example', { type: 'note', title: 'Idea', compiled_truth: 'x', source_path: 'note-example.md' }, { sourceId }));
+ expect(error).toMatchObject(claimed);
+ expect(error.message).toContain('note-example.md');
+ expect(await liveClaimants(e, sourceId, 'note-example.md')).toEqual([]);
+ });
+});
+
+describe('the unique index, when it exists', () => {
+ each('a 23505 on pages_live_origin_key maps to origin_already_claimed and is no slug collision', async e => {
+ const sourceId = await source(e);
+ await e.executeRaw('UPDATE pages SET deleted_at = now() WHERE deleted_at IS NULL AND source_path IS NOT NULL');
+ await e.executeRaw(`CREATE UNIQUE INDEX ${guard.ORIGIN_INDEX_NAME} ON pages (source_id, source_path) WHERE deleted_at IS NULL AND source_path IS NOT NULL`);
+ try {
+ await row(e, sourceId, 'notes/note-example', NOTE);
+ const raced = await refusal(() => row(e, sourceId, 'ideas/note-example', NOTE));
+ expect(String((raced as { code?: unknown }).code)).toBe('23505');
+ expect(guard.classifyOriginUniqueViolation(raced)).toMatchObject(claimed);
+ expect(isUniqueViolation(raced)).toBe(false);
+ const slugTaken = await refusal(() => row(e, sourceId, 'notes/note-example', null));
+ expect(isUniqueViolation(slugTaken)).toBe(true);
+ expect(guard.classifyOriginUniqueViolation(slugTaken)).toBeNull();
+ } finally {
+ await e.executeRaw(`DROP INDEX IF EXISTS ${guard.ORIGIN_INDEX_NAME}`);
+ }
+ });
+});
+
+describe('readers and repairs target the canonical page', () => {
+ each('canonicalOriginPage picks the slug the file derives, else reports the twins', async e => {
+ const sourceId = await source(e);
+ await row(e, sourceId, 'ideas/note-example', NOTE);
+ await row(e, sourceId, 'notes/note-example', NOTE);
+ await row(e, sourceId, 'a/twin', 'other/twin.md');
+ await row(e, sourceId, 'b/twin', 'other/twin.md');
+ expect(await guard.canonicalOriginPage(e, sourceId, NOTE)).toMatchObject({ slug: 'notes/note-example' });
+ expect(await guard.canonicalOriginPage(e, sourceId, 'other/twin.md')).toEqual({ ambiguous: ['a/twin', 'b/twin'] });
+ });
+
+ each('classic sync delete resolves a removed file to its canonical page and refuses ambiguous twins', async e => {
+ const sourceId = await source(e);
+ await row(e, sourceId, 'notes/note-example', NOTE);
+ await row(e, sourceId, 'ideas/note-example', NOTE);
+ await row(e, sourceId, 'a/twin', 'other/twin.md');
+ await row(e, sourceId, 'b/twin', 'other/twin.md');
+ const resolved = await resolveSlugsForRemovedPaths(e, [NOTE, 'other/twin.md'], sourceId);
+ expect(resolved.slugs.get(NOTE)).toBe('notes/note-example');
+ expect(resolved.slugs.has('other/twin.md')).toBe(false);
+ expect(resolved.refused).toEqual([expect.objectContaining({ path: 'other/twin.md', claimants: ['a/twin', 'b/twin'] })]);
+ });
+
+ each('fence repair reads the canonical page of a file twins record', async e => {
+ const root = mkdtempSync(join(home, 'fence-'));
+ mkdirSync(join(root, 'notes'));
+ writeFileSync(join(root, NOTE), '---\ntitle: Note\n---\nA synthetic note.\n');
+ writeFileSync(join(root, 'twin.md'), '---\ntitle: Twin\n---\nA synthetic twin.\n');
+ const sourceId = await source(e, root);
+ await row(e, sourceId, 'ideas/note-example', NOTE);
+ await row(e, sourceId, 'notes/note-example', NOTE);
+ await row(e, sourceId, 'a/twin', 'twin.md');
+ await row(e, sourceId, 'b/twin', 'twin.md');
+ const [{ incarnation }] = await e.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ const src: FenceSource = { id: sourceId, incarnation, managed: false, mirror: false, root, owner: null, busy: { paths: new Set(), slugs: new Set(), unknown: null } };
+ const read = await readFenceTarget(e, src, { key: `path:${NOTE}`, path: NOTE });
+ expect(read).toMatchObject({ ok: true, target: { slug: 'notes/note-example' } });
+ const twin = await readFenceTarget(e, src, { key: 'path:twin.md', path: 'twin.md' });
+ expect(twin).toMatchObject({ ok: false, reason: 'origin_conflict' });
+ });
+
+ each('frontmatter repair holds a file twins record with no canonical page as origin_conflict', async e => {
+ const root = mkdtempSync(join(home, 'fm-'));
+ mkdirSync(join(root, 'notes'));
+ writeFileSync(join(root, NOTE), '---\ntitle: Roundup\nauthor: alice-example (citing acme-example) (original: https://example.invalid/a)\n---\nA synthetic roundup.\n');
+ const sourceId = await source(e, root);
+ await row(e, sourceId, 'a/note-example', NOTE);
+ await row(e, sourceId, 'b/note-example', NOTE);
+ const runner = await repairRunner(e, { apply: false, noEmbed: true, logger: quiet });
+ const preview = await runner.run('frontmatter', await resolveRepairScope(e, sourceId), { explicit: true, sourceFlag: sourceId });
+ const details = preview.details as unknown as FrontmatterPreviewDetails;
+ expect(details.counts.safe).toBe(0);
+ expect(details.needs_review).toEqual([expect.objectContaining({ path: NOTE, code: 'origin_conflict' })]);
+ });
+
+ each('file-drift refuses to repair a twin that is not the canonical page of its file', async e => {
+ const sourceId = await source(e);
+ await row(e, sourceId, 'notes/note-example', NOTE);
+ await row(e, sourceId, 'ideas/note-example', NOTE);
+ expect(await refusal(() => prepareDriftPage(e, sourceId, 'ideas/note-example', 'file', new Date().toISOString())))
+ .toMatchObject({ code: 'page_identity_changed', detail: 'origin_conflict' });
+ });
+});
+
+describe('races (Postgres)', () => {
+ const pg = () => engines.find(([b]) => b === 'postgres')?.[1];
+ const run = backends.includes('postgres') ? test : test.skip;
+
+ /** Holds a putPage's transaction open until `release`; the second write starts while it is open. */
+ async function race(e: BrainEngine, sourceId: string, first: [string, string], second: [string, string]) {
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ let entered!: () => void;
+ const inside = new Promise<void>(resolve => { entered = resolve; });
+ const a = e.transaction(async tx => {
+ await tx.putPage(first[0], { type: 'note', title: 'A', compiled_truth: 'First.', source_path: first[1] }, { sourceId });
+ entered();
+ await gate;
+ });
+ await inside;
+ let settled = false;
+ const b = e.putPage(second[0], { type: 'note', title: 'B', compiled_truth: 'Second.', source_path: second[1] }, { sourceId }).finally(() => { settled = true; });
+ await Bun.sleep(300);
+ const blocked = !settled;
+ release();
+ return { blocked, results: await Promise.allSettled([a, b]) };
+ }
+
+ run('two concurrent assignments of one origin to different pages: exactly one commits', async () => {
+ const e = pg()!;
+ const sourceId = await source(e);
+ const { blocked, results } = await race(e, sourceId, ['ideas/note-example', NOTE], ['notes/note-example', NOTE]);
+ expect(blocked).toBe(true);
+ expect(results.map(r => r.status)).toEqual(['fulfilled', 'rejected']);
+ expect((results[1] as PromiseRejectedResult).reason).toMatchObject(claimed);
+ expect(await liveClaimants(e, sourceId, NOTE)).toEqual(['ideas/note-example']);
+ }, 60_000);
+
+ run('two spellings of one origin (legacy <scope>/<origin>) race onto one lock: exactly one commits', async () => {
+ const e = pg()!;
+ const repo = mkdtempSync(join(home, 'race-'));
+ mkdirSync(join(repo, '.git'));
+ mkdirSync(join(repo, 'sub'));
+ const sourceId = await source(e, join(repo, 'sub'), { slug_root_mode: 'source-root' });
+ const { blocked, results } = await race(e, sourceId, ['ideas/note-example', 'note-example.md'], ['note-example', 'sub/note-example.md']);
+ expect(blocked).toBe(true);
+ expect(results.map(r => r.status)).toEqual(['fulfilled', 'rejected']);
+ expect((results[1] as PromiseRejectedResult).reason).toMatchObject(claimed);
+ }, 60_000);
+
+ run('with the unique index, an insert raced by an unguarded writer maps its 23505 to origin_already_claimed', async () => {
+ const e = pg()!;
+ const sourceId = await source(e);
+ await e.executeRaw('UPDATE pages SET deleted_at = now() WHERE deleted_at IS NULL AND source_path IS NOT NULL');
+ await e.executeRaw(`CREATE UNIQUE INDEX ${guard.ORIGIN_INDEX_NAME} ON pages (source_id, source_path) WHERE deleted_at IS NULL AND source_path IS NOT NULL`);
+ try {
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ let entered!: () => void;
+ const inside = new Promise<void>(resolve => { entered = resolve; });
+ const unguarded = e.transaction(async tx => { await row(tx, sourceId, 'raw/note-example', NOTE); entered(); await gate; });
+ await inside;
+ const guarded = e.putPage('notes/note-example', { type: 'note', title: 'N', compiled_truth: 'Guarded.', source_path: NOTE }, { sourceId });
+ await Bun.sleep(300);
+ release();
+ const [first, second] = await Promise.allSettled([unguarded, guarded]);
+ expect(first.status).toBe('fulfilled');
+ expect(second.status).toBe('rejected');
+ expect((second as PromiseRejectedResult).reason).toMatchObject(claimed);
+ } finally {
+ await e.executeRaw(`DROP INDEX IF EXISTS ${guard.ORIGIN_INDEX_NAME}`);
+ }
+ }, 60_000);
+});
diff --git a/test/origin-twins-6948.test.ts b/test/origin-twins-6948.test.ts
index b3717da629..e9d971817e 100644
--- a/test/origin-twins-6948.test.ts
+++ b/test/origin-twins-6948.test.ts
@@ -82,8 +82,12 @@ for (const backend of testBackends()) describe(`[${backend}] #6948 mergeTwinInto
const write = <T>(fn: (tx: BrainEngine) => Promise<T>) => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => fn(tx), TEST_WRITE_ATTRIBUTION));
const id = async (slug: string) => Number((await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0]!.id);
async function put(slug: string, opts: { body?: string; sourcePath?: string | null; frontmatter?: Record<string, unknown> } = {}) {
- await write(tx => tx.putPage(slug, { type: 'note', title: slug, compiled_truth: opts.body ?? 'One shared body.', timeline: '', frontmatter: opts.frontmatter ?? {},
- content_hash: randomUUID(), ...(opts.sourcePath ? { source_path: opts.sourcePath } : {}) }, { sourceId }));
+ // Twins are legacy data: no writer records a held origin on a second page (#6948), so the origin is set directly.
+ await write(async tx => {
+ await tx.putPage(slug, { type: 'note', title: slug, compiled_truth: opts.body ?? 'One shared body.', timeline: '', frontmatter: opts.frontmatter ?? {},
+ content_hash: randomUUID() }, { sourceId });
+ if (opts.sourcePath) await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [sourceId, slug, opts.sourcePath]);
+ });
return id(slug);
}
/** A survivor and a twin recording one origin with one body, and a third page. */
diff --git a/test/page-prepare-shared-origin-6517.test.ts b/test/page-prepare-shared-origin-6517.test.ts
index 8575b14e95..ad2cfd878f 100644
--- a/test/page-prepare-shared-origin-6517.test.ts
+++ b/test/page-prepare-shared-origin-6517.test.ts
@@ -43,6 +43,7 @@ import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
+import { dropOriginIndex } from './helpers/origin-index.ts';
import { repairRunner } from '../src/core/repair/registry.ts';
import { resolveRepairScope } from '../src/core/repair/core.ts';
@@ -84,8 +85,12 @@ for (const backend of testBackends()) describe(`[${backend}] #6517 delete of a s
expect((await withEnv(env, () => performManagedSync(engine, opts))).status).toBe('first_sync');
expect((await page(id, names.file))?.source_path).toBe(`${names.file}.md`);
const sourcePath = twin === 'uri' ? null : twin === 'dot-path' ? `./${names.file}.md` : `${names.file}.md`;
- await engine.transaction(tx => withCoordinatedWrite(tx, [id], () => tx.putPage(names.twin, { type: 'note', title: 'Twin', compiled_truth: `A twin recording ${names.file}.`,
- timeline: '', frontmatter: {}, content_hash: `twin-${names.file}`, source_path: sourcePath, source_uri: twin === 'uri' ? pathToFileURL(file).href : null }, { sourceId: id }), TEST_WRITE_ATTRIBUTION));
+ // #6948: no writer records a held origin on a second page any more, so the twin's origin is set as legacy data left it.
+ await engine.transaction(tx => withCoordinatedWrite(tx, [id], async () => {
+ await tx.putPage(names.twin, { type: 'note', title: 'Twin', compiled_truth: `A twin recording ${names.file}.`,
+ timeline: '', frontmatter: {}, content_hash: `twin-${names.file}`, source_uri: twin === 'uri' ? pathToFileURL(file).href : null }, { sourceId: id });
+ if (sourcePath) await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [id, names.twin, sourcePath]);
+ }, TEST_WRITE_ATTRIBUTION));
return { id, root, file, bytes, opts, names };
}
const coordinated = (sourceId: string, sql: string, params: unknown[]) => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));
@@ -95,6 +100,8 @@ for (const backend of testBackends()) describe(`[${backend}] #6517 delete of a s
beforeAll(async () => {
if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }
+ // Shared origins exist only on brains written before #6948, whose pages_live_origin_key index is pending.
+ await dropOriginIndex(engine);
}, 120_000);
afterAll(async () => {
installFaultHook(undefined);
diff --git a/test/persistence-reconcile.test.ts b/test/persistence-reconcile.test.ts
index ca05b14d00..91ca6a033e 100644
--- a/test/persistence-reconcile.test.ts
+++ b/test/persistence-reconcile.test.ts
@@ -30,6 +30,7 @@ import { operationsByName } from '../src/core/operations.ts';
import { reconcileCanonical } from '../src/core/persistence/reconcile-merge.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { withEnv } from './helpers/with-env.ts';
+import { dropOriginIndex } from './helpers/origin-index.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
const home = mkdtempSync(join(tmpdir(), 'gbrain-reconcile-'));
@@ -38,6 +39,8 @@ let closePostgres: (() => Promise<void>) | undefined;
beforeAll(async () => {
const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine);
if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ // Several tests seed legacy shared origins, which only a brain whose pages_live_origin_key index is pending holds (#6948).
+ for (const engine of engines) await dropOriginIndex(engine);
}, 120_000);
afterAll(async () => {
await withEnv({ GBRAIN_HOME: home }, async () => {
@@ -568,7 +571,9 @@ test('historical basename origins in separate slug directories remain distinct c
await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => {
await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [f.id, f.slug, 'example.md']);
await tx.putPage(otherSlug, { type: 'note', title: 'Other example', compiled_truth: 'An independent historical basename page.',
- frontmatter: { independent: true }, source_path: 'example.md' }, { sourceId: f.id });
+ frontmatter: { independent: true } }, { sourceId: f.id });
+ // #6948: two pages recording one basename are legacy data no writer creates now.
+ await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [f.id, otherSlug, 'example.md']);
}, TEST_WRITE_ATTRIBUTION));
const other = (await engine.readPageSnapshot(otherSlug, { sourceId: f.id }))!;
writeFileSync(otherFile, serializePageToMarkdown(other.page, other.tags));
@@ -620,7 +625,9 @@ test('genuine shared-file origins through explicit paths or URI fallback still r
const sourcePath = origin === 'uri' ? null : origin === 'dot-path' ? './notes/example.md'
: origin === 'repeated-separators' ? 'notes//example.md' : 'notes/example.md';
await tx.putPage('other/collision', { type: 'note', title: 'Collision', compiled_truth: 'Another page claiming the same file.',
- frontmatter: {}, source_path: sourcePath, source_uri: origin === 'uri' ? uri : null }, { sourceId: f.id });
+ frontmatter: {}, source_uri: origin === 'uri' ? uri : null }, { sourceId: f.id });
+ // #6948: a second live claimant of a file is legacy data no writer creates now.
+ if (sourcePath) await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [f.id, 'other/collision', sourcePath]);
}, TEST_WRITE_ATTRIBUTION));
const snapshot = await engine.readPageSnapshot(f.slug, { sourceId: f.id });
await local(engine, f.registration, async () => {
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 48b964e4e7..4abf2dadae 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -208,6 +208,7 @@ test/managed-sync-stale-group-head.test.ts
test/migration-persistence-request-id-index.test.ts
test/migration-persistence-request-slug-index.test.ts
test/on-commit-embedding.serial.test.ts
+test/origin-guard-6948.test.ts
test/origin-twins-6948.test.ts
test/overwritten-edits-6712.test.ts
test/owner-refusal.test.ts
diff --git a/test/put-page-persistence.test.ts b/test/put-page-persistence.test.ts
index ed77ab51d5..7e32de4f2c 100644
--- a/test/put-page-persistence.test.ts
+++ b/test/put-page-persistence.test.ts
@@ -253,7 +253,7 @@ describe('put_page persistence boundary', () => {
const executeRaw = engine.executeRaw;
let rejected = false;
engine.executeRaw = function<T>(sql: string, params?: unknown[]): Promise<T[]> {
- if (sql.includes('SET source_path = $1')) {
+ if (/SET source_path ?= ?\$\d/.test(sql)) {
rejected = true;
throw new Error('fixture source-path write rejected');
}
diff --git a/test/sync-origin-live-wins-6517.test.ts b/test/sync-origin-live-wins-6517.test.ts
index 6efba5d15a..0769edfb34 100644
--- a/test/sync-origin-live-wins-6517.test.ts
+++ b/test/sync-origin-live-wins-6517.test.ts
@@ -56,7 +56,9 @@ for (const backend of testBackends()) describe(`[${backend}] #6517 assertSyncPag
for (const state of states) {
const slug = `origin-rule/${++n}`;
await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {
- await tx.putPage(slug, { type: 'note', title: slug, compiled_truth: `Page ${n}.`, timeline: '', frontmatter: {}, content_hash: `h-${n}`, source_path: origin }, { sourceId });
+ await tx.putPage(slug, { type: 'note', title: slug, compiled_truth: `Page ${n}.`, timeline: '', frontmatter: {}, content_hash: `h-${n}` }, { sourceId });
+ // #6948: a second live claimant only exists as legacy data now, so the origin is set directly.
+ await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [sourceId, slug, origin]);
if (state === 'gone') await tx.executeRaw('UPDATE pages SET deleted_at=now() WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
}, TEST_WRITE_ATTRIBUTION));
ids.push(Number((await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0]!.id));