Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge F1b attribution read surface into foundations-1

garrytan6cad517b991d
diff --cc docs/architecture/system-of-record.md
index 31cce8b398,d25a298a16..f9ab4a3b50
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@@ -145,116 -145,33 +145,141 @@@ appear file-backed
## Write attribution
-Journaled and coordinated writes stamp who wrote each row, in the database
-only (Markdown never carries it):
+Foundations 1 records creation attribution: who wrote each page revision,
+page version, fact, take and timeline row. It does not yet attribute every
+write. BEFORE ROW triggers copy three transaction-local settings into the row
+(`persistence/attribution-schema.ts`). `withCoordinatedWrite` sets them for
+journaled requests and coordinated maintenance, and `withWriteAttribution`
+(through `maintenanceTransaction`) sets them for unmanaged legacy transactions. A row written outside both
+scopes keeps `NULL` attribution, which reads as "unrecorded".
+
++The stamps live in the database only (Markdown never carries them):
+
+ | Table | Columns | Meaning |
+ | --- | --- | --- |
+ | `pages` | `revision_write_request_id`, `revision_principal_kind`, `revision_principal_id` | Who wrote the live revision. |
+ | `page_versions` | `write_*` and `archived_*` | Who wrote the snapshotted revision, and whose write archived it. |
+ | `facts`, `takes`, `timeline_entries` | `write_*` and `last_write_*`, `last_written_at` | Who created the row, and who last changed its content. |
+
+ Only the request id (`persistence_requests.id`) and the principal (kind, id)
+ are stored. Names, operations and times are joined at read time by
+ `get_write_attribution` (`gbrain attribution`), an `admin` operation; see
+ [write attribution](../mcp/ADMIN.md#write-attribution). `get_versions` returns
+ attribution only to trusted local and `admin` callers. A NULL request with a
+ principal is a maintenance write; all NULL is `unrecorded`: written before
-attribution existed or by a legacy writer that records none, so this is
-creation attribution for journaled and coordinated writes, not an audit of
-every write.
++attribution existed or by a writer listed under "unattributed" below, so this
++is creation attribution, not an audit of every write.
+
+ Nothing is inferred for older rows. `gbrain repair attribution-backfill` fills
+ only rows the write journal proves exactly (the page write whose recorded
+ result is that revision, the `remember` that inserted that fact) and leaves the
+ rest `unrecorded`. Attribution is not file-backed: rebuilding from Markdown
+ loses it, and `gbrain migrate --to` copies it verbatim only for facts (pages, takes
+ and timeline rows are re-created on the target and start `unrecorded`; version
+ history is not copied).
+
+- **Managed brains:** creation attribution is complete. The writer guard
+ refuses a canonical write outside `withCoordinatedWrite`, so a direct writer
+ below either enters a coordinated path or fails before it writes.
+- **Unmanaged brains:** journaled page, memory, take and timeline operations
+ carry their request. These legacy transactions carry the local maintenance
+ principal with `write_request_id` NULL: direct markdown, code and image
+ imports (every `importFromContent` caller without `prepare`), the
+ `extract_facts` page reconcile, `extract-takes` and the
+ `gbrain repair stale-atoms --apply` retirement. The maintenance principal is
+ the local CLI registration (`local_cli`), else this host's identity
+ (`application`, `host:<id>`), else `host:unregistered`: attribution never
+ creates an identity file. The direct writers listed under "unattributed"
+ below still write without an actor.
+
+Agents: treat `NULL` attribution on an unmanaged brain as "written by a legacy
+maintenance path", not as evidence of tampering. To get attribution for a
+writer on this list now, run the work on a managed brain or through a
+journaled operation. When you add a direct writer, run it in
+`maintenanceTransaction(engine, fn)` (`persistence/attribution.ts`) or route it
+through the coordinator, then update these lists with the count
+`test/write-attribution-legacy.test.ts` reports. The test compares both lists
+with a grep of `src` for direct page, version, fact, take and timeline writers
+outside the engine and schema layers. The number in parentheses is that grep's
+count for the file.
+
+Attributed (inside a request, a coordinated scope or `maintenanceTransaction`,
+or a physical projection that leaves attribution untouched):
+
+<!-- write-attribution-covered:start -->
+- `src/commands/migrate-engine.ts` (5): engine copy keeps the source rows' attribution values verbatim.
+- `src/core/cycle/extract-takes.ts` (2): coordinated per page on managed brains; the unmanaged batch upsert runs in `maintenanceTransaction`.
+- `src/core/embed-facts.ts` (1): embedding columns only (physical projection).
+- `src/core/embedding-dim-check.ts` (1): embedding columns only (physical projection).
+- `src/core/facts/relink-publish.ts` (2): `relink_facts` request preparer.
+- `src/core/facts/withdrawal.ts` (1): runs inside the `forget` request's coordinated write.
+- `src/core/page-state/materialize.ts` (1): coordinated maintenance.
+- `src/core/page-state/versions.ts` (1): `createVersion` itself; the caller's scope supplies the actor.
+- `src/core/persistence/atom-maintenance.ts` (1): request preparer.
+- `src/core/persistence/canonical-projections.ts` (7): fence projection inside the request's publication.
+- `src/core/persistence/connector-google-receipts.ts` (2): request preparer.
+- `src/core/persistence/connector-sync.ts` (2): connector publication inside `withCoordinatedWrite`.
+- `src/core/persistence/derived-facts.ts` (1): `withDerivedFactsWrite` (managed derived facts).
+- `src/core/persistence/facts-prepare.ts` (3): managed `extract_facts` request preparer.
+- `src/core/persistence/grandfather.ts` (2): request preparer.
+- `src/core/persistence/links-maintenance.ts` (1): coordinated maintenance.
+- `src/core/persistence/loop-fact-retirement.ts` (1): request preparer.
+- `src/core/persistence/memory-mutations.ts` (1): `forget` inside its request's coordinated write.
+- `src/core/persistence/memory-prepare.ts` (3): `remember` request preparer.
+- `src/core/persistence/page-prepare.ts` (6): page request preparer.
+- `src/core/persistence/prepared-maintenance.ts` (4): managed maintenance request preparer.
+- `src/core/persistence/semantic-pages.ts` (1): `add_timeline_entry` request preparer.
+- `src/core/persistence/sync-prepare.ts` (4): managed sync request preparer.
+- `src/core/persistence/takes-prepare.ts` (3): takes request preparer.
+- `src/core/repair/stale-atoms.ts` (3): a request on managed brains; the unmanaged retirement runs in `maintenanceTransaction`.
+<!-- write-attribution-covered:end -->
+
+Unattributed until Foundations 2 mutation attribution (on unmanaged brains
+these write with `NULL` attribution):
+
+<!-- write-attribution-unattributed:start -->
+- `src/commands/extract-conversation-facts.ts` (3): the conversation fact index calls the engine directly through `writeDerivedFacts`.
+- `src/commands/extract-timeline-db.ts` (2): `gbrain extract timeline --source db` batch insert.
+- `src/commands/extract.ts` (4): `gbrain extract` timeline walks (file, incremental, stale) and the per-entry fallback.
+- `src/commands/sync/renames.ts` (1): legacy sync rename (`updateSlug`).
+- `src/core/calibration/undo-wave.ts` (1): calibration wave undo of take resolutions.
+- `src/core/chronicle/extract-events.ts` (1): event page write.
+- `src/core/company-brain/profile.ts` (1): company-brain sync soft deletes.
+- `src/core/cycle/dream-provenance.ts` (1): dream provenance frontmatter stamp.
+- `src/core/cycle/drift.ts` (1): drift report page.
+- `src/core/cycle/extract-atoms-page-state.ts` (1): atom extraction frontmatter stamp.
+- `src/core/cycle/extract-atoms.ts` (1): soft delete of stale atoms.
+- `src/core/cycle/extract-facts.ts` (7): remaining site: expiry of fence facts whose page was soft-deleted. The page reconcile is attributed.
+- `src/core/cycle/grade-takes.ts` (1): take resolution.
+- `src/core/cycle/phantom-redirect.ts` (3): fact move, phantom page body refresh and soft delete.
+- `src/core/cycle/phases/consolidate.ts` (4): consolidation takes and fact updates.
+- `src/core/cycle/synthesize.ts` (1): synthesis summary page.
+- `src/core/enrichment-service.ts` (2): enrichment page and auto-timeline entry.
+- `src/core/extract-timeline-from-meetings.ts` (1): meeting timeline batch.
+- `src/core/extract/receipt-writer.ts` (1): extraction receipt page.
+- `src/core/facts/backstop.ts` (3): legacy DB-only fact fallbacks.
+- `src/core/facts/fence-write.ts` (2): markdown-first fence reconcile insert and page body refresh.
+- `src/core/facts/forget.ts` (4): legacy forget expiry and fence strike-through.
+- `src/core/facts/proposal-supersede.ts` (4): unmanaged `decide` proposal accept and undo (facts and page body).
+- `src/core/facts/write-single.ts` (2): legacy single-fact insert and supersession.
+- `src/core/import-file.ts` (11): remaining sites: the moved-file rename (`updateSlug`) and the #3694 legacy-hash re-stamp of an unchanged body. Direct import writes are attributed.
+- `src/core/minions/handlers/ingest-capture.ts` (1): capture ingest soft delete.
+- `src/core/ops/extraction.ts` (2): extraction review promote (frontmatter) and reject (soft delete).
+- `src/core/output/writer.ts` (4): synthesize-phase BrainWriter pages and timeline.
+- `src/core/page-state/rename-alias.ts` (2): fact slug rewrite on rename.
+- `src/core/repair/captured-facts.ts` (1): unmanaged captured-facts expiry.
+- `src/core/repair/extractor-facts.ts` (1): extractor-facts repair update.
+- `src/core/schema-pack/page-to-alias.ts` (1): page-to-alias conversion soft delete.
+- `src/core/schema-pack/page-to-link.ts` (1): page-to-link conversion soft delete.
+- `src/core/schema-pack/retype.ts` (1): schema-pack retype.
+- `src/core/schema-pack/sync.ts` (1): schema-pack type sync.
+- `src/core/sweep.ts` (1): sweep timeline batch.
+- `src/core/takes-write.ts` (7): legacy takes file helper mirror rows and resolutions.
+- `src/core/think/index.ts` (1): saved `think` result page.
+- `src/core/timeline-dedup-repair.ts` (1): timeline dedup repair.
+- `src/core/timeline-write-through.ts` (2): timeline write-through entry and page timeline.
+<!-- write-attribution-unattributed:end -->
+
## The privacy boundary
Private knowledge in a fence still lives in the markdown file. If the
diff --cc scripts/e2e-backend-matrix.txt
index dfbdbfed92,1ebfb23a26..1abb34aa7c
--- a/scripts/e2e-backend-matrix.txt
+++ b/scripts/e2e-backend-matrix.txt
@@@ -46,4 -46,4 +46,5 @@@ test/e2e/takes-scorecard-parity.test.t
test/e2e/evidence-delivery-parity.test.ts
test/e2e/apply-migrations-orchestration-lock.test.ts
test/e2e/postgres-poisoned-connection.test.ts
+test/e2e/write-attribution-postgres.test.ts
+ test/e2e/write-attribution-read-parity.test.ts
diff --cc scripts/module-size-limits.tsv
index 4fbb6c2af7,d362e00917..388e0c7d2f
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -17,9 -17,9 +17,9 @@@ src/core/cycle.ts 3200 ratchet +2 Syste
src/core/cycle/synthesize.ts 3297 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts)
src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)
src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
-src/core/import-file.ts 2232 ratchet +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)
+src/core/import-file.ts 2233 ratchet +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)
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 332 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)
+ src/core/operations.ts 333 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)
src/core/pglite-engine.ts 3117 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); 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)
src/core/postgres-engine.ts 3130 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)
src/core/search/hybrid.ts 1584 ratchet +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
diff --cc test/write-attribution-read.test.ts
index 0000000000,ee4d043ab6..064cabe0a1
mode 000000,100644..100644
--- a/test/write-attribution-read.test.ts
+++ b/test/write-attribution-read.test.ts
@@@ -1,0 -1,316 +1,313 @@@
+ /**
+ * Foundations 1, F1b (spec 2.6-2.8, tests 12-14): write attribution read
+ * exposure and the journal-proven backfill.
+ *
+ * Runs on PGLite, or on an isolated Postgres database when DATABASE_URL is set
+ * (`test/e2e/write-attribution-read-parity.test.ts`, which the E2E backend
+ * matrix also runs through transaction-mode PgBouncer).
+ *
+ * Lane F1a owns the attribution columns and triggers. Until it merges, the
+ * test-only helper adds the columns (no triggers), so these tests stamp
+ * attribution with plain SQL where F1a's triggers would.
+ */
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+ import { randomUUID } from 'node:crypto';
+ import type { BrainEngine } from '../src/core/engine.ts';
+ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+ import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+ import { OperationError } from '../src/core/ops/contract.ts';
+ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+ import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';
+ import { attributionBackfillRepair } from '../src/core/repair/attribution-backfill.ts';
+ import { copyMigrationFacts, copyMigrationSources } from '../src/commands/migrate-engine.ts';
+ import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
-import { ensureWriteAttributionColumns } from './helpers/write-attribution-columns.ts';
+
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const logger = { info() {}, warn() {}, error() {} };
+
+ beforeAll(async () => {
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engine = pg.engine; close = pg.close;
+ } else {
+ const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema();
+ engine = pglite; close = () => pglite.disconnect();
+ }
- await ensureWriteAttributionColumns(engine);
+ }, 120_000);
+
+ afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await close();
+ }, 60_000);
+
+ async function newSource(prefix: string): Promise<string> {
+ const id = `${prefix}-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [id]);
+ return id;
+ }
+
+ function local(sourceId: string): OperationContext {
+ return { engine, sourceId, remote: false, dryRun: false, config: { engine: engine.kind, embedding_disabled: true }, logger };
+ }
+
+ function remote(sourceId: string, scopes: string[]): OperationContext {
+ return { engine, sourceId, remote: true, transport: 'http', dryRun: false, config: { engine: engine.kind, embedding_disabled: true }, logger,
+ auth: { token: 'synthetic', clientId: 'client-example', scopes, sourceId } } as OperationContext;
+ }
+
+ const ATTRIBUTION_KEY = /write|archived|principal|written_by|archived_by/;
+
+ /**
+ * Make a source's rows look written before attribution existed. With lane
+ * F1a's stamping triggers present, journaled writes are attributed at write
+ * time and attribution is immutable once set, so only a trigger-bypassing
+ * session (test setup only) can recreate pre-attribution rows.
+ */
+ async function rawAttributionWrite(sql: string, params: unknown[]) {
+ await engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL session_replication_role = replica');
+ await tx.executeRaw(sql, params);
+ });
+ }
+
+ async function asPreAttributionRows(sourceId: string) {
+ await rawAttributionWrite(`UPDATE pages SET revision_write_request_id=NULL, revision_principal_kind=NULL, revision_principal_id=NULL
+ WHERE source_id=$1`, [sourceId]);
+ await rawAttributionWrite(`UPDATE page_versions SET write_request_id=NULL, write_principal_kind=NULL, write_principal_id=NULL,
+ archived_write_request_id=NULL, archived_principal_kind=NULL, archived_principal_id=NULL
+ WHERE page_id IN (SELECT id FROM pages WHERE source_id=$1)`, [sourceId]);
+ await rawAttributionWrite(`UPDATE facts SET write_request_id=NULL, write_principal_kind=NULL, write_principal_id=NULL,
+ last_write_request_id=NULL, last_write_principal_kind=NULL, last_write_principal_id=NULL, last_written_at=NULL
+ WHERE source_id=$1`, [sourceId]);
+ }
+
+ async function seedNames() {
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id, client_name) VALUES('client-example', 'agent-example') ON CONFLICT DO NOTHING`);
+ const [token] = await engine.executeRaw<{ id: string }>(
+ `INSERT INTO access_tokens(name, token_hash) VALUES('legacy-example', $1) RETURNING id::text AS id`, [`hash-${randomUUID()}`]);
+ return token.id;
+ }
+
+ describe('read exposure (spec 2.7, test 12)', () => {
+ let sourceA: string;
+ let sourceB: string;
+ let tokenId: string;
+ const requestA = randomUUID();
+ const requestB = randomUUID();
+
+ beforeAll(async () => {
+ sourceA = await newSource('attr-a'); sourceB = await newSource('attr-b');
+ tokenId = await seedNames();
+ for (const sourceId of [sourceA, sourceB]) {
+ await engine.putPage('notes/shared', { type: 'note', title: 'Shared', compiled_truth: 'First body.', frontmatter: { visibility: 'world' } }, { sourceId });
+ await engine.createVersion('notes/shared', { sourceId });
+ await engine.putPage('notes/shared', { type: 'note', title: 'Shared', compiled_truth: 'Second body.', frontmatter: { visibility: 'world' } }, { sourceId });
+ }
+ await engine.executeRaw(`UPDATE page_versions SET write_request_id=$1, write_principal_kind='oauth_client', write_principal_id='client-example',
+ archived_write_request_id=$2, archived_principal_kind='legacy_token', archived_principal_id=$3
+ WHERE page_id=(SELECT id FROM pages WHERE source_id=$4 AND slug='notes/shared')`, [requestA, requestB, tokenId, sourceA]);
+ await engine.executeRaw(`UPDATE pages SET revision_write_request_id=$1, revision_principal_kind='legacy_token', revision_principal_id=$2
+ WHERE source_id=$3 AND slug='notes/shared'`, [requestB, tokenId, sourceA]);
+ });
+
+ test('get_versions without admin returns no attribution fields; admin and trusted local callers get resolved writers', async () => {
+ const plain = await operationsByName.get_versions.handler(remote(sourceA, ['read', 'write']), { slug: 'notes/shared' }) as Record<string, unknown>[];
+ expect(plain).toHaveLength(1);
+ expect(Object.keys(plain[0]).filter(key => ATTRIBUTION_KEY.test(key))).toEqual([]);
+
+ for (const ctx of [remote(sourceA, ['admin']), local(sourceA)]) {
+ const [version] = await operationsByName.get_versions.handler(ctx, { slug: 'notes/shared' }) as Record<string, any>[];
+ expect(version.write_principal_id).toBeUndefined();
+ expect(version.written_by).toEqual({ request_id: requestA, operation: null, at: null, origin: 'request',
+ principal: { kind: 'oauth_client', id: 'client-example', name: 'agent-example' } });
+ expect(version.archived_by).toMatchObject({ request_id: requestB, origin: 'request',
+ principal: { kind: 'legacy_token', id: tokenId, name: 'legacy-example' } });
+ expect(version.archived_by.at).toBe(new Date(version.snapshot_at).toISOString());
+ }
+ });
+
+ test('a pre-attribution version reads as unrecorded', async () => {
+ const [version] = await operationsByName.get_versions.handler(local(sourceB), { slug: 'notes/shared' }) as Record<string, any>[];
+ expect(version.written_by).toEqual({ request_id: null, operation: null, principal: null, at: null, origin: 'unrecorded' });
+ expect(version.archived_by.origin).toBe('unrecorded');
+ });
+
+ test('get_write_attribution is an admin op and stays inside the caller grant', async () => {
+ const op = operationsByName.get_write_attribution;
+ expect(op.scope).toBe('admin');
+ expect(op.localOnly).toBe(false);
+ expect(op.cliHints?.name).toBe('attribution');
+
+ const inGrant = await op.handler(remote(sourceA, ['admin']), { slug: 'notes/shared', versions: true }) as Record<string, any>;
+ expect(inGrant.target).toMatchObject({ kind: 'page', slug: 'notes/shared', source_id: sourceA });
+ expect(inGrant.created.principal).toEqual({ kind: 'oauth_client', id: 'client-example', name: 'agent-example' });
+ expect(inGrant.last.principal).toEqual({ kind: 'legacy_token', id: tokenId, name: 'legacy-example' });
+ expect(inGrant.live_revision.written_by.request_id).toBe(requestB);
+ expect(inGrant.versions).toHaveLength(1);
+ expect(inGrant.versions[0].written_by.request_id).toBe(requestA);
+
+ const otherSource = await op.handler(remote(sourceB, ['admin']), { slug: 'notes/shared' }) as Record<string, any>;
+ expect(otherSource.target.source_id).toBe(sourceB);
+ expect(otherSource.created.origin).toBe('unrecorded');
+
+ const outside = { ...remote(sourceB, ['admin']), auth: { token: 't', clientId: 'client-example', scopes: ['admin'], sourceId: sourceB, allowedSources: [sourceB] } } as OperationContext;
+ const page = await engine.putPage('notes/only-a', { type: 'note', title: 'Only A', compiled_truth: 'A only.', frontmatter: { visibility: 'world' } }, { sourceId: sourceA });
+ expect(page.id).toBeGreaterThan(0);
+ await expect(op.handler(outside, { slug: 'notes/only-a' })).rejects.toMatchObject({ code: 'page_not_found' });
+ });
+
+ test('row targets: remote admins see world facts and allowed take holders only; local sees every row', async () => {
+ const op = operationsByName.get_write_attribution;
+ const [page] = await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE source_id=$1 AND slug='notes/shared'`, [sourceA]);
+ const facts = await engine.executeRaw<{ id: number; visibility: string }>(
+ `INSERT INTO facts(source_id, entity_slug, fact, visibility, source, write_request_id, write_principal_kind, write_principal_id,
+ last_write_principal_kind, last_write_principal_id, last_written_at)
+ VALUES ($1,'notes/shared','World fact.','world','test',$2,'oauth_client','client-example','local_cli','writer-example','2026-01-02T03:04:05Z'),
+ ($1,'notes/shared','Private fact.','private','test',NULL,NULL,NULL,NULL,NULL,NULL)
+ RETURNING id, visibility`, [sourceA, requestA]);
+ const world = facts.find(f => f.visibility === 'world')!.id;
+ const hidden = facts.find(f => f.visibility === 'private')!.id;
+
+ const fact = await op.handler(remote(sourceA, ['admin']), { slug: 'notes/shared', fact: world }) as Record<string, any>;
+ expect(fact.target).toMatchObject({ kind: 'fact', id: Number(world), slug: 'notes/shared', source_id: sourceA });
+ expect(fact.created).toMatchObject({ request_id: requestA, origin: 'request', principal: { kind: 'oauth_client', name: 'agent-example' } });
+ expect(fact.last).toEqual({ request_id: null, operation: null, at: '2026-01-02T03:04:05.000Z', origin: 'maintenance',
+ principal: { kind: 'local_cli', id: 'writer-example', name: null } });
+
+ await expect(op.handler(remote(sourceA, ['admin']), { slug: 'notes/shared', fact: hidden })).rejects.toMatchObject({ code: 'fact_not_found' });
+ const privateLocal = await op.handler(local(sourceA), { slug: 'notes/shared', fact: hidden }) as Record<string, any>;
+ expect(privateLocal.created.origin).toBe('unrecorded');
+
+ await engine.executeRaw(`INSERT INTO takes(page_id,row_num,claim,kind,holder,write_principal_kind,write_principal_id)
+ VALUES ($1,1,'World take.','take','world','application','host:example'),($1,2,'Owner take.','take','owner-example',NULL,NULL)`, [page.id]);
+ const take = await op.handler(remote(sourceA, ['admin']), { slug: 'notes/shared', take: 1 }) as Record<string, any>;
+ expect(take.target).toMatchObject({ kind: 'take', row_num: 1 });
+ expect(take.created).toMatchObject({ origin: 'maintenance', principal: { kind: 'application', id: 'host:example', name: null } });
+ await expect(op.handler(remote(sourceA, ['admin']), { slug: 'notes/shared', take: 2 })).rejects.toMatchObject({ code: 'not_found' });
+ expect((await op.handler(local(sourceA), { slug: 'notes/shared', take: 2 }) as Record<string, any>).target.row_num).toBe(2);
+
+ const [entry] = await engine.executeRaw<{ id: number }>(`INSERT INTO timeline_entries(page_id,date,summary,write_request_id,write_principal_kind,write_principal_id)
+ VALUES ($1,'2026-01-01','Met.',$2,'legacy_token',$3) RETURNING id`, [page.id, requestB, tokenId]);
+ const timeline = await op.handler(remote(sourceA, ['admin']), { slug: 'notes/shared', timeline: entry.id }) as Record<string, any>;
+ expect(timeline.created.principal.name).toBe('legacy-example');
+
+ await expect(op.handler(local(sourceA), { slug: 'notes/shared', fact: world, take: 1 })).rejects.toBeInstanceOf(OperationError);
+ await expect(op.handler(local(sourceA), { slug: 'notes/shared', fact: -1 })).rejects.toMatchObject({ code: 'invalid_params' });
+ });
+ });
+
+ describe('attribution-backfill (spec 2.6, test 13)', () => {
+ test('fills only journal-proven NULLs, resumes after an interruption, is idempotent and leaves the rest NULL', async () => {
+ const sourceId = await newSource('attr-fill');
+ const ctx = local(sourceId);
+ const put = async (slug: string, body: string) => {
+ const requestId = randomUUID();
+ const [current] = await engine.executeRaw<{ revision: string }>(
+ 'SELECT knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ await operationsByName.put_page.handler(ctx, { slug, request_id: requestId, content: `---\ntype: note\ntitle: Alpha\n---\n${body}\n`,
+ ...(current ? { expected_revision: current.revision } : {}) });
+ return requestId;
+ };
+ const first = await put('notes/alpha', 'First body.');
+ const second = await put('notes/alpha', 'Second body.');
+ await engine.putPage('people/beta-example', { type: 'person', title: 'Beta Example', compiled_truth: 'Unjournaled page.' }, { sourceId });
+ const rememberId = randomUUID();
+ const remembered = await operationsByName.remember.handler(ctx, { fact: 'Beta likes tea.', provenance: 'test', entity: 'people/beta-example',
+ request_id: rememberId }) as Record<string, any>;
+ expect(remembered.status).toBe('inserted');
+ const duplicate = await operationsByName.remember.handler(ctx, { fact: 'Beta likes tea.', provenance: 'test', entity: 'people/beta-example',
+ request_id: randomUUID() }) as Record<string, any>;
+ expect(duplicate.status).toBe('duplicate');
+ await engine.putPage('notes/gamma', { type: 'note', title: 'Gamma', compiled_truth: 'Unjournaled gamma.' }, { sourceId });
+ const gamma = await operationsByName.get_page.handler(ctx, { slug: 'notes/gamma', include_content: true }) as Record<string, any>;
+ const [gammaRevision] = await engine.executeRaw<{ revision: string }>(
+ `SELECT knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug='notes/gamma'`, [sourceId]);
+ const unchanged = await operationsByName.put_page.handler(ctx, { slug: 'notes/gamma', request_id: randomUUID(), content: gamma.content,
+ expected_revision: gammaRevision.revision }) as Record<string, any>;
+ expect(unchanged.status).toBe('skipped');
+ expect(unchanged.revision).toBe(gammaRevision.revision);
+ const [orphan] = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO facts(source_id, entity_slug, fact, visibility, source) VALUES ($1,'people/beta-example','Unjournaled fact.','world','test') RETURNING id`, [sourceId]);
+
+ const journal = async (requestId: string) => (await engine.executeRaw<{ id: string; principal_kind: string; principal_id: string }>(
+ 'SELECT id::text AS id, principal_kind, principal_id FROM persistence_requests WHERE request_id=$1', [requestId]))[0];
+ const [r1, r2, r3] = [await journal(first), await journal(second), await journal(rememberId)];
+ expect(r1.principal_kind).toBe('local_cli');
+ const alpha = async () => (await engine.executeRaw<Record<string, string | null>>(
+ `SELECT revision_write_request_id::text AS req, revision_principal_kind AS kind, revision_principal_id AS pid FROM pages WHERE source_id=$1 AND slug='notes/alpha'`, [sourceId]))[0];
+ const versions = async () => engine.executeRaw<Record<string, string | null>>(
+ `SELECT pv.write_request_id::text AS req, pv.write_principal_kind AS kind FROM page_versions pv JOIN pages p ON p.id=pv.page_id
+ WHERE p.source_id=$1 AND p.slug='notes/alpha' ORDER BY pv.id`, [sourceId]);
+ const fact = async (id: number | string) => (await engine.executeRaw<Record<string, string | null>>(
+ 'SELECT write_request_id::text AS req, write_principal_kind AS kind, last_write_request_id::text AS last FROM facts WHERE id=$1', [id]))[0];
+ const revisionOf = async (slug: string) => (await engine.executeRaw<Record<string, string | null>>(
+ 'SELECT revision_write_request_id::text AS req, revision_principal_kind AS kind FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0];
+
+ await asPreAttributionRows(sourceId);
+ const scope = await resolveRepairScope(engine, sourceId);
+ const preview = await runRepair(ctx, attributionBackfillRepair, scope, { apply: false });
+ expect(preview.mode).toBe('dry_run');
+ expect(preview.sample.map(s => s.split(':')[1].split('#')[0])).toEqual(['pages', 'page_versions', 'facts']);
+ expect(preview.residuals).toEqual({ unrecorded_pages: 1, unrecorded_page_versions: 1, unrecorded_facts: 1 });
+ expect(await alpha()).toEqual({ req: null, kind: null, pid: null });
+
+ const interrupted = await runRepair(ctx, attributionBackfillRepair, scope, { apply: true, limit: 1 });
+ expect(interrupted).toMatchObject({ applied: 1, complete: false });
+ expect(await alpha()).toEqual({ req: r2.id, kind: 'local_cli', pid: r2.principal_id });
+ expect((await versions())[0].req).toBeNull();
+
+ const resumed = await runRepair(ctx, attributionBackfillRepair, scope, { apply: true });
+ expect(resumed.resumed_from).toEqual({ phase: 0, id: expect.any(Number) });
+ expect(resumed).toMatchObject({ applied: 2, complete: true });
+ expect(await versions()).toEqual([{ req: r1.id, kind: 'local_cli' }]);
+ expect(await fact(remembered.id)).toEqual({ req: r3.id, kind: 'local_cli', last: null });
+ expect(await fact(orphan.id)).toEqual({ req: null, kind: null, last: null });
+ // The fenced remember wrote the entity page's live revision; the duplicate only observed it and proves nothing.
+ expect(await revisionOf('people/beta-example')).toEqual({ req: r3.id, kind: 'local_cli' });
+ // A skipped put_page reports the unjournaled page's revision without writing it: still unrecorded.
+ expect(await revisionOf('notes/gamma')).toEqual({ req: null, kind: null });
+
+ const again = await runRepair(ctx, attributionBackfillRepair, scope, { apply: true });
+ expect(again).toMatchObject({ affected: 0, applied: 0, complete: true, resumed_from: null });
+ expect(await alpha()).toEqual({ req: r2.id, kind: 'local_cli', pid: r2.principal_id });
+
+ await rawAttributionWrite(`UPDATE pages SET revision_write_request_id=NULL, revision_principal_kind='oauth_client', revision_principal_id='client-example'
+ WHERE source_id=$1 AND slug='notes/alpha'`, [sourceId]);
+ await runRepair(ctx, attributionBackfillRepair, scope, { apply: true });
+ expect(await alpha()).toEqual({ req: null, kind: 'oauth_client', pid: 'client-example' });
+ });
+
+ test('is a registered bookkeeping kind that --all runs', async () => {
+ const { repairSpec, AUTO_REPAIR_REGISTRY } = await import('../src/core/repair/registry.ts');
+ expect(repairSpec('attribution-backfill')).toMatchObject({ embeds: 'none', checks: [] });
+ expect(AUTO_REPAIR_REGISTRY.map(spec => spec.kind)).toContain('attribution-backfill');
+ });
+ });
+
+ describe('engine copy (test 14)', () => {
+ let target: PGLiteEngine;
+ beforeAll(async () => {
+ target = new PGLiteEngine(); await target.connect({}); await target.initSchema();
- await ensureWriteAttributionColumns(target);
+ }, 120_000);
+ afterAll(async () => { await target.disconnect(); });
+
+ test('gbrain migrate --to copies fact attribution verbatim', async () => {
+ const sourceId = await newSource('attr-copy');
+ const requestId = randomUUID();
+ await engine.executeRaw(`INSERT INTO facts(source_id, entity_slug, fact, visibility, source, write_request_id, write_principal_kind, write_principal_id,
+ last_write_request_id, last_write_principal_kind, last_write_principal_id, last_written_at)
+ VALUES ($1,'people/copy-example','Copied fact.','world','test',$2,'oauth_client','client-example',$2,'legacy_token','token-example','2026-02-03T04:05:06Z')`,
+ [sourceId, requestId]);
+ await copyMigrationSources(engine, target);
+ const result = await copyMigrationFacts(engine, target);
+ expect(result.failed).toEqual([]);
+ const select = `SELECT write_request_id::text AS w, write_principal_kind AS wk, write_principal_id AS wi, last_write_request_id::text AS l,
+ last_write_principal_kind AS lk, last_write_principal_id AS li, last_written_at FROM facts WHERE source_id=$1`;
+ const [copied] = await target.executeRaw<Record<string, unknown>>(select, [sourceId]);
+ const [original] = await engine.executeRaw<Record<string, unknown>>(select, [sourceId]);
+ expect({ ...copied, last_written_at: new Date(copied.last_written_at as string).toISOString() })
+ .toEqual({ ...original, last_written_at: new Date(original.last_written_at as string).toISOString() });
+ expect(copied.w).toBe(requestId);
+ });
+ });