Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(f1c): unmanaged legacy transactions carry the maintenance principal

garrytan0d3efb10d87a
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.md
index 00b84fff00..d16f1ce018 100644
--- a/docs/architecture/system-of-record.md
+++ b/docs/architecture/system-of-record.md
@@ -143,6 +143,115 @@ Keep an appropriate database backup before any destructive recovery, and do
not delete historical unmatched facts or generate empty pages to make them
appear file-backed.
+## Write attribution
+
+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".
+
+- **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 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 --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 18fb6cb24e..c16e2311fc 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -193,7 +193,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/sync-*.ts": ["test/e2e/sync-sigkill-resume-postgres.test.ts", "test/e2e/sync-lock-overlap-postgres.test.ts", "test/e2e/sync-run-workers-postgres.test.ts"],
// v0.32.8 multi-source bug class regression suite — fires on any cycle
// phase, extract, integrity, embed, or migrate-engine change.
- "src/core/cycle/extract-takes.ts": ["test/e2e/multi-source-bug-class.test.ts", "test/e2e/extract-takes-managed.test.ts"],
+ "src/core/cycle/extract-takes.ts": ["test/e2e/multi-source-bug-class.test.ts", "test/e2e/extract-takes-managed.test.ts", "test/e2e/write-attribution-postgres.test.ts"],
// Takes write-op layer (fence-first write + page-lock journey on real PG).
"src/core/ops/takes.ts": ["test/e2e/takes-write-ops-postgres.test.ts"],
"src/core/takes-write.ts": ["test/e2e/takes-write-ops-postgres.test.ts"],
@@ -607,7 +607,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/serve-http-ingest-webhook.test.ts",
],
"src/core/embed-facts*.ts": ["test/e2e/fact-embedding-backfill-parity.test.ts"],
- "src/core/cycle/extract-facts.ts": ["test/e2e/fact-vector-repair-parity.test.ts", "test/e2e/facts-fence-reconcile-postgres.test.ts"],
+ "src/core/cycle/extract-facts.ts": ["test/e2e/fact-vector-repair-parity.test.ts", "test/e2e/facts-fence-reconcile-postgres.test.ts", "test/e2e/write-attribution-postgres.test.ts"],
"src/core/cycle/phases/consolidate.ts": ["test/e2e/managed-maintenance.test.ts", "test/e2e/cycle.test.ts"],
"src/core/ops/facts.ts": ["test/e2e/managed-facts-backstop.test.ts"],
"src/core/facts/backstop.ts": ["test/e2e/capture-dedup-postgres.test.ts", "test/e2e/managed-facts-backstop.test.ts", "test/e2e/facts-worker-config.test.ts", "test/e2e/managed-facts-embedding.test.ts", "test/e2e/managed-facts-compaction.test.ts", "test/e2e/legacy-fact-extraction-dedup-postgres.test.ts"],
@@ -625,7 +625,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/commands/sources-retry-held.ts": ["test/e2e/connector-holds.test.ts"],
"src/core/repair/connector-fences.ts": ["test/e2e/connector-holds.test.ts"],
// Fix wave 5 (#5770): stale-atoms repair and its #5777 cross-lane journey.
- "src/core/repair/stale-atoms.ts": ["test/e2e/repair-stale-atoms-postgres.test.ts", "test/e2e/journey-atoms-sync-race-postgres.test.ts", "test/e2e/managed-extract-atoms.test.ts", "test/e2e/fix-wave-5-integration.test.ts"],
+ "src/core/repair/stale-atoms.ts": ["test/e2e/repair-stale-atoms-postgres.test.ts", "test/e2e/journey-atoms-sync-race-postgres.test.ts", "test/e2e/managed-extract-atoms.test.ts", "test/e2e/fix-wave-5-integration.test.ts", "test/e2e/write-attribution-postgres.test.ts"],
// Fix wave 3 lane A: connector identity, account pin, no-op kernel, pending set and migration 176.
"src/core/take-proposals.ts": ["test/e2e/takes-propose-accept-managed.test.ts"],
"src/core/persistence/connector-sync.ts": ["test/e2e/connector-wave3.test.ts", "test/e2e/connector-holds.test.ts"],
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9d83f5a962..4fbb6c2af7 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -17,7 +17,7 @@ src/core/cycle.ts 3200 ratchet +2 System One v1 S9: extract_facts phase tail run
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/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)
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index a7b5aaf619..7f8949e586 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -347,5 +347,6 @@ test/v0_37_gap_fill.serial.test.ts Lane D.3 — sync surfaces dim-mismatch recip
test/v0_37_gap_fill.serial.test.ts Lane E.4 — loadRecommendationContext is provider-aware 1 readFileSync,source-surface-helper
test/v0_37_gap_fill.serial.test.ts reinit-pglite — backup + reinit 7 source-surface-helper
test/worker-supervised-db-probe.test.ts issue #1801 fix #2 — supervised DB self-defense 5 readFileSync
+test/write-attribution-legacy.test.ts write attribution inventory 1 readFileSync
# unknown (detectors present, no attributable suite):
# unknown test/e2e/postgres-driver-install.test.ts
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 3bf867fde2..1ca31c4d81 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -56,6 +56,7 @@ import { existsSync, readFileSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
import { managedDerivedFactsPreflight, withDerivedFactsWrite } from '../persistence/derived-facts.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
import {
resolveSupersededByRow,
supersessionChainOf,
@@ -444,7 +445,7 @@ export async function runExtractFacts(
// inside the coordinator's source capability under the page key.
const managed = await managedDerivedFactsPreflight(engine, sourceId);
const transact = <T>(slugs: string[], fn: (tx: BrainEngine) => Promise<T>): Promise<T> =>
- managed ? withDerivedFactsWrite(engine, sourceId, slugs, fn) : engine.transaction(fn);
+ managed ? withDerivedFactsWrite(engine, sourceId, slugs, fn) : maintenanceTransaction(engine, fn);
const result: ExtractFactsResult = {
pagesScanned: 0,
pagesWithFacts: 0,
diff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.ts
index 5590dd5365..9fd7bcbb4c 100644
--- a/src/core/cycle/extract-takes.ts
+++ b/src/core/cycle/extract-takes.ts
@@ -28,7 +28,7 @@ import { parseTakesFence, TAKES_FENCE_BEGIN, type ParsedTake } from '../takes-fe
import { walkMarkdownFiles } from '../../commands/extract.ts';
import { takesPreparation } from '../takes-write.ts';
import { withCoordinatedWrite } from '../persistence/context.ts';
-import { maintenanceAttribution } from '../persistence/attribution.ts';
+import { maintenanceAttribution, maintenanceTransaction } from '../persistence/attribution.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
export interface ExtractTakesOpts {
@@ -131,7 +131,7 @@ async function flushBatch(
if (dryRun) {
result.takesUpserted += buffer.length;
} else {
- const inserted = await engine.addTakesBatch(buffer);
+ const inserted = await maintenanceTransaction(engine, tx => tx.addTakesBatch(buffer));
result.takesUpserted += inserted;
}
buffer.length = 0;
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index f7b8bf1c7d..009416e134 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -1,4 +1,5 @@
import { assertUnmanagedCanonicalWriter } from './persistence/maintenance.ts';
+import { maintenanceTransaction } from './persistence/attribution.ts';
import { assertImportBase, sameCanonicalImport, sameContentAnyKeyOrder } from './page-state/import-guard.ts';
import { stabilizeSafetyAssessments } from './persistence/reconcile-safety.ts';
import { decideImportIdentity, collidingSlugOwner, fileOriginUri } from './import-identity.ts';
@@ -1031,7 +1032,7 @@ export async function importFromContent(
validate: tx => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),
apply: applyPrepared,
});
- await engine.transaction(applyPrepared).catch(async (err: unknown) => {
+ await maintenanceTransaction(engine, applyPrepared).catch(async (err: unknown) => {
// #4287: name the dimension-mismatch rollback instead of letting the bare
// pgvector message ("expected N dimensions, not M") surface with no code,
// no consequence and no fix. S2: name the registry-ACTIVE column the
@@ -1546,7 +1547,7 @@ export async function importCodeFile(
const result: ImportResult = { slug, status: 'imported', chunks: chunks.length };
return opts.prepare({ slug, parsedPage, observedRevision: existing?.knowledge_revision ?? null, noop: false, result, validate: async () => {}, apply });
}
- await engine.transaction(apply);
+ await maintenanceTransaction(engine, apply);
// Post-write read-back verification.
// Same guard as the markdown path: a code page write is not "done" until
@@ -1696,7 +1697,7 @@ export async function withImportTransaction(
engine: BrainEngine,
spec: ImportTransactionSpec,
): Promise<void> {
- await engine.transaction(tx => applyImportTransaction(tx, spec));
+ await maintenanceTransaction(engine, tx => applyImportTransaction(tx, spec));
}
async function applyImportTransaction(tx: BrainEngine, spec: ImportTransactionSpec): Promise<void> {
diff --git a/src/core/persistence/attribution.ts b/src/core/persistence/attribution.ts
index 2d8b1f83c0..f61376e7bb 100644
--- a/src/core/persistence/attribution.ts
+++ b/src/core/persistence/attribution.ts
@@ -1,5 +1,7 @@
import { currentVerifiedLocalWriter, localHostId, readLocalWriter } from './identity.ts';
import type { Principal, SqlEngine, WriteRequest } from './model.ts';
+import type { BrainEngine } from '../engine.ts';
+import { withWriteAttribution } from './context.ts';
/**
* The actor the database stamps on rows written inside withCoordinatedWrite
@@ -8,7 +10,7 @@ import type { Principal, SqlEngine, WriteRequest } from './model.ts';
*/
export interface WriteAttribution { requestId: string | null; principal: Principal; }
-export { withWriteAttribution } from './context.ts';
+export { withWriteAttribution };
/** A journaled request publishes as itself. */
export function requestAttribution(row: Pick<WriteRequest, 'id' | 'principal_kind' | 'principal_id'>): WriteAttribution {
@@ -45,3 +47,13 @@ export async function maintenanceAttribution(engine: SqlEngine): Promise<WriteAt
}
}
const installationRegistration = new WeakMap<SqlEngine, Promise<string>>();
+
+/**
+ * One unmanaged legacy transaction (direct import, extract_facts, extract-takes,
+ * stale-atom retirement) whose rows carry the maintenance principal. A managed
+ * brain's guard still refuses these writes: this sets no coordinator capability.
+ */
+export async function maintenanceTransaction<T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ const attribution = await maintenanceAttribution(engine);
+ return engine.transaction(tx => withWriteAttribution(tx, attribution, () => fn(tx)));
+}
diff --git a/src/core/repair/stale-atoms.ts b/src/core/repair/stale-atoms.ts
index a108a58652..d200d77402 100644
--- a/src/core/repair/stale-atoms.ts
+++ b/src/core/repair/stale-atoms.ts
@@ -29,6 +29,7 @@ import type { WriteRequest } from '../persistence/model.ts';
import { OperationError, type OperationContext } from '../ops/contract.ts';
import { authorizeWrite } from '../persistence/authority.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
import { preparePageMutation } from '../persistence/page-prepare.ts';
import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
import { bumpAtomGeneration, managedAtomCompletedSql } from '../persistence/atom-maintenance.ts';
@@ -174,7 +175,7 @@ async function retireStaleAtom(ctx: OperationContext, atom: StaleAtom): Promise<
}
return { applied: true, outcome: 'retired' };
}
- const retired = await engine.transaction(async tx => {
+ const retired = await maintenanceTransaction(engine, async tx => {
await tx.lockPageKeys([{ sourceId: atom.source_id, slug: atom.slug }, { sourceId: atom.source_id, slug: atom.origin_slug }]);
if (!sameAtom((await staleAtoms(tx, [atom.source_id], atom.id))[0], atom)) return false;
await tx.createVersion(atom.slug, { sourceId: atom.source_id });
diff --git a/test/e2e/write-attribution-postgres.test.ts b/test/e2e/write-attribution-postgres.test.ts
index 9ee4eacfef..410fcc32ef 100644
--- a/test/e2e/write-attribution-postgres.test.ts
+++ b/test/e2e/write-attribution-postgres.test.ts
@@ -3,9 +3,11 @@ import { hasDatabase } from './helpers.ts';
// Foundations 1 write attribution on Postgres: the transaction-local actor
// settings and BEFORE ROW triggers, run direct and through transaction-mode
-// PgBouncer (scripts/e2e-backend-matrix.txt).
+// PgBouncer (scripts/e2e-backend-matrix.txt). The legacy file covers the
+// unmanaged transactional writers (F1c).
if (hasDatabase()) {
await import('../write-attribution.test.ts');
+ await import('../write-attribution-legacy.test.ts');
} else {
test.skip('write attribution on Postgres requires DATABASE_URL', () => {});
}
diff --git a/test/import-file.test.ts b/test/import-file.test.ts
index 65d4f2a2aa..0562fa2477 100644
--- a/test/import-file.test.ts
+++ b/test/import-file.test.ts
@@ -75,6 +75,8 @@ function mockEngine(overrides: Partial<Record<string, any>> = {}): BrainEngine {
}
// transaction: just call the fn with the same engine (no real DB transaction in tests)
if (prop === 'transaction') return async (fn: (tx: BrainEngine) => Promise<any>) => fn(engine);
+ // Like a real engine, executeRaw always resolves to a row array.
+ if (prop === 'executeRaw' && !overrides.executeRaw) return (...args: any[]) => { calls.push({ method: prop, args }); return Promise.resolve([]); };
return track(prop);
},
});
diff --git a/test/import-yaml-frontmatter.test.ts b/test/import-yaml-frontmatter.test.ts
index 891e25057f..f64824c0c8 100644
--- a/test/import-yaml-frontmatter.test.ts
+++ b/test/import-yaml-frontmatter.test.ts
@@ -31,7 +31,8 @@ function mockEngine(): BrainEngine {
if (prop === 'transaction') return async (fn: (tx: BrainEngine) => Promise<any>) => fn(engine);
return (...args: any[]) => {
calls.push({ method: String(prop), args });
- return Promise.resolve(null);
+ // Like a real engine, executeRaw always resolves to a row array.
+ return Promise.resolve(prop === 'executeRaw' ? [] : null);
};
},
});
diff --git a/test/write-attribution-legacy.test.ts b/test/write-attribution-legacy.test.ts
new file mode 100644
index 0000000000..19ecbb746a
--- /dev/null
+++ b/test/write-attribution-legacy.test.ts
@@ -0,0 +1,206 @@
+/**
+ * Foundations 1 (F1c) write attribution on unmanaged brains: the legacy
+ * transactional writers that have no journal request stamp the local
+ * maintenance principal (write_request_id NULL).
+ *
+ * Protects: direct markdown, code and image imports (pages.revision_* and the
+ * page_versions row an edit archives), the unmanaged extract_facts page
+ * reconcile, extract-takes and `gbrain repair stale-atoms --apply`. Fails if
+ * one of those transactions stops entering maintenanceTransaction. Also pins the
+ * "unattributed until Foundations 2" list in docs/architecture/system-of-record.md
+ * against a grep of src, so a new direct writer cannot fall out silently.
+ * Runs on PGLite, and on Postgres (direct and transaction-mode PgBouncer)
+ * through test/e2e/write-attribution-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, relative } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { importFromContent, importFromFile, importImageFile } from '../src/core/import-file.ts';
+import { registerLocalWriter, readLocalWriter } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { extractTakes } from '../src/core/cycle/extract-takes.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { renderTakesFence } from '../src/core/takes-fence.ts';
+import { configureGateway } from '../src/core/ai/gateway.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const engines: BrainEngine[] = [];
+const scratch = mkdtempSync(join(tmpdir(), 'gbrain-write-attribution-legacy-'));
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ rmSync(scratch, { recursive: true, force: true });
+});
+
+type Actor = { request: string | null; kind: string | null; id: string | null };
+interface Brain { engine: BrainEngine; sourceId: string; maintenance: Actor }
+/** An unmanaged brain whose installation has a local CLI registration: maintenance writes name it. */
+async function unmanagedBrain(engine: BrainEngine): Promise<Brain> {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const sourceId = `legacy-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await registerLocalWriter(engine, 'cli');
+ return { engine, sourceId, maintenance: { request: null, kind: 'local_cli', id: (await readLocalWriter(engine, 'cli')).id } };
+}
+async function revisionActor(brain: Brain, slug: string): Promise<Actor | undefined> {
+ return (await brain.engine.executeRaw<Actor>(`SELECT revision_write_request_id::text AS request,revision_principal_kind AS kind,revision_principal_id AS id
+ FROM pages WHERE source_id=$1 AND slug=$2`, [brain.sourceId, slug]))[0];
+}
+async function versionActors(brain: Brain, slug: string) {
+ return brain.engine.executeRaw<{ write: Actor; archived: Actor }>(`SELECT
+ jsonb_build_object('request',v.write_request_id::text,'kind',v.write_principal_kind,'id',v.write_principal_id) AS write,
+ jsonb_build_object('request',v.archived_write_request_id::text,'kind',v.archived_principal_kind,'id',v.archived_principal_id) AS archived
+ FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY v.id`, [brain.sourceId, slug]);
+}
+const ROW_ACTORS = `jsonb_build_object('request',write_request_id::text,'kind',write_principal_kind,'id',write_principal_id) AS created,
+ jsonb_build_object('request',last_write_request_id::text,'kind',last_write_principal_kind,'id',last_write_principal_id) AS last`;
+const page = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\n---\n${body}\n`;
+const PNG = (shade: string) => Buffer.from(shade, 'base64');
+
+describe('write attribution on an unmanaged brain', () => {
+ test('direct markdown, code and image imports stamp the local maintenance principal on the revision and the archived version', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const slug = 'notes/direct-import-example';
+ await importFromContent(engine, slug, page('Direct', 'First body'), { sourceId: brain.sourceId, noEmbed: true });
+ await importFromContent(engine, slug, page('Direct', 'Second body'), { sourceId: brain.sourceId, noEmbed: true });
+ expect(await revisionActor(brain, slug)).toEqual(brain.maintenance);
+ expect(await versionActors(brain, slug)).toEqual([{ write: brain.maintenance, archived: brain.maintenance }]);
+
+ const root = join(scratch, brain.sourceId);
+ mkdirSync(join(root, 'src'), { recursive: true }); mkdirSync(join(root, 'photos'), { recursive: true });
+ const code = join(root, 'src/example.ts');
+ writeFileSync(code, 'export const answer = 1;\n');
+ const first = await importFromFile(engine, code, 'src/example.ts', { sourceId: brain.sourceId, noEmbed: true });
+ writeFileSync(code, 'export const answer = 2;\n');
+ await importFromFile(engine, code, 'src/example.ts', { sourceId: brain.sourceId, noEmbed: true });
+ expect(await revisionActor(brain, first.slug)).toEqual(brain.maintenance);
+ expect(await versionActors(brain, first.slug)).toEqual([{ write: brain.maintenance, archived: brain.maintenance }]);
+
+ const image = join(root, 'photos/board.png');
+ writeFileSync(image, PNG('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aV9kAAAAASUVORK5CYII='));
+ const pictured = await importImageFile(engine, image, 'photos/board.png', { sourceId: brain.sourceId, noEmbed: true });
+ writeFileSync(image, PNG('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgAAIAAAUAAarVyFEAAAAASUVORK5CYII='));
+ await importImageFile(engine, image, 'photos/board.png', { sourceId: brain.sourceId, noEmbed: true });
+ expect(await revisionActor(brain, pictured.slug)).toEqual(brain.maintenance);
+ expect(await versionActors(brain, pictured.slug)).toEqual([{ write: brain.maintenance, archived: brain.maintenance }]);
+ }
+ }, 120_000);
+
+ test('an unmanaged extract_facts cycle stamps the facts it reconciles', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const slug = 'people/alice-example';
+ const facts = renderFactsTable([
+ { rowNum: 1, claim: 'Prefers written updates', kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true },
+ ] as never);
+ await engine.putPage(slug, { type: 'person', title: 'Alice', compiled_truth: `Profile\n\n${facts}` }, { sourceId: brain.sourceId });
+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1', [brain.sourceId])).toEqual([]);
+ await runExtractFacts(engine, { sourceId: brain.sourceId });
+ const rows = await engine.executeRaw<{ created: Actor; last: Actor }>(`SELECT ${ROW_ACTORS} FROM facts WHERE source_id=$1`, [brain.sourceId]);
+ expect(rows).toEqual([{ created: brain.maintenance, last: brain.maintenance }]);
+ }
+ }, 120_000);
+
+ test('extract-takes stamps the takes it upserts', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const slug = `people/charlie-example-${brain.sourceId}`;
+ const takes = renderTakesFence([{ rowNum: 1, claim: 'Ships carefully', kind: 'take', holder: 'world', weight: 0.6, active: true }] as never);
+ const stored = await engine.putPage(slug, { type: 'person', title: 'Charlie', compiled_truth: `Profile\n\n${takes}` }, { sourceId: brain.sourceId });
+ await engine.executeRaw('DELETE FROM takes WHERE page_id=$1', [stored.id]);
+ expect((await extractTakes(engine, { source: 'db', slugs: [slug] })).takesUpserted).toBe(1);
+ const rows = await engine.executeRaw<{ created: Actor; last: Actor }>(`SELECT ${ROW_ACTORS} FROM takes WHERE page_id=$1`, [stored.id]);
+ expect(rows).toEqual([{ created: brain.maintenance, last: brain.maintenance }]);
+ }
+ }, 120_000);
+
+ test('gbrain repair stale-atoms --apply stamps the retirement on the atom revision and its archived version', async () => {
+ for (const engine of engines) {
+ const brain = await unmanagedBrain(engine);
+ const atom = 'atoms/2026-01-01/gone-example';
+ await engine.putPage('notes/gone-example', { type: 'note', title: 'Gone', compiled_truth: 'A page the user deleted.' }, { sourceId: brain.sourceId });
+ await engine.putPage(atom, { type: 'atom', title: atom, compiled_truth: 'A claim.',
+ frontmatter: { type: 'atom', source_slug: 'notes/gone-example', source_hash: 'cccccccccccccccc' } }, { sourceId: brain.sourceId });
+ await engine.softDeletePage('notes/gone-example', { sourceId: brain.sourceId });
+ const repair = async (args: string[]) => {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await runRepairCommand(engine, ['stale-atoms', '--source', brain.sourceId, ...args, '--json']); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')).results[0] as { apply_command: string; outcomes?: Record<string, number> };
+ };
+ const hash = (await repair([])).apply_command.match(/--expect ([0-9a-f]+)/)![1];
+ expect((await repair(['--apply', '--expect', hash])).outcomes).toEqual({ retired: 1 });
+ const [retired] = await engine.executeRaw<{ deleted: boolean }>('SELECT deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id=$1 AND slug=$2', [brain.sourceId, atom]);
+ expect(retired.deleted).toBe(true);
+ expect(await revisionActor(brain, atom)).toEqual(brain.maintenance);
+ expect((await versionActors(brain, atom)).map(row => row.archived)).toEqual([brain.maintenance]);
+ }
+ }, 120_000);
+});
+
+describe('write attribution inventory', () => {
+ /**
+ * Every src file that writes a content row (facts, takes, timeline_entries),
+ * a page version or a page revision directly, outside the engine and schema
+ * layers. Comment lines are skipped. The count per file is the number of
+ * writer references this grep finds, so a new writer in a listed file moves
+ * it too.
+ */
+ const WRITER_METHODS = 'putPage|refreshPageBody|softDeletePage|softDeletePages|restorePage|createVersion|revertToVersion|addTag|removeTag|updateSlug|'
+ + 'addTimelineEntry|addTimelineEntriesBatch|addTakesBatch|updateTake|supersedeTake|resolveTake|insertFact|insertFacts|expireFact|consolidateFact|migrateFactsToCanonical';
+ const WRITER = new RegExp(`\\.(?:${WRITER_METHODS})\\s*(?:\\?\\.)?\\s*\\(`
+ + '|\\b(?:INSERT\\s+INTO|UPDATE)\\s+(?:page_versions|facts|takes|timeline_entries)\\b'
+ + '|\\bUPDATE\\s+pages\\s+(?:\\w+\\s+)?SET\\s+(?:\\w+\\.)?(?:frontmatter|compiled_truth|timeline|title|type|deleted_at|slug|content_hash)\\b', 'gi');
+ const LAYER = /^src\/(?:eval\/|core\/engine-sql\/|core\/schema-migrations\/|commands\/migrations\/)|(?:^|\/)(?:engine|pglite-engine|postgres-engine)\.ts$|(?:^|[/-])schema\.ts$|\.generated\.ts$/;
+ const root = join(import.meta.dir, '..');
+ function sourceFiles(directory: string): string[] {
+ return readdirSync(directory, { withFileTypes: true }).flatMap(entry => entry.isDirectory()
+ ? sourceFiles(join(directory, entry.name)) : entry.name.endsWith('.ts') ? [join(directory, entry.name)] : []);
+ }
+ function directWriters(): Record<string, number> {
+ const found: Record<string, number> = {};
+ for (const file of sourceFiles(join(root, 'src'))) {
+ const path = relative(root, file);
+ if (LAYER.test(path)) continue;
+ // test-reads-source-ok[structural]: the attribution inventory is a source-text tripwire by design, like the canonical writer census.
+ const body = readFileSync(file, 'utf8').split('\n').map(line => /^\s*(?:\/\/|\/?\*)/.test(line) ? '' : line).join('\n');
+ const count = [...body.matchAll(WRITER)].length;
+ if (count) found[path] = count;
+ }
+ return found;
+ }
+ function documentedList(marker: string): Record<string, number> {
+ const doc = readFileSync(join(root, 'docs/architecture/system-of-record.md'), 'utf8');
+ const section = doc.split(`<!-- ${marker}:start -->`)[1]?.split(`<!-- ${marker}:end -->`)[0];
+ if (section === undefined) throw new Error(`system-of-record.md is missing the ${marker} list`);
+ return Object.fromEntries([...section.matchAll(/^- `([^`]+)` \((\d+)\)/gm)].map(match => [match[1], Number(match[2])]));
+ }
+
+ test('every direct writer is either attributed or listed as unattributed until Foundations 2', () => {
+ const unattributed = documentedList('write-attribution-unattributed');
+ const attributed = documentedList('write-attribution-covered');
+ expect(Object.keys(unattributed).filter(path => path in attributed)).toEqual([]);
+ expect({ ...attributed, ...unattributed }, 'A direct writer moved. Run it in maintenanceTransaction (or route it through the coordinator) and list it under '
+ + '"attributed" with its new count, or list it under "unattributed until Foundations 2 mutation attribution" in docs/architecture/system-of-record.md.')
+ .toEqual(directWriters());
+ });
+});