Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(connectors): a managed connector page turning private leaves Git HEAD (#7971 item 1)
garrytan6a75ec527b42
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 8f25bdc923..ab8a0fc979 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -6,7 +6,7 @@ The #6188 fence check and fence repair live in [fence repair](core-fence-repair.- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member in one budget (`sources.refresh_sync_budget_ms`; past it a member is `deferred`) (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target or descends from it, or with `outcome.sync_blocked` / `sync_deferred` when a member blocks or is deferred. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies` on every consumer topology scan) touches interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. #7679: each row records its holder (`outcome.holder`: host id, hostname, pid, process start; `previous_holder` after a recovery adopts it). A row whose lock is free is orphaned: `resumeWorktreeRefreshes` also completes an orphaned `syncing` row once every member's `last_commit` reached the target or a descendant, and a plain `gbrain sources refresh` on the owner host finishes any orphaned non-`recovery_required` row through the `--resume` path (`adoptOrphanedRefresh` + `resumeHeld`) before its own refresh, reporting it as `recovered`. A holder recorded on another host is never adopted. `refreshHolderReport` (writer status `worktree_refreshes`, sync status `worktree_refresh`) names the holder, `liveness` (`live` / `orphaned` / `unknown` off the lock's host) and a fix naming `--resume`. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command). Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts` (#7685: `--json` prints a refusal's structured `fix` when it has one; `refresh_in_progress` carries the writer-status read); while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), `test/worktree-refresh-orphan-7679.test.ts` (SIGKILL mid-syncing, live-holder no-steal), `test/oversize-hold-rescreen-8072.test.ts` (budget), Postgres via `test/e2e/worktree-refresh-*postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.- `src/core/persistence/git-gap.ts` + `src/commands/sources-git-gap.ts` + `src/commands/doctor/checks/db-ahead-of-git.ts` — git-canonical memory, wave G1 (`docs/designs/GIT_CANONICAL_MEMORY.md#the-git-gap-census`), read-only. `declaredDatabaseOnly` is the one predicate for pages that may not have a tracked file, tested in order: a read-only mirror source, a private page (`isPrivatePage`), an alias-private page (`isDerivationPrivate`), lineage-private (computed in SQL from `privatePagesFilterFragment`), `database_only_reason`, a `storage.db_only` prefix (`isSourceDbOnlySlug`, refusing an invalid gbrain.yml), a never-filed derive-phase page (page-prepare.ts `isNeverFiledDerivedPage`: no `source_path`/`source_uri` under `DERIVE_PHASE_DB_ONLY_DEFAULTS`), a path the checkout's Git ignores (`ignoredPaths`: filter-free `check-ignore -z --stdin`, tracked files never reported, exit 1 = none, null when Git cannot answer). The equality contract compares a committed blob with the page's export view (`readExportPage`, withdrawals overlaid; the census reads a batch's views with `readExportPages`, the same snapshots in two statements, #7617): an inline blob parsed as reconcile parses a canonical file, aligned with the stored type, subtype and #6429 stamp and compared by `reconcileCanonical` digest; a segmented page by the Git blob id of its streamed export. HEAD is read with hardened plumbing only (`readHeadTree`: one `ls-tree -r -l -z --full-tree` under the source's directory; `readBlobs`: `cat-file --batch` in calls of at most 64 MiB) and the working tree by hashing raw bytes (`worktreeBlobOid`), never `git status`/`git diff`, so no repository filter, textconv or fsmonitor runs. `gbrain sources git-gap <id> [--sample n] [--json]` (trusted local CLI, not an MCP op) puts every live page in one state (`equal`, `database_ahead`, `git_ahead` when the sync import record's `blob_oid`/`disk_blob_oid` differs from HEAD, else folded into `database_ahead` and counted in `database_ahead_without_import_record`, `declared_database_only` per class, `undeclared_database_only`, `worktree_only`, `unparseable`, `unsafe_path`), reports the working tree separately, and counts rows with no Git home (unfenced active facts, fenced facts on a missing page or a page without a committed file, links whose `link_source` is not in `DERIVED_LINK_SOURCES`, timeline rows on pages without a file), open `sync-hold` records by code and parked effect targets by kind and code. Each 256-page batch reads in its own read-only transaction. Doctor `db_ahead_of_git` runs the census per non-archived source whose directory is a Git checkout (others are only counted) under `GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS` (default 10 s) and the entry deadline; it is always `ok` (informational) and lists totals only, a source the budget stopped or never reached as partial. Tests: `test/git-gap-census.test.ts` (PGLite and Postgres).-- `src/core/persistence/git-declared.ts` + `src/core/persistence/git-canonical-schema.ts` (migration `git_canonical_declared`) — git-canonical memory, wave G7a: the declared database-only classes of a strict source (`sources.config.canonical = "git"`, default off). `strictPageClass` judges a page by its slug and prior file (`declaredPathClass`: `db_only_prefix` for a `storage.db_only` dir, `derive_folder` for a never-filed derive-phase page; G3's indexer reads the same function) and then its rendered content (`privacyClass`: `private`, `alias_private`, or `lineage_private` from the same SQL remote reads use, `privatePagesFilterFragment`, over the page's own values). `page-prepare.ts` `prepareFileTarget` asks it before it builds a strict file target: a declared page gets no target (no file, no door commit, no Git effect), an untracked ignored target is `git_ignored`, a page turning private gets the removal of the file it still has in the worktree or at HEAD, and a path whose `filter` attribute is `lfs` passes `assertLfsTarget` only with `storage.git_lfs` and a checkout that configures the LFS filter (`git_lfs_not_enabled`). `preparePrivateTransition` (page-prepare.ts) is that removal for other writers (GBRA-60). In `publishMutation` and `publishGroup`, `assertNoPrivateCommit` refuses a file target carrying a private page's bytes before anything is written (`git_private_commit_refused`; a group rolls back whole), and `declareStrictPublication` (after apply, before the door commit) refuses a declared page's file or an undeclared file-less page (`git_home_required`), stamps `pages.database_only_reason` and, for a privacy class, clears `source_path`/`source_uri` in the transaction of the door commit that removed the file. A managed import builds its own file target, so it meets only these publication checks. `assertStrictGitHome` is the refusal for writers with no file form yet (G4, G5). The managed writer guard (`writer-guard-schema.ts`) refuses rows of a strict source unless the writer declares `gbrain.git_protocol` (`withCoordinatedWrite` does), behind the `git_canonical_brain.strict_sources` counter kept by `sources` triggers (`git_protocol_required`, mapped in `publication-failure.ts`). The guard reads its state as the writing role and fails closed: a hidden or missing `persistence_brain` or `git_canonical_brain` row, or a source or page row hidden by row-level security, raises `writer_coordinator_required` (`managed_writer_guard:unreadable_state`), and the counter refuses a recount under RLS on `sources` (`test/writer-fence-fail-closed-7636.test.ts`). The census (`git-gap.ts`) adds `database_only_source` (a source with no checkout) and maps the stamped reasons to their own classes. Tests: `test/git-canonical-declared-g7a.test.ts` (both engines).+- `src/core/persistence/git-declared.ts` + `src/core/persistence/git-canonical-schema.ts` (migration `git_canonical_declared`) — git-canonical memory, wave G7a: the declared database-only classes of a strict source (`sources.config.canonical = "git"`, default off). `strictPageClass` judges a page by its slug and prior file (`declaredPathClass`: `db_only_prefix` for a `storage.db_only` dir, `derive_folder` for a never-filed derive-phase page; G3's indexer reads the same function) and then its rendered content (`privacyClass`: `private`, `alias_private`, or `lineage_private` from the same SQL remote reads use, `privatePagesFilterFragment`, over the page's own values). `page-prepare.ts` `prepareFileTarget` asks it before it builds a strict file target: a declared page gets no target (no file, no door commit, no Git effect), an untracked ignored target is `git_ignored`, a page turning private gets the removal of the file it still has in the worktree or at HEAD, and a path whose `filter` attribute is `lfs` passes `assertLfsTarget` only with `storage.git_lfs` and a checkout that configures the LFS filter (`git_lfs_not_enabled`). `preparePrivateTransition` (page-prepare.ts) is that removal for other writers (GBRA-60, connector imports #7971). In `publishMutation` and `publishGroup`, `assertNoPrivateCommit` refuses a file target carrying a private page's bytes before anything is written (`git_private_commit_refused`; a group rolls back whole), and `declareStrictPublication` (after apply, before the door commit) refuses a declared page's file or an undeclared file-less page (`git_home_required`), stamps `pages.database_only_reason` and, for a privacy class, clears `source_path`/`source_uri` in the transaction of the door commit that removed the file. A managed import builds its own file target, so it meets only these publication checks. `assertStrictGitHome` is the refusal for writers with no file form yet (G4, G5). The managed writer guard (`writer-guard-schema.ts`) refuses rows of a strict source unless the writer declares `gbrain.git_protocol` (`withCoordinatedWrite` does), behind the `git_canonical_brain.strict_sources` counter kept by `sources` triggers (`git_protocol_required`, mapped in `publication-failure.ts`). The guard reads its state as the writing role and fails closed: a hidden or missing `persistence_brain` or `git_canonical_brain` row, or a source or page row hidden by row-level security, raises `writer_coordinator_required` (`managed_writer_guard:unreadable_state`), and the counter refuses a recount under RLS on `sources` (`test/writer-fence-fail-closed-7636.test.ts`). The census (`git-gap.ts`) adds `database_only_source` (a source with no checkout) and maps the stamped reasons to their own classes. Tests: `test/git-canonical-declared-g7a.test.ts` (both engines).- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `page_body_segmented` is a write error code, so a verb refused by a segmented target keeps it as `write_error` and canonical code under the frozen `invalid_params` (caller class, not retryable) on both the receipt and the pre-admission path (`runMemoryWrite`). `remember` reads a segmented entity page up to PAGE_MAX_BYTES back whole (`materializedPage`) for its inferred-target checks and fence write; over it, a named or inferred entity refuses before admission with `segmentedRememberRefusal` (fix: remember with `infer_entity: false`), never a silent `NO_ENTITY` (`test/large-pages/segmented-remember-refusal.test.ts`); `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.- `src/core/persistence/database-write.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `ontology_propose` (one entity page key) uses it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys. Unmanaged brains keep the engine calls. Tests: `test/managed-ontology-propose.test.ts`.diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.tsindex 3cc1488d28..d38dbdfb02 100644--- a/src/core/persistence/connector-sync.ts+++ b/src/core/persistence/connector-sync.ts@@ -27,7 +27,7 @@ import { managedSyncAuthority, validateManagedSyncOptions, validateSyncAuthorityimport type { PreparedContentImport } from './prepared-import.ts';import { persistenceFileHash, type PreparedMutation } from './coordinator.ts';import { isTerminal, type WriteRequest } from './model.ts';-import { databaseOnlyPublication, prepareFileTarget } from './page-prepare.ts';+import { databaseOnlyPublication, prepareFileTarget, preparePrivateTransition } from './page-prepare.ts';import { sourceCanonicalGit } from './git-door.ts';import { isPrivatePage } from '../search/private-visibility.ts';import { assertPhysicalRoot } from './physical-root.ts';@@ -252,6 +252,19 @@ async function strictPrivateImport(engine: BrainEngine, sourceId: string, contenreturn isPrivatePage({ type: parsed.type, frontmatter }) && await sourceCanonicalGit(engine, sourceId);}+/**+ * #7971: the file target of a strict private import, or null when the import is not one. A page turning private (its+ * stored snapshot is live and public) gets the removal of the file it still has in the worktree or at HEAD, which the+ * door commits with the publication (G7a, preparePrivateTransition), so the public file leaves HEAD and no private byte+ * is committed. A page already private, or one without a file, publishes no file.+ */+async function strictPrivateFile(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, content: string, sourcePath: string,+ snapshot: PageSnapshot | null): Promise<{ file: PreparedMutation['file'] } | null> {+ if (!await strictPrivateImport(engine, row.source_id, content, sourcePath, snapshot)) return null;+ const turning = snapshot && !snapshot.page.deleted_at && !isPrivatePage({ type: snapshot.page.type, frontmatter: snapshot.page.frontmatter });+ return { file: turning ? await preparePrivateTransition(engine, row, snapshot) : undefined };+}+export async function beginConnectorSync(engine: BrainEngine, sourceId: string, connector: ConnectorKind,suppliedConfig: unknown, opts: SyncOpts & { resetCheckpoint?: boolean }, lease?: ConnectorLease): Promise<ManagedConnectorSync | null> {if (!await readManagedMode(engine)) return null;@@ -892,7 +905,7 @@ export class ManagedConnectorSync {if (kind === 'connector_v2_delete') {if (this.binding || prepared.noop !== true) return false;} else {- const databaseOnly = !this.binding || await strictPrivateImport(this.engine, this.sourceId, intent.content ?? '', sourcePath ?? `${slug}.md`, snapshot);+ const databaseOnly = !this.binding || !prepared.file && await strictPrivateImport(this.engine, this.sourceId, intent.content ?? '', sourcePath ?? `${slug}.md`, snapshot);const verdict = await inspectUnchanged(this.engine, { prepared, snapshot, sourcePath, databaseOnly });if (verdict.admitReason) return false;}@@ -916,9 +929,11 @@ export class ManagedConnectorSync {extra.googleReceipts = ownedGoogleReceipts(snapshot, (this.identity.config as GoogleSourceConfig).account, extra.googleReceipts!);sourcePath = snapshot!.page.source_path!;}- const file = kind === 'connector_v2_checkpoint' || kind === 'connector_v2_import' && sourcePath && typeof extra.content === 'string'- && await strictPrivateImport(this.engine, this.sourceId, extra.content, sourcePath, snapshot) ? undefined : await connectorFileTarget(this.engine,- { source_id: this.sourceId, worktree_id: this.binding?.worktree_id ?? null, slug }, snapshot, extra.content ?? null, sourcePath, this.canonicalRoot);+ const target = { source_id: this.sourceId, worktree_id: this.binding?.worktree_id ?? null, slug };+ const strictPrivate = kind === 'connector_v2_import' && sourcePath && typeof extra.content === 'string'+ ? await strictPrivateFile(this.engine, target, extra.content, sourcePath, snapshot) : null;+ const file = kind === 'connector_v2_checkpoint' ? undefined : strictPrivate ? strictPrivate.file+ : await connectorFileTarget(this.engine, target, snapshot, extra.content ?? null, sourcePath, this.canonicalRoot);if (file && sourcePath && resolve(file.path) !== resolve(this.canonicalRoot!, sourcePath)) {throw opError('source_changed', 'The connector source path no longer names its canonical file.',`The recorded path of ${slug} no longer resolves to its canonical file under the root of ${this.sourceId}, so nothing was submitted. Inspect the root and binding before running gbrain sync --source ${this.sourceId} again.`,@@ -1195,7 +1210,8 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteReconst project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, snapshot, 'preserving');const tags = [...new Set([...(snapshot?.tags ?? []), ...ready.parsedPage.tags])].sort();const page: Page = { ...(snapshot?.page ?? { id: 0, slug: row.slug, source_id: row.source_id, created_at: new Date(row.created_at), updated_at: new Date(row.created_at) }), ...ready.parsedPage };- const target = await strictPrivateImport(engine, row.source_id, p.content, p.sourcePath, snapshot) ? undefined+ const strictPrivate = await strictPrivateFile(engine, row, p.content, p.sourcePath, snapshot);+ const target = strictPrivate ? strictPrivate.file: await connectorFileTarget(engine, row, snapshot, serializePageToMarkdown(page, tags), p.sourcePath, p.canonicalRoot);// Google pages hold private mail: derived here from the stored connector, never submitted, so request ids are unchanged.const file = target && p.connector === 'google' ? { ...target, publishMode: 0o600 } : target;diff --git a/test/connector-private-transition-7971.test.ts b/test/connector-private-transition-7971.test.tsnew file mode 100644index 0000000000..46b2bd3531--- /dev/null+++ b/test/connector-private-transition-7971.test.ts@@ -0,0 +1,100 @@+/**+ * #7971 item 1: on a managed, Git-bound connector source that is strict (canonical: git), a page that turns private+ * leaves Git. A managed Google calendar sweep commits a world event's page through the door; when Google later marks the+ * event private, the next sweep publishes the commit that removes its file (G7a's private transition), so the file is+ * gone from HEAD and the working tree, the row is private and database-only, and the private text appears in no commit.+ * An event that was private from the start still writes no file, before and after. Before the fix the connector path+ * published the turning-private page database-only and left its public file committed at HEAD.+ * PGLite here; Postgres in test/e2e/connector-private-transition-7971-postgres.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';+import { completeBaselineSweep, googleConfig, json, options, withGoogleAccount } from './helpers/connector-fixture.ts';+import { git } from './helpers/git-publication.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { withEnv } from './helpers/with-env.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { initStrictCheckout, strictSource } from './helpers/strict-door-census.ts';++const config = { ...googleConfig, g_services: 'calendar' };+const PRIVATE_MARKER = 'turnedprivatemarkeracmeexample';+const at = Date.parse('2026-10-20T17:00:00Z');+const event = (id: string, summary: string, extra: Record<string, unknown> = {}) => ({ id, summary, status: 'confirmed',+ start: { dateTime: new Date(at).toISOString() }, end: { dateTime: new Date(at + 3_600_000).toISOString() }, ...extra });++interface Row { slug: string; source_path: string | null; withheld_source_path: string | null; reason: string | null; visibility: string | null }+const calendarRows = (engine: BrainEngine) => engine.executeRaw<Row>(+ `SELECT slug, source_path, withheld_source_path, database_only_reason AS reason, frontmatter->>'visibility' AS visibility+ FROM pages WHERE source_id='default' AND slug LIKE 'calendar/%' AND deleted_at IS NULL ORDER BY slug`);+const atHead = (root: string, path: string) => git(root, 'ls-tree', '--name-only', 'HEAD', '--', path).trim();++for (const backend of testBackends()) describe(`[${backend}] #7971: a connector page turning private on a strict Git-bound source`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ test('the public file leaves HEAD in the transition commit; no private text is committed; an always-private page writes no file', () => withEnv({ CONNECTOR_TEST_TOKEN: 'synthetic-local-fixture' }, () => managedBrain(async ({ engine, root }) => {+ await strictSource(engine);+ let events = [+ event('turning-event-a', 'Acme example planning', { updated: '2026-10-19T00:00:00Z' }),+ event('private-event-b', 'Bob example offsite', { visibility: 'private', updated: '2026-10-19T00:00:00Z' }),+ ];+ const calendarFetch = withGoogleAccount(async (url: string) => {+ if (url.includes('/settings/sendAs')) return json({ sendAs: [] });+ if (url.includes('/calendar/')) return json({ items: events, nextSyncToken: 'calendar-7971' });+ throw new Error('Unexpected external fixture route');+ });+ const run = () => runGoogleSync(engine, 'default', parseGoogleSourceConfig(config, root), options, calendarFetch);+ await completeBaselineSweep(engine, 'default', run);++ const first = await calendarRows(engine);+ expect(first).toHaveLength(2);+ const turning = first.find(row => row.slug.includes('acme-example-planning'))!;+ const alwaysPrivate = first.find(row => row.slug.includes('bob-example-offsite'))!;+ expect(turning.visibility).toBeNull();+ expect(turning.source_path).toBeTruthy();+ const path = turning.source_path!;+ expect(atHead(root, path)).toBe(path);+ expect(alwaysPrivate).toMatchObject({ visibility: 'private', source_path: null, reason: 'private' });+ expect(existsSync(join(root, `${alwaysPrivate.slug}.md`))).toBe(false);+ expect(atHead(root, `${alwaysPrivate.slug}.md`)).toBe('');++ events = [+ event('turning-event-a', 'Acme example planning', { visibility: 'private', description: `Agenda ${PRIVATE_MARKER} notes`, updated: '2026-10-21T00:00:00Z' }),+ event('private-event-b', 'Bob example offsite', { visibility: 'private', updated: '2026-10-19T00:00:00Z' }),+ ];+ await completeBaselineSweep(engine, 'default', run);++ const after = await calendarRows(engine);+ expect(after.map(row => row.slug)).toEqual(first.map(row => row.slug));+ expect(after.find(row => row.slug === turning.slug)).toMatchObject({ visibility: 'private', source_path: null, withheld_source_path: path, reason: 'private' });+ expect(atHead(root, path)).toBe('');+ expect(existsSync(join(root, path))).toBe(false);+ expect(git(root, 'log', '-p', '--all', '--format=%H %s').includes(PRIVATE_MARKER)).toBe(false);+ expect(git(root, 'log', '--diff-filter=D', '--name-only', '--format=', '--', path).trim()).toBe(path);+ expect(after.find(row => row.slug === alwaysPrivate.slug)).toMatchObject({ visibility: 'private', source_path: null, reason: 'private' });+ expect(existsSync(join(root, `${alwaysPrivate.slug}.md`))).toBe(false);+ expect(git(root, 'log', '--all', '--name-only', '--format=').includes(alwaysPrivate.slug)).toBe(false);+ expect(git(root, 'status', '--porcelain', '--untracked-files=all')).toBe('');++ // A changed re-render of the now-private page (its removed path kept as withheld_source_path) stays database-only.+ const headBefore = git(root, 'rev-parse', 'HEAD').trim();+ events = [+ event('turning-event-a', 'Acme example planning', { visibility: 'private', description: `Agenda ${PRIVATE_MARKER} revised`, updated: '2026-10-22T00:00:00Z' }),+ event('private-event-b', 'Bob example offsite', { visibility: 'private', description: `Offsite ${PRIVATE_MARKER} plan`, updated: '2026-10-22T00:00:00Z' }),+ ];+ await completeBaselineSweep(engine, 'default', run);+ const [rerendered] = await engine.executeRaw<{ body: string }>("SELECT compiled_truth AS body FROM pages WHERE source_id='default' AND slug=$1", [turning.slug]);+ expect(rerendered!.body).toContain(`${PRIVATE_MARKER} revised`);+ expect(git(root, 'rev-parse', 'HEAD').trim()).toBe(headBefore);+ expect(atHead(root, path)).toBe('');+ expect(existsSync(join(root, path))).toBe(false);+ expect(existsSync(join(root, `${alwaysPrivate.slug}.md`))).toBe(false);+ expect(git(root, 'log', '-p', '--all', '--format=%H %s').includes(PRIVATE_MARKER)).toBe(false);+ expect(git(root, 'status', '--porcelain', '--untracked-files=all')).toBe('');+ }, { databaseUrl, setup: async ({ engine, root }) => {+ initStrictCheckout(root);+ await engine.executeRaw("UPDATE sources SET config=$1::text::jsonb WHERE id='default'", [JSON.stringify(config)]);+ } })), 180_000);+});diff --git a/test/e2e/connector-private-transition-7971-postgres.test.ts b/test/e2e/connector-private-transition-7971-postgres.test.tsnew file mode 100644index 0000000000..f0b0c3b369--- /dev/null+++ b/test/e2e/connector-private-transition-7971-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../connector-private-transition-7971.test.ts'));