Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): B-14 streamed sync imports into the page recording the file's origin

garrytana45b13d4c6e6
diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.md
index 2e8a7a4958..cba4cec384 100644
--- a/docs/architecture/key-files/files-and-sync-2.md
+++ b/docs/architecture/key-files/files-and-sync-2.md
@@ -17,6 +17,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/repair/rename-identity.ts` — `gbrain repair rename-identity` (#6729), explicit-only, preview-bound, destructive. `plan` selects one open pair (`--slug`/`--from`), hashes `identityRemedyParts` (brain, pair, both page ids and revisions, disposition) and saves the approved set; with no pair named it lists the open pairs. On a managed brain a carry preview returns no items with `details.code: managed_remedy_unavailable` and the `--close` preview, and an apply refuses with that code. `carryIdentity` (classic only): one maintenance transaction under both page locks re-checks the hash, the open record and `fenceRowChecks`, merges matching fence rows onto the old rows, retires the provisional page under `purgedSlug`, moves the old page to the new slug (`updateSlug` redirect), moves the provisional's page-id rows (`movePageIdReferences`), imports the new file, settles the record `remedied`. `--close` settles `closed`. Refusals: `fact_rows_collide`, `managed_remedy_unavailable`, `changed_since_preview`, `preview_changed`, `invalid_params`.
- `src/core/persistence/sync-prescreen.ts` — #6712 PR 1 (L1): the discovery prescreen and drift baseline. After `discoverManagedSync` freezes identities, `prescreenSyncEntries` reads the pinned blobs (`readTreeBlobs`, one recursive listing for a large set) and the import provenance of every Git import of an existing page, and `classifyBaseline` marks each `prescreened` (disk blob, revision and `syncImportParserFor` fingerprint all match; bypassed under `--full` and for held paths) or `drift` (`database`: the page moved, the file did not; `both`/`unknown` in a tree walk or for a `file_drift` hold). A page whose current revision a committed managed-sync request wrote, or whose writer's publication wrote to its file (a write-through `git` effect), is not guarded (`fileBackedRevisions`), and drifted pages under `storage.keep_db` prefixes leave the manifest as drift candidates (`releaseKeepDbDrift`, `recordDriftSkip`). The run passes prescreened entries through `waivePrescreenedRun` (`sync-waivers.ts`); `freezeEntry` holds a drifted import `file_drift` (`fileDriftHold`, `sync-page-fault.ts`) unless `sameContentAtOrigin` proves it a no-op. `movedDriftHolds` re-screens drift holds whose page moved. Tests: `test/sync-prescreen-drift-6712.test.ts` (both engines).
- `src/core/persistence/sync-image.ts` — #6529: managed sync's image branch. With multimodal embedding on, `freezeEntry` (`sync-run.ts`) freezes an image entry as its bytes in base64 (`frozenImageIntent`; `rawHash` stays the file sha256, so the working-tree check and the hash no-op are unchanged) and `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncImage`, which runs `importImageFile` with `prepare` (the coordinated path `gbrain import` uses in `import-prepare.ts`): the importer decides the hash no-op, OCRs and embeds the image at preparation inside the sync budget (`--no-embed` skips both; the caption chunk's text vector is deferred to `embed --stale`), and the apply records `source_path`, releases the path's hold and re-reads the snapshot. A company plan refuses (`profile_incompatible`), a screening preparation (`sameContentAtOrigin`, the no-op waiver in `sync-waivers.ts` and `unchangedManagedImport` in `import-mutations.ts` return early for images) is refused rather than paid for, newer working-tree bytes or a vanished file refuse `source_changed`, and a Git rename publishes the new slug and soft-deletes the old page. `import-file.ts` records `source_path` on the legacy importer's hash-skip path too (`refreshSourcePath`), so no image import leaves it NULL. Tests: `test/managed-sync-images-5493.test.ts` (both engines), `test/embed-stale-images-managed-6529.test.ts`.
-- `src/core/persistence/sync-streamed.ts` — Wave B PR 2: managed sync of a Markdown file over the 24 MiB single-string ceiling. With `pages.segmented_storage` on, `freezeEntry` (`sync-run.ts`) freezes such a file by reference instead of holding it by its size: `streamedSyncBodyRef` hashes the sha256 and the Git blob id as a stream (sha1 or sha256 by the pinned commit's length) into `intent.body_ref` (`git_blob`, or `input_file` for an uncommitted working-tree file); the journal carries no content, and a committed entry whose working tree does not hold its pinned blob, a file over `pages.max_bytes` or a non-Markdown file is held as before. `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncStreamed`, which streams it through `importStreamedMarkdownFile` (`page-body/streamed-import.ts`, `coordinated`; `moved` on a rename keeps an implicit type following the new path) and publishes database-only; a rename moves the page first and re-seals an unchanged body (`sealSegmentedPage`). A file the streamed path refuses (a facts fence) fails its request with the refusal's code and the run holds it (`streamedRefusalHold` in `sync-screen.ts`); a dry run lists it in `screen_skipped` as `page_body_segmented`; `groupableIntent` (`sync-group.ts`) keeps it out of bulk groups. Tests: `test/large-pages/managed-sync-streamed.test.ts` (both engines), `managed-sync-streamed-crash.test.ts` (owner killed at `consumer:prepared`), `managed-sync-streamed-memory.slow.test.ts` (VmHWM).
+- `src/core/persistence/sync-streamed.ts` — Wave B PR 2: managed sync of a Markdown file over the 24 MiB single-string ceiling. With `pages.segmented_storage` on, `freezeEntry` (`sync-run.ts`) freezes such a file by reference instead of holding it by its size: `streamedSyncBodyRef` hashes the sha256 and the Git blob id as a stream (sha1 or sha256 by the pinned commit's length) into `intent.body_ref` (`git_blob`, or `input_file` for an uncommitted working-tree file); the journal carries no content, and a committed entry whose working tree does not hold its pinned blob, a file over `pages.max_bytes` or a non-Markdown file is held as before. `prepareManagedSyncMutation` (`sync-prepare.ts`) hands it to `prepareManagedSyncStreamed`, which streams it through `importStreamedMarkdownFile` (`page-body/streamed-import.ts`, `coordinated`; `moved` on a rename keeps an implicit type following the new path; `slug` is the admitted page, the one recording the file as its origin, as the inline import targets) and publishes database-only, recording the origin through `bindOrigin` (B-14: a renamed page keeping its origin takes the file, no twin at the path's slug); a rename moves the page first and re-seals an unchanged body (`sealSegmentedPage`). A file the streamed path refuses (a facts fence) fails its request with the refusal's code and the run holds it (`streamedRefusalHold` in `sync-screen.ts`); a dry run lists it in `screen_skipped` as `page_body_segmented`; `groupableIntent` (`sync-group.ts`) keeps it out of bulk groups. Tests: `test/large-pages/managed-sync-streamed.test.ts` (both engines), `managed-sync-streamed-crash.test.ts` (owner killed at `consumer:prepared`), `managed-sync-streamed-memory.slow.test.ts` (VmHWM), `streamed-sync-origin-b14.test.ts` (both engines).
- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `resolvePageWriteTarget(engine, slug, sourceId, { includeDeleted? })` (active rows by default; `includeDeleted: true` resolves a tombstone's recorded `source_path` for the purge remediation retry) is the exported single source of truth for the ONE file a (source, slug) pair lives in on disk: a source with its own `local_path` writes at that tree's ROOT (never nested under `.sources/`); a source without one nests under the host repo (`sync.repo_path`, default at root, non-default under `.sources/<id>/`) unless that path is another source's own working tree (leak guard → `source_repo_belongs_to_other_source`); the page's recorded `source_path` (or a contained absolute `file://` `source_uri`; a relative or host-only `file://` names no local file and is read as absent) is preferred over a slug-derived name so writes land in the file of record instead of minting a twin; and `isWriteTargetContained` rejects hostile rows escaping the tree (`path_escapes_source_root`). The ok-result also carries `sourcePathToBind` — the target expressed in the file scanner's `source_path` convention for the source's pinned `slug_root_mode` (or the mode its first sync would pin, via `scannerSlugRootMode`): GIT-ROOT-relative under `git-root` when the scan root sits inside a git repo, scan-root-relative under `source-root` and for non-git or git-root scan roots, so a put-born page binds the same form managed sync and delete-reconcile key on. Every recorded-path reader (write targets, takes, reconcile, audit, export restore, doctor) decodes with the same mode (`resolveSourceLocalFilePath(..., slugRootMode)`): under `source-root` the scope prefix is removed only from the legacy Git-root form whose remainder names the page slug, and basename rows resolve under the unstripped slug directory. The resolver is shared by `writePageThrough`, the facts fence writer (`src/core/facts/fence-write.ts`), and fence forget (`src/core/facts/forget.ts`) — the fence appends to the page's file, so all writers MUST compute the identical path or the fence lands in a file sync never reads back and the next extract_facts reconcile deletes the fence-owned DB rows. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?, expectedFileBytes?})` resolves the target through it, re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` so the brain has a committable artifact that round-trips through `gbrain sync`. Rendering from the row keeps the serialized content consistent at write time. The fsync-backed `atomicWriteFileSync` stages and renames the file after required source-path bookkeeping; lock/lease checks run before publication. `put_page` holds the root lock before importing and invokes write-through inside its database transaction, so ordinary filesystem rejection rolls back existing content, tags, chunks, and versions. A crash or database COMMIT failure after rename can still leave canonical Markdown ahead of the index; this is not distributed ACID or a durable queue. Never throws — returns `WriteThroughResult { written, path?, skipped?: 'disabled_by_config' | 'no_repo_configured' | 'repo_not_found' | 'source_repo_belongs_to_other_source' | 'page_not_found_after_write' | 'path_escapes_source_root' | 'case_insensitive_collision' | 'file_changed', warning?, error? }` (`file_changed`: the caller's `expectedFileBytes` preimage, null for absent, no longer matches the file under the source filesystem lock, so the file is left untouched) so the caller decides messaging + exit codes. `withNoRepoWriteThroughWarning(result, sourceId)` decorates an unwritten `no_repo_configured` result with `warning` (the write landed only in the database; bind the token/server to a git-backed source or configure `local_path`/`sync.repo_path`); `put_page` applies it for untrusted callers only (`ctx.remote !== false`), so local CLI responses and the `disabled_by_config` operator opt-out stay silent. `isWriteThroughDisabled` (shared with the fence lane, ~30s per-engine cache) honors the `sync.write_through` opt-out. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever; result carries `committed?: boolean`. Unhardened repos keep write-only behavior. `deletePageThrough(engine, slug, {sourceId?, target?, logger?})` is the delete-side sink (sole caller: the `delete_page` op): resolves the same target, unlinks the `.md`, and on a hardened repo best-effort commits the removal path-limited through the same helper with subject `gbrain: delete write-through <slug>`, reporting `committed?: boolean` on `DeleteThroughResult` (absent when unhardened or when the commit did not land — the unlink still stands; a never-committed page leaves nothing to commit, so no empty commit). Pinned by `test/delete-write-through-commit.test.ts`. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.test.ts`. The `put_page` op is that deciding caller for direct writes: a skip outside the deliberate DB-only set (`no_repo_configured`/`disabled_by_config`/`subagent_sandbox`/`dry_run`) throws `storage_error` inside the import transaction, rolling back the page revision, tags, chunks and version snapshot instead of deleting a just-created row afterward.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 16621013c6..04c5ffc542 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -901,6 +901,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', text: 'Upgrading builds the index `ingest_log_marked_idx` (migration v258): on Postgres online (`CREATE INDEX CONCURRENTLY`; reads and writes go on while it builds), on PGLite as a plain build that holds writes until it ends. It took 0.4 s for 1M `ingest_log` rows on Postgres and 0.5 s on PGLite. The segmented storage writer hold now judges every recent import, sync or connector run and resident process by its version, including those of a gbrain that already records reading segmented pages (v0.60.290.0), and the index keeps that read to the last 7 days of the log: 600 buffers on a 1M-row log, where a scan reads the whole table.' },
{ since: 'TBD', text: 'Upgrading builds the index `pages_segmented_body_bytes_idx` (migration v259) over pages stored in segments: on Postgres online (`CREATE INDEX CONCURRENTLY`), on PGLite as a plain build that holds writes until it ends. With it, the default `persistence.limits.worktree_recovery_bytes` also leaves room for the largest page already stored in segments, deleted pages included (while the index is not yet valid, a page at the engine ceiling, so no limit read scans `pages`): turning `pages.segmented_storage` off or lowering `pages.max_bytes` no longer makes a delete, restore or withdrawal mirror of such a page fail with `request_too_large` (a withdrawn row stayed in its file). A value you set is kept, and a request it cannot hold is refused with `request_too_large` naming both recovery budgets and the bytes it needed.' },
{ since: 'TBD', text: 'Doctor `segmented_storage` no longer tells you to upgrade this host when the only writes holding segmented storage off are this host\'s own from before its upgrade and the upgraded gbrain has since made the same kind of write (the same import or sync type, resident kind or managed principal), after the last of them: it reports the hold as information with the time it clears. Another host, an older `serve` or worker still running on this host, or an older write this build has not matched (a cron job or `npx` run on this host) keeps the warning and the `gbrain upgrade` fix.' },
+ { since: 'TBD', text: 'Managed sync of a Markdown file over 24 MiB whose origin another page records (a page renamed with its file) now imports it into that page, as for a smaller file, instead of failing it `revision_conflict` ("A different page already owns this file identity") and stopping the source\'s sync at it.' },
{ since: 'TBD', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },
];
diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.ts
index 3a00bd5796..5af17f0101 100644
--- a/src/core/page-body/streamed-import.ts
+++ b/src/core/page-body/streamed-import.ts
@@ -102,6 +102,8 @@ type StreamedImportOptions = {
* runs in the coordinator's publication transaction.
*/
coordinated?: { snapshot: PageSnapshot | null; owner: SegmentedStagingOwner; sha256: string;
+ /** The admitted page (a managed sync's `row.slug`): the page that records the file as its origin, which may differ from the path's slug. */
+ slug?: string;
/** A managed sync rename: `snapshot` is the page at its old slug, which the publication moves here first; an implicit type follows the new path. */
moved?: boolean;
prepare(prepared: StreamedPreparedImport): Promise<ImportResult> };
@@ -340,6 +342,7 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
slug = parsed.slug;
logSlugFallback(slug, relativePath, expectedSlug ? 'normalization-equivalent identity restore' : 'path slugified empty');
}
+ slug = opts.coordinated?.slug ?? slug;
if (hasGuardrails()) return hold(slug, size, 'a registered guardrail reads the whole payload');
if (scan.bodyFlags.has_nul) return hold(slug, size, 'NUL bytes change the stored size the content gate measures');
const drift = { changed: false };
diff --git a/src/core/persistence/sync-streamed.ts b/src/core/persistence/sync-streamed.ts
index 4189c7fd37..e559e4d12e 100644
--- a/src/core/persistence/sync-streamed.ts
+++ b/src/core/persistence/sync-streamed.ts
@@ -11,7 +11,10 @@
* rewritten). A file the streamed path refuses fails its request with the
* refusal's code, and the run holds it (`holdFailedFenceRequest`). A rename
* moves the page in the publication and applies the preparation made at the
- * new path.
+ * new path. The import targets the admitted page (`row.slug`, the page that
+ * records the file as its origin, as the inline import does), and the
+ * publication records the origin through `bindOrigin`; several live pages
+ * recording the file are held `origin_conflict` by discovery (#6948).
*/
import { createReadStream } from 'node:fs';
import { lstat } from 'node:fs/promises';
@@ -97,14 +100,12 @@ export async function prepareManagedSyncStreamed(engine: BrainEngine, row: Write
let ready: StreamedPreparedImport | undefined;
enterClaimStep(ctx.clock, 'import_content', undefined, 'fs');
const result = await importStreamedMarkdownFile(engine, filePath, p.sourcePath, { sourceId: row.source_id, noEmbed: true, ...(ctx.activePack ? { activePack: ctx.activePack } : {}),
- coordinated: { snapshot: base, sha256: ref.sha256, moved: !!renamed, prepare: async value => { ready = value; return value.result; },
+ coordinated: { snapshot: base, sha256: ref.sha256, slug: row.slug, moved: !!renamed, prepare: async value => { ready = value; return value.result; },
owner: { kind: 'sync', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: base?.revision ?? null } } }, stat, policy)
.catch(error => { throw error instanceof OperationError && error.code === 'source_changed' ? changed() : error; });
if (!ready) throw result.refusal ? ctx.contentRefusal(result.refusal) : refuse('invalid_params', result.error ?? 'The sync file could not be prepared.',
`The file could not be prepared as page ${row.slug}.`);
const prepared: StreamedPreparedImport = ready;
- if (prepared.slug !== row.slug) throw refuse('revision_conflict', 'A different page already owns this file identity; resolve the duplicate before syncing.',
- `Page ${prepared.slug} already holds the content identity of ${row.slug}; resolve the duplicate pages first.`);
if (prepared.observedRevision !== (base?.revision ?? null)) throw refuse('revision_conflict', 'The page changed during sync preparation.',
`Page ${renamed?.slug ?? row.slug} changed while this sync was being prepared.`);
const source = { sourceId: row.source_id };
diff --git a/test/large-pages/streamed-sync-origin-b14.test.ts b/test/large-pages/streamed-sync-origin-b14.test.ts
new file mode 100644
index 0000000000..06608ad02b
--- /dev/null
+++ b/test/large-pages/streamed-sync-origin-b14.test.ts
@@ -0,0 +1,140 @@
+/**
+ * B-14 (#6948 on the large-file path): managed sync of a Markdown file over the single-string ceiling whose origin is
+ * recorded by a page at another slug.
+ *
+ * 1. Protects: the streamed import targets the admitted page, the one that records the file as its origin (a page
+ * renamed with \`updateSlug\` keeps its old origin, B-1's fourth writer), as the inline import does; the publication
+ * records the origin through \`bindOrigin\`, so a live page at the path's own slug never becomes a second claimant,
+ * and the rest of the source syncs. Several live pages recording the file stay one \`origin_conflict\` hold of that
+ * file alone while the rest syncs (B-1's twins), with neither page written.
+ * 2. Fails when: the streamed writer refuses the file \`revision_conflict\` ("A different page already owns this file
+ * identity") and the run stops at it (\`blocked_by_failures\`, the other file not imported), imports it into the
+ * path's slug beside the page recording it (a twin), or writes into a twin.
+ *
+ * PGLite and, with DATABASE_URL, Postgres. Synthetic content only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { parseMarkdown } from '../../src/core/markdown.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { readGitSourceHolds } from '../../src/core/persistence/sync-holds.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { dropOriginIndex } from '../helpers/origin-index.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+import { reconstructedPage } from '../helpers/segmented-page-checks.ts';
+
+const huge = conversationPage(PAGE_MAX_BYTES + 1024 * 1024, { seed: 83 });
+const edited = `${huge.trimEnd()}\n\n**alice-example**: a closing streamed remark.\n`;
+const small = (body: string) => `---\ntitle: Small\n---\n${body}\n`;
+
+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
+function commit(root: string): void { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'synthetic content'); }
+
+for (const backend of testBackends()) describe(`[${backend}] B-14 streamed sync of a file another page records`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), `gbrain-b14-${backend}-`));
+ const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+ const write = (sourceId: string, fn: (tx: BrainEngine) => Promise<unknown>) => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+ const claimants = async (sourceId: string, origin: string) => (await engine.executeRaw<{ slug: string }>(
+ 'SELECT slug FROM pages WHERE source_id=$1 AND source_path=$2 AND deleted_at IS NULL ORDER BY slug', [sourceId, origin])).map(row => row.slug);
+ const row = async (sourceId: string, slug: string) => (await engine.executeRaw<{ compiled_truth: string; source_path: string | null; body_generation: string | null; revision: string }>(
+ 'SELECT compiled_truth, source_path, body_generation::text AS body_generation, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]))[0] ?? null;
+ const holds = async (sourceId: string) => (await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? [];
+
+ /** A managed Git source holding notes/huge.md (over the ceiling) and notes/small.md, synced once with the switch on. */
+ async function source() {
+ await disposePersistenceConsumer(engine);
+ const sourceId = `b14-${randomUUID().slice(0, 8)}`, root = join(home, sourceId);
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes/huge.md'), huge);
+ writeFileSync(join(root, 'notes/small.md'), small('A small note.'));
+ commit(root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ expect(await sync(sourceId)).toMatchObject({ status: 'first_sync', filesImported: 2 });
+ expect((await reconstructedPage(engine, 'notes/huge', sourceId)).page.body_storage).toBe('segmented');
+ return { sourceId, root };
+ }
+ /** One managed sync to a settled result: a streamed page outlasts a pass's bounded wait, as the drain's next pass picks it up. */
+ async function sync(sourceId: string) {
+ for (let pass = 0; ; pass++) {
+ const result = await performManagedSync(engine, { sourceId, noPull: true, noEmbed: true });
+ if (result.status !== 'partial' || result.reason !== 'writer_pending' || pass === 30) return result;
+ }
+ }
+ function editBoth(root: string) {
+ writeFileSync(join(root, 'notes/huge.md'), edited);
+ writeFileSync(join(root, 'notes/small.md'), small('A small note, edited.'));
+ commit(root);
+ }
+
+ beforeAll(async () => {
+ if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ else { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engine = pg.engine; closePostgres = pg.close; }
+ await engine.setConfig('pages.segmented_storage', 'on');
+ // Twins exist only on brains written before pages_live_origin_key, whose index is pending.
+ await dropOriginIndex(engine);
+ }, 120_000);
+ afterAll(async () => {
+ await withEnv(env, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); await closePostgres?.(); });
+ rmSync(home, { recursive: true, force: true });
+ }, 60_000);
+
+ test('a renamed page keeping its origin and a live page at the path\'s slug: the file streams into the page recording it, no twin, the rest syncs', async () => withEnv(env, async () => {
+ const f = await source();
+ await write(f.sourceId, tx => tx.updateSlug('notes/huge', 'archive/huge', { sourceId: f.sourceId }));
+ await write(f.sourceId, tx => tx.putPage('notes/huge', { type: 'note', title: 'At the path', compiled_truth: 'A page at the path, recording no file.', timeline: '', frontmatter: {},
+ content_hash: randomUUID() }, { sourceId: f.sourceId }));
+ expect(await claimants(f.sourceId, 'notes/huge.md')).toEqual(['archive/huge']);
+ editBoth(f.root);
+ const result = await sync(f.sourceId);
+ expect(result.failures ?? []).toEqual([]);
+ expect(result.status).toBe('synced');
+ expect((await row(f.sourceId, 'notes/small'))!.compiled_truth).toContain('A small note, edited.');
+ const parsed = parseMarkdown(edited, 'notes/huge.md');
+ const { page, body, hash } = await reconstructedPage(engine, 'archive/huge', f.sourceId);
+ expect(page.body_storage).toBe('segmented');
+ expect(body.compiled_truth).toBe(parsed.compiled_truth);
+ expect(page.content_hash).toBe(hash);
+ expect(await claimants(f.sourceId, 'notes/huge.md')).toEqual(['archive/huge']);
+ expect(await row(f.sourceId, 'notes/huge')).toMatchObject({ source_path: null, compiled_truth: 'A page at the path, recording no file.' });
+ expect(await holds(f.sourceId)).toEqual([]);
+ expect((await sync(f.sourceId)).status).not.toBe('blocked_by_failures');
+ }), 300_000);
+
+ test('regression: two live pages recording the file hold it origin_conflict alone, neither is written, and the rest syncs', async () => withEnv(env, async () => {
+ const f = await source();
+ await write(f.sourceId, async tx => {
+ await tx.putPage('notes/huge-copy', { type: 'note', title: 'Copy', compiled_truth: 'A copy.', timeline: '', frontmatter: {}, content_hash: randomUUID() }, { sourceId: f.sourceId });
+ // Legacy data: no writer records a held origin on a second page, so the twin's origin is set directly.
+ await tx.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [f.sourceId, 'notes/huge-copy', 'notes/huge.md']);
+ });
+ const before = { huge: await row(f.sourceId, 'notes/huge'), copy: await row(f.sourceId, 'notes/huge-copy') };
+ editBoth(f.root);
+ const result = await sync(f.sourceId);
+ expect(result.status).toBe('synced');
+ expect((await row(f.sourceId, 'notes/small'))!.compiled_truth).toContain('A small note, edited.');
+ const held = (await holds(f.sourceId)).filter(h => h.code === 'origin_conflict');
+ expect(held.map(h => [h.path, h.meta.canonical_slug])).toEqual([['notes/huge.md', 'notes/huge']]);
+ expect(await row(f.sourceId, 'notes/huge')).toEqual(before.huge);
+ expect(await row(f.sourceId, 'notes/huge-copy')).toEqual(before.copy);
+ expect(await claimants(f.sourceId, 'notes/huge.md')).toEqual(['notes/huge', 'notes/huge-copy']);
+ }), 300_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index fd45beb70b..f7feedb828 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -176,6 +176,7 @@ test/large-pages/segmented-versions.test.ts
test/large-pages/segmented-withdrawal-mirror.test.ts
test/large-pages/segmented-withdrawn-fence-delete.test.ts
test/large-pages/streamed-import-drift.test.ts
+test/large-pages/streamed-sync-origin-b14.test.ts
test/large-pages/stuck-recovery-large.slow.test.ts
test/large-pages/v252-master-reader-compat.test.ts
test/link-cross-source.test.ts