Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
attribution: route repair, sync soft delete, ingest, review and conversation-fact writers through maintenanceTransaction
garrytanf95e86542acf
diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex b4a80e669d..afb42e2cf7 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -207,11 +207,14 @@ Attributed (inside a request, a coordinated scope or `maintenanceTransaction`,or a physical projection that leaves attribution untouched):<!-- write-attribution-covered:start -->+- `src/commands/extract-conversation-facts.ts` (3): the conversation fact index writes through `writeDerivedFacts`: one `maintenanceTransaction` on unmanaged brains, `withDerivedFactsWrite` on managed brains.- `src/commands/extract-timeline-db.ts` (2): `gbrain extract timeline --source db` commits one `maintenanceTransaction` per 100-row batch on unmanaged brains; managed brains publish per page through a maintenance request.- `src/commands/migrate-engine.ts` (5): engine copy keeps the source rows' attribution values verbatim.- `src/commands/sync/holds.ts` (1): a full sync's move of a held rename (`updateSlug` and its `source_path`) runs in one `maintenanceTransaction`; managed sources publish renames through the sync request preparer.- `src/commands/sync/renames.ts` (1): the legacy sync rename (`updateSlug`) runs in `maintenanceTransaction`; managed sources publish renames through the sync request preparer.+- `src/core/calibration/undo-wave.ts` (1): the calibration wave undo of take resolutions runs in `maintenanceTransaction`.- `src/core/chronicle/publish.ts` (3): Life Chronicle event generations: maintenance requests on managed brains; the unmanaged event write, retirement soft delete and retired stamp run in `maintenanceTransaction`.+- `src/core/company-brain/profile.ts` (1): legacy sync soft deletes (`softDeleteSyncPages`) run in `maintenanceTransaction`, inside the company-brain source check when one is active.- `src/core/cycle/dream-provenance.ts` (1): the dream provenance frontmatter stamp runs per page in `maintenanceTransaction` (unmanaged brains only; managed synthesis publishes through maintenance requests).- `src/core/cycle/drift.ts` (1): the unmanaged drift report page runs in `maintenanceTransaction`; managed brains publish it through a maintenance request.- `src/core/cycle/extract-atoms-page-state.ts` (1): the atom completion stamp runs in `maintenanceTransaction`.@@ -233,6 +236,8 @@ or a physical projection that leaves attribution untouched):- `src/core/facts/withdrawal.ts` (1): runs inside the `forget` request's coordinated write.- `src/core/facts/write-single.ts` (2): the legacy single-fact insert and its supersession link each run in `maintenanceTransaction`; managed brains publish through the fact request.- `src/core/import-file.ts` (11): direct markdown, code and image imports, the moved-file rename (`updateSlug`) and the #3694 legacy-hash re-stamp run in `maintenanceTransaction`; managed imports go through the page request preparer.+- `src/core/minions/handlers/ingest-capture.ts` (1): the capture ingest tombstone soft delete runs in `maintenanceTransaction`.+- `src/core/ops/extraction.ts` (2): extraction review promote (frontmatter) and reject (soft delete) each run in `maintenanceTransaction`.- `src/core/output/writer.ts` (4): `BrainWriter.transaction` is a `maintenanceTransaction`, so its pages and timeline rows carry the maintenance principal.- `src/core/page-state/materialize.ts` (1): coordinated maintenance.- `src/core/page-state/rename-alias.ts` (2): the fact slug rewrite runs inside its caller's `updateSlug` transaction, and every caller is attributed.@@ -241,7 +246,7 @@ or a physical projection that leaves attribution untouched):- `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/derived-facts.ts` (1): `withDerivedFactsWrite` (managed derived facts); `writeDerivedFacts` runs legacy writers in `maintenanceTransaction` on unmanaged brains.- `src/core/persistence/facts-prepare.ts` (3): managed `extract_facts` request preparer.- `src/core/persistence/file-repair.ts` (2): `managed_file_repair` request preparer (#5988).- `src/core/persistence/grandfather.ts` (2): request preparer.@@ -254,6 +259,8 @@ or a physical projection that leaves attribution untouched):- `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/captured-facts.ts` (1): a request on managed brains; the unmanaged captured-facts expiry runs in `maintenanceTransaction`.+- `src/core/repair/extractor-facts.ts` (1): a request on managed brains; the unmanaged extractor-facts restore runs in `maintenanceTransaction`.- `src/core/repair/frontmatter.ts` (1): a `managed_file_repair` request on managed sources; the unmanaged rename runs in `maintenanceTransaction`.- `src/core/repair/stale-atoms.ts` (3): a request on managed brains; the unmanaged retirement runs in `maintenanceTransaction`.- `src/core/schema-pack/page-to-alias.ts` (1): the page-to-alias conversion soft-deletes each converted page in `maintenanceTransaction`.@@ -271,16 +278,9 @@ Unattributed until Foundations 2 mutation attribution (on unmanaged brainsthese 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.ts` (4): `gbrain extract` timeline walks (file, incremental, stale) and the per-entry fallback.-- `src/core/calibration/undo-wave.ts` (1): calibration wave undo of take resolutions.-- `src/core/company-brain/profile.ts` (1): company-brain sync soft deletes.- `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/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/repair/captured-facts.ts` (1): unmanaged captured-facts expiry.-- `src/core/repair/extractor-facts.ts` (1): extractor-facts repair update.<!-- write-attribution-unattributed:end -->## The privacy boundarydiff --git a/src/core/calibration/undo-wave.ts b/src/core/calibration/undo-wave.tsindex d1df82e563..af2b0e211b 100644--- a/src/core/calibration/undo-wave.ts+++ b/src/core/calibration/undo-wave.ts@@ -42,6 +42,7 @@import { execFileSync } from 'node:child_process';import { GSTACK_LEARNING_NAMESPACE } from './gstack-coupling.ts';import type { BrainEngine } from '../engine.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';export interface UndoWaveOpts {/** Wave version to reverse. v0.36.1.0 ship state: 'v0.36.1.0'. */@@ -118,7 +119,7 @@ export async function undoWave();result.resolutions_reverted = counted[0]?.count ?? 0;} else {- const reverted = await engine.executeRaw<{ id: number }>(+ const reverted = await maintenanceTransaction(engine, tx => tx.executeRaw<{ id: number }>(`UPDATE takesSET resolved_at = NULL,resolved_outcome = NULL,@@ -131,7 +132,7 @@ export async function undoWave(AND resolved_by = $2RETURNING id`,[targetTakeIds, resolvedByLabel],- );+ ));result.resolutions_reverted = reverted.length;}}diff --git a/src/core/company-brain/profile.ts b/src/core/company-brain/profile.tsindex 7d10235ce2..a01359ddcc 100644--- a/src/core/company-brain/profile.ts+++ b/src/core/company-brain/profile.ts@@ -13,6 +13,7 @@ import type { ResolvedPack } from '../schema-pack/registry.ts';import type { CompanyBrainPlan, InspectionEntry } from './types.ts';import type { SourceIngestionCheckpoint } from './receipts.ts';import { companyBrainProfile, companyBrainPolicyFingerprint, type CompanyBrainProfile } from './policy.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';export { companyBrainProfile, type CompanyBrainProfile } from './policy.ts';function statusFix(sourceId: string): Action {@@ -73,7 +74,7 @@ export async function withCompanyBrainSource<T>(engine: BrainEngine, sourceId: s}export function softDeleteSyncPages(engine: BrainEngine, slugs: string[], opts: { sourceId: string }): Promise<string[]> {- return withCompanyBrainSource(engine, opts.sourceId, tx => tx.softDeletePages(slugs, opts));+ return withCompanyBrainSource(engine, opts.sourceId, tx => maintenanceTransaction(tx, inner => inner.softDeletePages(slugs, opts)));}export async function readCompanyBrainPlan(engine: BrainEngine, receiptId: string): Promise<CompanyBrainPlan> {diff --git a/src/core/minions/handlers/ingest-capture.ts b/src/core/minions/handlers/ingest-capture.tsindex 16aac1d8d0..89bd35c66c 100644--- a/src/core/minions/handlers/ingest-capture.ts+++ b/src/core/minions/handlers/ingest-capture.ts@@ -34,6 +34,7 @@ import type { BrainEngine } from '../../engine.ts';import type { IngestionEvent } from '../../ingestion/types.ts';import { validateIngestionEvent } from '../../ingestion/types.ts';import { importFromContent } from '../../import-file.ts';+import { maintenanceTransaction } from '../../persistence/attribution.ts';export interface IngestCaptureResult {slug: string;@@ -201,7 +202,7 @@ export function makeIngestCaptureHandler(engine: BrainEngine) {// same-slug page in another source is untouched. Idempotent: a missing or// already-deleted page reports 'skipped'.if (isTombstone) {- const deleted = await engine.softDeletePage(slug, { sourceId: sourceId ?? 'default' });+ const deleted = await maintenanceTransaction(engine, tx => tx.softDeletePage(slug, { sourceId: sourceId ?? 'default' }));if (sourceFallback) {console.error(`[WARN] ingest_capture: requested source '${sourceFallback.requested}' unavailable ` +diff --git a/src/core/ops/extraction.ts b/src/core/ops/extraction.tsindex 4503eb0491..d1b40aae2d 100644--- a/src/core/ops/extraction.ts+++ b/src/core/ops/extraction.ts@@ -15,6 +15,7 @@ import { hostOnlyError, paramUse, readFix } from './op-fix.ts';import { sourceScopeOpts } from './context.ts';import { unverifiedExtractionFragment, isUnverifiedExtraction, EXTRACTION_STATUS_KEY, STATUS_VERIFIED } from '../extraction-review.ts';import { buildVisibilityClause } from '../search/sql-ranking.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';// ---------------------------------------------------------------------------// Extraction quarantine lane (issue #160)@@ -229,16 +230,16 @@ const extraction_review: Operation = {// trail of HOW the page came to exist; status → 'verified' records// the owner's call. jsonb_build_object binds as text (no// JSON.stringify-into-::jsonb hazard); identical on both engines.- await ctx.engine.executeRaw(+ await maintenanceTransaction(ctx.engine, tx => tx.executeRaw(`UPDATE pagesSET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || jsonb_build_object($1::text, $2::text),updated_at = now()WHERE slug = $3 AND source_id = $4`,[EXTRACTION_STATUS_KEY, STATUS_VERIFIED, slug, page.source_id],- );+ ));results.push({ slug, status: 'promoted' });} else {- await ctx.engine.softDeletePage(slug, { sourceId: page.source_id });+ await maintenanceTransaction(ctx.engine, tx => tx.softDeletePage(slug, { sourceId: page.source_id }));results.push({ slug, status: 'rejected' });}}diff --git a/src/core/persistence/derived-facts.ts b/src/core/persistence/derived-facts.tsindex 875f457b52..86360c3e21 100644--- a/src/core/persistence/derived-facts.ts+++ b/src/core/persistence/derived-facts.ts@@ -4,7 +4,7 @@ import { opError } from '../ops/contract.ts';import { readFix, trustedCliRequired } from '../ops/op-fix.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { withCoordinatedWrite } from './context.ts';-import { maintenanceAttribution } from './attribution.ts';+import { maintenanceAttribution, maintenanceTransaction } from './attribution.ts';import { currentVerifiedLocalWriter } from './identity.ts';import { managedPersistenceEnabled } from './ownership.ts';import { assertPersistenceAccepting } from './service.ts';@@ -55,13 +55,13 @@ export async function withDerivedFactsWrite<T>(engine: BrainEngine, sourceId: st}/**- * Legacy writers keep their own engine call on unmanaged brains. On a managed- * brain the page must still be live under its lock, so rows are never+ * Legacy writers run in one maintenance transaction on unmanaged brains. On a+ * managed brain the page must still be live under its lock, so rows are never* published for a page deleted or purged while the model ran.*/export async function writeDerivedFacts<T>(engine: BrainEngine, sourceId: string, slug: string,fn: (db: BrainEngine) => Promise<T>): Promise<T> {- if (!await managedPersistenceEnabled(engine)) return fn(engine);+ if (!await managedPersistenceEnabled(engine)) return maintenanceTransaction(engine, fn);return withDerivedFactsWrite(engine, sourceId, [slug], async tx => {const [page] = await tx.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]);if (!page) {diff --git a/src/core/repair/captured-facts.ts b/src/core/repair/captured-facts.tsindex 417d0a5a10..f0c87ff823 100644--- a/src/core/repair/captured-facts.ts+++ b/src/core/repair/captured-facts.ts@@ -54,6 +54,7 @@ import { claudeProjectsDir } from '../bootstrap/host-specs.ts';import { corpusFileSessionId, corpusTextForExtraction } from '../context/corpus-segments.ts';import { pruneDir } from '../sync.ts';import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';export const CAPTURE_LANES = ['hook:writeback', 'hook:compact', 'sweep:corpus'] as const;const CORPUS_KEY = 'dream.synthesize.session_corpus_dir';@@ -310,7 +311,7 @@ const expireRows = (tx: BrainEngine, sourceId: string, ids: number[]) => tx.exec* unmanaged brain one transaction.*/async function expireDatabaseRows(engine: BrainEngine, page: CapturedFactsPage, hash: string, ids: number[]): Promise<number[]> {- if (!await managedPersistenceEnabled(engine)) return (await engine.transaction(tx => expireRows(tx, page.source_id, ids))).map(row => Number(row.id));+ if (!await managedPersistenceEnabled(engine)) return (await maintenanceTransaction(engine, tx => expireRows(tx, page.source_id, ids))).map(row => Number(row.id));const authority = (await maintenancePreflight(engine, page.source_id))!;const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });const h = digest(['captured-facts-expire-v1', hash, page.source_id, page.slug, ids, snapshot?.revision ?? null]);diff --git a/src/core/repair/extractor-facts.ts b/src/core/repair/extractor-facts.tsindex 8fb5d979aa..d7e7b1532f 100644--- a/src/core/repair/extractor-facts.ts+++ b/src/core/repair/extractor-facts.ts@@ -62,6 +62,7 @@ import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persisimport { compareWriterVersions, recentWriterVersions, writerVersionLabel } from '../persistence/writer-versions.ts';import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';export const EXTRACTOR_FACTS_INTENT = 'managed_maintenance_restore_extractor_facts';export const EXTRACTOR_FACTS_SOURCE_PREFIX = 'cli:extract-conversation-facts';@@ -320,7 +321,7 @@ export const extractorFactsRepair: RepairHandler = {const { page, hash, last } = entry as PageItem;const result = await managedPersistenceEnabled(ctx.engine)? await restoreManaged(ctx.engine, ctx.config, page, hash)- : await ctx.engine.transaction(async tx => {+ : await maintenanceTransaction(ctx.engine, async tx => {await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);return restorePageFacts(tx, page, false);});diff --git a/test/e2e/write-attribution-postgres.test.ts b/test/e2e/write-attribution-postgres.test.tsindex a5e2c1b506..1785fc90d2 100644--- a/test/e2e/write-attribution-postgres.test.ts+++ b/test/e2e/write-attribution-postgres.test.ts@@ -15,6 +15,8 @@ if (hasDatabase()) {await import('../write-attribution-timeline-10k.slow.test.ts');await import('../write-attribution-facts-takes.test.ts');await import('../write-attribution-cycle.test.ts');+ await import('../write-attribution-schema-pack.test.ts');+ await import('../write-attribution-misc.test.ts');} else {test.skip('write attribution on Postgres requires DATABASE_URL', () => {});}diff --git a/test/sync-rename-reconcile.serial.test.ts b/test/sync-rename-reconcile.serial.test.tsindex 002dd062eb..569e54e025 100644--- a/test/sync-rename-reconcile.serial.test.ts+++ b/test/sync-rename-reconcile.serial.test.ts@@ -252,7 +252,7 @@ describe('#3056: rename fallback reconciles the stale old row', () => {// Inject a transient failure into the reconcile delete (#4587: the// reconcile soft-deletes via softDeletePages now).- const origDelete = engine.softDeletePages.bind(engine);+ const origDelete = engine.softDeletePages;engine.softDeletePages = async () => { throw new Error('injected transient delete failure'); };let blocked;try {@@ -343,7 +343,7 @@ describe('#3479 blocker 1: a permanent reconcile failure has a documented operat// environment where UPDATE still works but this DELETE never will):// every retry fails the same way. Capture stderr to pin that the// blocked message documents the operator exit, not just the retry.- const origDelete = engine.softDeletePages.bind(engine);+ const origDelete = engine.softDeletePages;engine.softDeletePages = async () => { throw new Error('permission denied for table pages (injected permanent failure)'); };const stderrChunks: string[] = [];const origWrite = process.stderr.write.bind(process.stderr);@@ -415,7 +415,7 @@ describe('#3479 blocker 2: an orphaned rename sentinel self-clears; a real dupli}, { sourceId: 'default' });execSync('git mv people/carol.md people/dana.md', { cwd: repo, stdio: 'pipe' });execSync('git commit -m "rename carol to dana"', { cwd: repo, stdio: 'pipe' });- const origDelete = engine.softDeletePages.bind(engine);+ const origDelete = engine.softDeletePages;engine.softDeletePages = async () => { throw new Error('injected transient delete failure'); };try {const blocked = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });@@ -561,7 +561,7 @@ describe('#3479: non-unique source_path — a soft-deleted row must not mask a l}, { sourceId: 'default' });execSync('git mv people/carol.md people/dana.md', { cwd: repo, stdio: 'pipe' });execSync('git commit -m "rename carol to dana"', { cwd: repo, stdio: 'pipe' });- const origDelete = engine.softDeletePages.bind(engine);+ const origDelete = engine.softDeletePages;engine.softDeletePages = async () => { throw new Error('injected transient delete failure'); };try {const blocked = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });diff --git a/test/sync-soft-delete.serial.test.ts b/test/sync-soft-delete.serial.test.tsindex b81cb57119..12cf933e97 100644--- a/test/sync-soft-delete.serial.test.ts+++ b/test/sync-soft-delete.serial.test.ts@@ -164,10 +164,11 @@ describe('#4587 X3: decompose-on-batch-failure — run continues, never aborts',// Fail the BATCH call only (slugs.length > 1); the one-element decompose// calls succeed — a transient blip must not lose the whole batch.- const orig = engine.softDeletePages.bind(engine);- engine.softDeletePages = async (slugs, opts) => {+ const orig = engine.softDeletePages;+ // Unbound: the soft delete runs on a transaction engine that inherits this override.+ engine.softDeletePages = async function (this: typeof engine, slugs, opts) {if (slugs.length > 1) throw new Error('injected transient batch failure');- return orig(slugs, opts);+ return orig.call(this, slugs, opts);};let result;try {@@ -195,7 +196,7 @@ describe('#4587 X3: decompose-on-batch-failure — run continues, never aborts',writeFileSync(join(repo, 'notes/fresh.md'), '# Fresh\n\nimports despite the delete outage\n');commitAll(repo, 'remove wedged, add fresh');- const orig = engine.softDeletePages.bind(engine);+ const orig = engine.softDeletePages;engine.softDeletePages = async () => { throw new Error('injected permanent delete failure'); };let blocked;try {diff --git a/test/undo-wave.test.ts b/test/undo-wave.test.tsindex 215c5b9aa2..a9b6e28bae 100644--- a/test/undo-wave.test.ts+++ b/test/undo-wave.test.ts@@ -79,6 +79,8 @@ function buildMockEngine(state: Partial<MockEngineState>): { engine: BrainEngine}return [];},+ // The take un-resolution runs in a maintenance transaction; the mock is its own transaction engine.+ async transaction<T>(fn: (tx: BrainEngine) => Promise<T>): Promise<T> { return fn(engine); },} as unknown as BrainEngine;return { engine, sqls };}diff --git a/test/write-attribution-cycle.test.ts b/test/write-attribution-cycle.test.tsindex ac41fcaa42..b3bcf8c546 100644--- a/test/write-attribution-cycle.test.ts+++ b/test/write-attribution-cycle.test.ts@@ -197,7 +197,7 @@ describe('cycle and synthesis writers on an unmanaged brain', () => {.toEqual([{ created: brain.maintenance, last: brain.maintenance }]);const saved = await persistSynthesis(engine, { question: 'What changed for the example team?', answer: 'The team grew.', citations: [], gaps: [],- pagesGathered: 0, takesGathered: 0, graphHits: 0, modelUsed: 'test:stub', rounds: 1, warnings: [], synthesisOk: true } as ThinkResult, { sourceId: brain.sourceId });+ pagesGathered: 0, takesGathered: 0, graphHits: 0, modelUsed: 'test:stub', rounds: 1, warnings: [], synthesisOk: true } as unknown as ThinkResult, { sourceId: brain.sourceId });expect(await revisionActor(engine, brain.sourceId, saved.slug)).toEqual(brain.maintenance);const receipt = await writeReceipt(engine, { kind: 'extract_facts', source_id: brain.sourceId, run_id: `run-${brain.sourceId}`, round: 'trial',diff --git a/test/write-attribution-misc.test.ts b/test/write-attribution-misc.test.tsnew file mode 100644index 0000000000..9d82bc5def--- /dev/null+++ b/test/write-attribution-misc.test.ts@@ -0,0 +1,156 @@+/**+ * Foundations 2 (Lane C) attribution for the remaining unmanaged writers: the+ * captured-facts and extractor-facts repairs, the calibration wave undo, the+ * legacy sync soft delete (`softDeleteSyncPages`), capture ingest tombstones,+ * extraction review promote and reject, and the conversation fact index's+ * derived fact writes (`writeDerivedFacts`) run in maintenanceTransaction.+ * Pages they advance name the local maintenance principal; rows they change+ * keep their creator and move their last writer.+ *+ * Protects the remaining writer families in docs/architecture/system-of-record.md.+ * Fails if any of those writers runs outside maintenanceTransaction. 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 { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createHash } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { undoWave } from '../src/core/calibration/undo-wave.ts';+import { softDeleteSyncPages } from '../src/core/company-brain/profile.ts';+import { makeIngestCaptureHandler } from '../src/core/minions/handlers/ingest-capture.ts';+import { writeDerivedFacts } from '../src/core/persistence/derived-facts.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.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';+import { withEnv } from './helpers/with-env.ts';+import { CREATOR_ACTOR, asCreator, revisionActor, rowActors, unmanagedBrain, type Actor, type UnmanagedBrain } from './helpers/unmanaged-attribution.ts';++const engines: BrainEngine[] = [];+const scratch = mkdtempSync(join(tmpdir(), 'gbrain-write-attribution-misc-'));+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 });+});++const actors = (rows: Array<{ id: number; created: Actor; last: Actor }>) => rows.map(({ created, last }) => ({ created, last }));+const ctx = (brain: UnmanagedBrain): OperationContext => ({ engine: brain.engine, config: { engine: brain.engine.kind } as never,+ logger: { info() {}, warn() {}, error() {} } as never, dryRun: false, remote: false, sourceId: brain.sourceId });+async function creatorPage(brain: UnmanagedBrain, slug: string, frontmatter: Record<string, unknown> = {}) {+ return asCreator(brain.engine, tx => tx.putPage(slug, { type: 'note', title: slug, compiled_truth: 'A page body.', frontmatter }, { sourceId: brain.sourceId }));+}+const deletedRevisionActor = async (brain: UnmanagedBrain, slug: string) => (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 AND deleted_at IS NOT NULL`, [brain.sourceId, slug]))[0];+async function repair(engine: BrainEngine, kind: string, args: string[]) {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ try { await runRepairCommand(engine, [kind, ...args, '--json']); } finally { console.log = original; }+ return JSON.parse(lines.join('\n')).results[0] as { apply_command: string; outcomes?: Record<string, number> };+}+const expectHash = (preview: { apply_command: string }) => preview.apply_command.match(/--expect ([0-9a-f]+)/)![1];++describe('remaining unmanaged writers', () => {+ test('gbrain repair captured-facts --apply expires a database-only self-capture row, keeping its creator', async () => {+ const claude = join(scratch, 'claude');+ mkdirSync(join(claude, 'projects', '-tmp-gbrain-claude-cli-cwd-4242'), { recursive: true });+ writeFileSync(join(claude, 'projects', '-tmp-gbrain-claude-cli-cwd-4242', 'sess-self.jsonl'), '{}\n');+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ await asCreator(engine, tx => tx.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_session)+ VALUES ($1, 'people/alice-example', 'Alice Example drinks oat milk', 'fact', 'private', 'hook:writeback', 'sess-self')`, [brain.sourceId]));+ await withEnv({ CLAUDE_CONFIG_DIR: claude }, async () => {+ const preview = await repair(engine, 'captured-facts', ['--source', brain.sourceId]);+ expect((await repair(engine, 'captured-facts', ['--source', brain.sourceId, '--apply', '--expect', expectHash(preview)])).outcomes).toEqual({ expired: 1 });+ });+ expect(actors(await rowActors(engine, 'facts', 'source_id=$1', [brain.sourceId]))).toEqual([{ created: CREATOR_ACTOR, last: brain.maintenance }]);+ }+ }, 120_000);++ test('gbrain repair extractor-facts --apply restores an expired extractor fact, keeping its creator', async () => {+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ await creatorPage(brain, 'conversations/example-call');+ await asCreator(engine, tx => tx.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_session, row_num, source_markdown_slug, expired_at)+ VALUES ($1, 'people/alice-example', 'Alice sends the deck', 'commitment', 'private', 'cli:extract-conversation-facts:sess', 'sess', NULL, 'conversations/example-call', now())`,+ [brain.sourceId]));+ const preview = await repair(engine, 'extractor-facts', ['--source', brain.sourceId, '--include-ambiguous']);+ expect((await repair(engine, 'extractor-facts', ['--source', brain.sourceId, '--include-ambiguous', '--apply', '--expect', expectHash(preview)])).outcomes)+ .toEqual({ restored: 1 });+ expect(actors(await rowActors(engine, 'facts', 'source_id=$1', [brain.sourceId]))).toEqual([{ created: CREATOR_ACTOR, last: brain.maintenance }]);+ }+ }, 120_000);++ test('a calibration wave undo keeps the take creator and moves its last writer', async () => {+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ const page = await creatorPage(brain, 'people/kai-example');+ const wave = `wave-${brain.sourceId}`;+ await asCreator(engine, async tx => {+ await tx.addTakesBatch([{ page_id: page.id, row_num: 1, claim: 'Ships on time', kind: 'bet', holder: 'world', weight: 0.7 }]);+ await tx.executeRaw(`UPDATE takes SET resolved_at=now(), resolved_quality='correct', resolved_outcome=true, resolved_by='gbrain:grade_takes' WHERE page_id=$1`, [page.id]);+ });+ const [take] = await engine.executeRaw<{ id: number }>('SELECT id::int AS id FROM takes WHERE page_id=$1', [page.id]);+ await engine.executeRaw(`INSERT INTO take_grade_cache (take_id, prompt_version, judge_model_id, evidence_signature, verdict, confidence, applied, wave_version)+ VALUES ($1, 'v1', 'test:judge', 'sig', 'correct', 0.99, true, $2)`, [take.id, wave]);+ expect((await undoWave(engine, { waveVersion: wave })).resolutions_reverted).toBe(1);+ expect(actors(await rowActors(engine, 'takes', 'page_id=$1', [page.id]))).toEqual([{ created: CREATOR_ACTOR, last: brain.maintenance }]);+ }+ }, 120_000);++ test('the legacy sync soft delete, a capture tombstone and an extraction review advance their pages under the maintenance principal', async () => {+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ await creatorPage(brain, 'notes/sync-removed-example');+ expect(await softDeleteSyncPages(engine, ['notes/sync-removed-example'], { sourceId: brain.sourceId })).toEqual(['notes/sync-removed-example']);+ expect(await deletedRevisionActor(brain, 'notes/sync-removed-example')).toEqual(brain.maintenance);++ await creatorPage(brain, 'captures/tombstoned-example');+ const ingest = makeIngestCaptureHandler(engine);+ const result = await ingest({ data: { event: { source_id: brain.sourceId, source_kind: 'webhook', source_uri: 'test://tombstone', received_at: new Date().toISOString(),+ content_type: 'text/markdown', content: 'deleted', content_hash: createHash('sha256').update('deleted').digest('hex'), kind: 'tombstone', untrusted_payload: false, slug: 'captures/tombstoned-example' } } } as never);+ expect(result.status).toBe('deleted');+ expect(await deletedRevisionActor(brain, 'captures/tombstoned-example')).toEqual(brain.maintenance);++ const unverified = { provenance: 'auto-extracted', status: 'unverified' };+ await creatorPage(brain, 'people/promoted-example', unverified);+ await creatorPage(brain, 'people/rejected-example', unverified);+ const review = operationsByName['extraction_review']!;+ await review.handler(ctx(brain), { action: 'promote', slugs: ['people/promoted-example'] });+ await review.handler(ctx(brain), { action: 'reject', slugs: ['people/rejected-example'] });+ expect(await revisionActor(engine, brain.sourceId, 'people/promoted-example')).toEqual(brain.maintenance);+ expect(await deletedRevisionActor(brain, 'people/rejected-example')).toEqual(brain.maintenance);+ }+ }, 120_000);++ test('the conversation fact index writes derived facts under the maintenance principal on an unmanaged brain', async () => {+ for (const engine of engines) {+ const brain = await unmanagedBrain(engine);+ await creatorPage(brain, 'conversations/derived-example');+ const inserted = await writeDerivedFacts(engine, brain.sourceId, 'conversations/derived-example', db => db.insertFacts([{ fact: 'Bob books the venue',+ kind: 'commitment', entity_slug: 'people/bob-example', visibility: 'private', source: 'cli:extract-conversation-facts:sess', row_num: 1,+ source_markdown_slug: 'conversations/derived-example' } as never], { source_id: brain.sourceId }));+ expect(inserted.inserted).toBe(1);+ expect(actors(await rowActors(engine, 'facts', 'source_id=$1', [brain.sourceId]))).toEqual([{ created: brain.maintenance, last: brain.maintenance }]);+ }+ }, 120_000);+});