Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): store manifest digest and file count instead of the per-file map (#5790)
garrytande82243ab123
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex d55c4f9453..514b383454 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -59,7 +59,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot; exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.-- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres.+- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Stored worktree manifests and clone recovery records keep `digest`, `file_count`, `canonical_stamp` and `self_transfer` but no per-file map (#5790), so their size is independent of the worktree; `compactStoredManifest` drops a legacy map on rewrite, and transfer prepare/accept hash under the native lock before their transaction. Large-repo tests: `test/persistence-large-manifest.test.ts` (12k files, both engines via `test/e2e/persistence-large-manifest-postgres.test.ts`) and `test/e2e/persistence-large-manifest-50k.test.ts`. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres.- `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`; `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/manual-links.ts` — `coordinatedManualLinkWrite` makes `add_link` / `remove_link` coordinated database-only writes on a managed brain: it checks the caller's durable write authority for the `from` page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits the edge inside `withCoordinatedWrite` holding both endpoint page keys. Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`.diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.mdindex cbebae8705..3e0ac9e7df 100644--- a/docs/guides/concurrent-writes.md+++ b/docs/guides/concurrent-writes.md@@ -620,6 +620,20 @@ source; a stale remote is never accepted as recovery. Incomplete directoryreplacement blocks that root until its recorded recovery finishes. Neitherrecovery nor lifecycle administration reverses a committed fact withdrawal.+Large worktrees have no file-count bound. The stored manifest records the+content digest and `file_count`, not a per-file map, so `sources add`, `claim`,+`rebind`, `archive`, `remove`, clone, reclone and writer transfer work the same+at 50,000 files as at 50. Rows written by older releases, which also carry a+per-file map, stay valid and are compacted on their next rewrite. Every command+still hashes each file once while holding the root's native lock and before it+opens a database transaction; in human output it reports `files hashed of total`+on stderr for worktrees above 5,000 files. Measured on a 4-vCPU cloud machine+with a 50,000-file, 3.4 MB worktree: `sources add`, `claim` and transfer+prepare and accept each took under one second on PGLite and Postgres, with+peak RSS growth of about 100 MB on Postgres and 325 MB on PGLite+(`test/e2e/persistence-large-manifest-50k.test.ts`). Hashing time grows with+total bytes, not only file count.+Physical checkout identity lives in private durable markers in and beside theroot. Copies, replaced directories, and competing homes cannot claim that samepath as separate worktrees. Keep those markers: removing them does not grantdiff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex b81fd33413..77c45f5b6a 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -266,6 +266,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/derived-visibility-repair.test.ts","test/e2e/repair-command.test.ts","test/e2e/w5-persistence-postgres.test.ts",+ "test/e2e/persistence-large-manifest-postgres.test.ts",+ "test/e2e/persistence-large-manifest-50k.test.ts",],"src/core/brain-score-recommendations.ts": ["test/e2e/w5-persistence-postgres.test.ts"],"src/core/repair/**": ["test/e2e/repair-command.test.ts", "test/e2e/derived-visibility-repair.test.ts", "test/e2e/safe-chunk-reseal.test.ts", "test/e2e/recovery-layer.test.ts", "test/e2e/repair-contextual-mode-5621-postgres.test.ts", "test/e2e/fix-wave-3-integration.test.ts"],diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex caf60bc477..27d5f8e98e 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -8,7 +8,7 @@ import { isValidSourceId } from '../source-id.ts';import { assertValidSlugPrefixes } from '../grants/encoding.ts';import { isWriteRequestId } from './types.ts';import { writerDiagnostics } from './control.ts';-import { acceptWriterTransfer, claimWorktree, getWorktreeBinding, prepareWriterTransfer, worktreeManifest } from './ownership.ts';+import { acceptWriterTransfer, claimWorktree, getWorktreeBinding, humanManifestProgress, prepareWriterTransfer, worktreeManifest } from './ownership.ts';import { existingLocalHostId, currentVerifiedLocalWriter, persistenceHome, readLocalWriter, registerLocalWriter, revokeLocalWriter, type LocalGrant } from './identity.ts';import type { PersistenceAdminOperation } from './admin-contract.ts';import { operationScopesAllowed } from '../scope.ts';@@ -233,12 +233,12 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatioconst binding = await getWorktreeBinding(engine, sourceId, existingLocalHostId());if (!binding || binding.owner_host_id !== existingLocalHostId() || !binding.local_path) throw new OperationError('permission_denied', 'Only the current owner can prepare a transfer.');const { manifest } = await prepareWriterTransfer(engine, sourceId, existingLocalHostId()!, undefined, { selfTransfer: params.self_transfer === true, dryRun: true });- return { dry_run: true, action: operation, binding, manifest: { digest: manifest.digest, file_count: Object.keys(manifest.files).length } };+ return { dry_run: true, action: operation, binding, manifest: { digest: manifest.digest, file_count: manifest.file_count } };}const expectedState = await requireWriterAdminIntent(engine, operation, params);const prepared = await prepareWriterTransfer(engine, sourceId, undefined, expectedState, { selfTransfer: params.self_transfer === true });return { prepared: true, source_id: sourceId, worktree_id: prepared.worktree_id, owner_epoch: prepared.owner_epoch,- manifest: { digest: prepared.manifest.digest, file_count: Object.keys(prepared.manifest.files).length } };+ manifest: { digest: prepared.manifest.digest, file_count: prepared.manifest.file_count } };}if (operation === 'writer_transfer_accept') {keys(params, ['source_id', 'path', 'expected_epoch', 'manifest', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer']);@@ -249,7 +249,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatioif (typeof params.manifest !== 'string' || !/^[a-f0-9]{64}$/.test(params.manifest)) throw invalid('manifest must be the prepared SHA-256 manifest digest.');if (params.dry_run && params.self_transfer === true) await acceptWriterTransfer(engine, sourceId, root, params.expected_epoch, params.manifest, existingLocalHostId()!, undefined, { selfTransfer: true, dryRun: true });if (params.dry_run) return { dry_run: true, action: operation, source_id: sourceId, current: await getWorktreeBinding(engine, sourceId, existingLocalHostId()),- manifest_matches: worktreeManifest(root).digest === params.manifest, expected_epoch: params.expected_epoch };+ manifest_matches: worktreeManifest(root, { progress: humanManifestProgress() }).digest === params.manifest, expected_epoch: params.expected_epoch };const expectedState = await requireWriterAdminIntent(engine, operation, params);await acceptWriterTransfer(engine, sourceId, root, params.expected_epoch, params.manifest, undefined, expectedState, { selfTransfer: params.self_transfer === true });return { transferred: true, binding: await getWorktreeBinding(engine, sourceId) };diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.tsindex 53e212ef55..ce3e0f9607 100644--- a/src/core/persistence/ownership.ts+++ b/src/core/persistence/ownership.ts@@ -4,6 +4,8 @@ import { isAbsolute, join, relative, resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';import { discoverGitRoot } from '../sync-git.ts';+import { cliOptsToProgressOptions, getCliOptions } from '../cli-options.ts';+import { createProgress, type ProgressOptions } from '../progress.ts';import { digest, sha256 } from './digest.ts';import { localHostId, persistenceHome } from './identity.ts';import type { SqlEngine, WriteRequest } from './model.ts';@@ -153,30 +155,61 @@ export async function activateManagedPersistence(engine: BrainEngine, opts: { coawait activatePersistence(engine, opts);}-/** Deterministic content manifest includes deletions by exact path-set equality. */-export function worktreeManifest(root: string): { digest: string; files: Record<string, string> } {+export interface WorktreeManifest { digest: string; file_count: number }+export type StoredWorktreeManifest = WorktreeManifest & { canonical_stamp?: string; self_transfer?: PhysicalRootRecovery };+export const MANIFEST_PROGRESS_MIN_FILES = 5000;++/**+ * Deterministic content manifest includes deletions by exact path-set equality.+ * The per-file hash map stays local; stored manifests carry only its digest+ * and file count, so their size does not grow with the worktree.+ */+export function worktreeManifest(root: string, opts: { progress?: ProgressOptions } = {}): WorktreeManifest {const canonical = realpathSync(root);- const files: Record<string, string> = {};+ const paths: string[] = [];const visit = (dir: string) => {for (const name of readdirSync(dir).sort()) {if (name === '.git' || name === '.gbrain-managed' || isPhysicalRootMetadata(name)) continue;const path = join(dir, name), info = lstatSync(path);if (info.isSymbolicLink()) throw new OperationError('writer_manifest_unsafe', 'Canonical worktree transfer requires a symlink-free manifest.');if (info.isDirectory()) visit(path);- else if (info.isFile()) files[relative(canonical, path).split(sep).join('/')] = sha256(readFileSync(path));+ else if (info.isFile()) paths.push(path);}};visit(canonical);- return { digest: digest(files), files };+ const progress = opts.progress && paths.length > MANIFEST_PROGRESS_MIN_FILES ? createProgress(opts.progress) : undefined;+ progress?.start('sources.manifest_hash', paths.length);+ const files: Record<string, string> = {};+ for (const path of paths) {+ files[relative(canonical, path).split(sep).join('/')] = sha256(readFileSync(path));+ progress?.tick();+ }+ progress?.finish();+ return { digest: digest(files), file_count: paths.length };+}++/** Human-mode progress for manifest hashing; JSON and quiet modes report nothing. */+export function humanManifestProgress(): ProgressOptions | undefined {+ const options = cliOptsToProgressOptions(getCliOptions());+ return options.mode === 'auto' ? options : undefined;+}++/** Drops a legacy per-file map from a stored manifest, keeping every other field. */+export function compactStoredManifest<T extends { digest: string; files?: Record<string, string>; file_count?: number }>(manifest: T): Omit<T, 'files'> & { file_count: number } {+ const { files, ...rest } = manifest;+ return { ...rest, file_count: rest.file_count ?? Object.keys(files ?? {}).length };}export async function prepareWriterTransfer(engine: BrainEngine, sourceId: string, hostId = localHostId(), expectedAdminState?: string,- opts: { selfTransfer?: boolean; dryRun?: boolean } = {}): Promise<{ worktree_id: string; owner_epoch: string; manifest: ReturnType<typeof worktreeManifest> }> {+ opts: { selfTransfer?: boolean; dryRun?: boolean } = {}): Promise<{ worktree_id: string; owner_epoch: string; manifest: StoredWorktreeManifest }> {const binding = await getWorktreeBinding(engine, sourceId, hostId);if (!binding || binding.owner_host_id !== hostId || !binding.local_path) throw new OperationError('permission_denied', 'Only the current owner can prepare this transfer.');if (!binding.coordination_path) throw new OperationError('recovery_required', 'The recorded coordination path is missing.');const lock = opts.selfTransfer ? await acquireNativeLock(binding.coordination_path, { timeoutMs: 5000 }) : await acquireWorktree(binding, 5000);if (!lock) throw new OperationError('write_pending', 'The worktree is busy; retry transfer preparation.');try {+ // The native lock already excludes writers, so hash before checking out a+ // connection. A hashing failure surfaces after the root checks below, as before.+ const hashed = (() => { try { return worktreeManifest(binding.local_path!, { progress: humanManifestProgress() }); } catch (error) { return error as Error; } })();return await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");await assertWriterAdminState(tx, expectedAdminState);@@ -193,7 +226,8 @@ export async function prepareWriterTransfer(engine: BrainEngine, sourceId: strinconst recovery = opts.selfTransfer ? inspectPhysicalRootRecovery(binding.local_path!, { brainId: brain.brain_id,worktreeId: binding.worktree_id, hostId, coordinationPath: binding.coordination_path! }) : undefined;if (!opts.selfTransfer) assertPhysicalRoot(binding.local_path!, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path });- const manifest = { ...worktreeManifest(binding.local_path!), ...(recovery ? { self_transfer: recovery } : {}) };+ if (hashed instanceof Error) throw hashed;+ const manifest: StoredWorktreeManifest = { ...hashed, ...(recovery ? { self_transfer: recovery } : {}) };if (!opts.dryRun) await tx.executeRaw(`UPDATE persistence_worktrees SET state='draining',manifest=$2::text::jsonb WHERE id=$1::uuid`, [binding.worktree_id, JSON.stringify(manifest)]);return { worktree_id: binding.worktree_id, owner_epoch: String(owner.owner_epoch), manifest };});@@ -202,8 +236,6 @@ export async function prepareWriterTransfer(engine: BrainEngine, sourceId: strinexport async function acceptWriterTransfer(engine: BrainEngine, sourceId: string, path: string, expectedEpoch: string, expectedManifest: string, hostId = localHostId(), expectedAdminState?: string,opts: { selfTransfer?: boolean; dryRun?: boolean } = {}): Promise<void> {const root = realpathSync(resolve(path));- const manifest = worktreeManifest(root);- if (manifest.digest !== expectedManifest) throw new OperationError('writer_manifest_mismatch', 'Successor checkout differs from the recorded canonical manifest.');const binding = await getWorktreeBinding(engine, sourceId, hostId);if (!binding) throw new OperationError('not_found', 'Source has no worktree owner.');if (opts.selfTransfer && binding.owner_host_id !== hostId) throw new OperationError('permission_denied', 'Self-transfer requires the current owner host.');@@ -213,6 +245,8 @@ export async function acceptWriterTransfer(engine: BrainEngine, sourceId: stringconst lock = await acquireNativeLock(coordination, { timeoutMs: 5000 });if (!lock) throw new OperationError('write_pending', 'Successor worktree is busy.');try {+ if (worktreeManifest(root, { progress: humanManifestProgress() }).digest !== expectedManifest)+ throw new OperationError('writer_manifest_mismatch', 'Successor checkout differs from the recorded canonical manifest.');await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");await assertWriterAdminState(tx, expectedAdminState);@@ -222,7 +256,7 @@ export async function acceptWriterTransfer(engine: BrainEngine, sourceId: stringif (!!owner.manifest.self_transfer !== !!opts.selfTransfer || JSON.stringify(await getWorktreeBinding(tx, sourceId, hostId)) !== JSON.stringify(binding)) throw new OperationError('writer_transfer_conflict', 'The prepared transfer mode or binding changed.');const pending = await tx.executeRaw(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND (state IN ('running','recovering') OR recovery IS NOT NULL) LIMIT 1`, [binding.worktree_id]);const mirrors = await tx.executeRaw('SELECT id FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1', [binding.worktree_id]);- if (pending.length || mirrors.length || worktreeManifest(root).digest !== expectedManifest) throw new OperationError('recovery_required', 'Transfer state changed; prepare again.');+ if (pending.length || mirrors.length) throw new OperationError('recovery_required', 'Transfer state changed; prepare again.');if (opts.selfTransfer) repairPhysicalRoot(root, owner.manifest.self_transfer!, { hostId, worktreeId: binding.worktree_id, coordinationPath: coordination }, opts.dryRun);else if (!opts.dryRun) await preparePhysicalRootTransfer(tx, root, { hostId, worktreeId: binding.worktree_id, coordinationPath: coordination, expectedEpoch });if (opts.dryRun) return;diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.tsindex d3330eaccf..4f074d811d 100644--- a/src/core/persistence/source-lifecycle.ts+++ b/src/core/persistence/source-lifecycle.ts@@ -9,7 +9,7 @@ import { parseSourceConfig } from '../sources-load.ts';import { redactSourceConfig } from '../source-config-redact.ts';import { discoverGitRoot } from '../sync-git.ts';import { isInsideGitRepo, hasTrackedContent } from '../git-remote.ts';-import { containsPath, getWorktreeBinding, type WorktreeBinding, worktreeManifest } from './ownership.ts';+import { containsPath, getWorktreeBinding, humanManifestProgress, type WorktreeBinding, type WorktreeManifest, worktreeManifest } from './ownership.ts';import { localHostId } from './identity.ts';import { advanceTopology, lockTopologyPrincipal, lockTopologyRows, settleTopologyRequests, topologyCanonicalStamp, topologyPrincipal, withTopologyLocks } from './topology-locks.ts';import { priorTopologyChange, recordTopologyChange, topologyReceipt } from './topology-receipts.ts';@@ -104,10 +104,10 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLreturn withTopologyLocks(engine,input.sourceId,async bindings=>{// Hash canonical bytes while holding native exclusion, without a database// connection checked out. The final transaction rejects new pending mirrors.- const manifests=new Map<string,ReturnType<typeof worktreeManifest>>();+ const manifests=new Map<string,WorktreeManifest>();for(const path of new Set([...bindings.map(binding=>binding.local_path!).filter(Boolean),...(root?[root.worktree]:[])])) {if(!existsSync(path)) {if(input.operation==='add'&&input.createDirectory&&path===root?.worktree)continue;throw new OperationError('recovery_required','The canonical checkout is missing; restore its verified manifest first.');}- const manifest=worktreeManifest(path);+ const manifest=worktreeManifest(path,{progress:humanManifestProgress()});if(Buffer.byteLength(JSON.stringify(manifest))>1_048_576) throw new OperationError('request_too_large','The verified source manifest exceeds the 1 MiB administration metadata bound.');manifests.set(path,manifest);}diff --git a/src/core/persistence/topology-clone-model.ts b/src/core/persistence/topology-clone-model.tsindex 7644fa95ee..498818e382 100644--- a/src/core/persistence/topology-clone-model.ts+++ b/src/core/persistence/topology-clone-model.ts@@ -3,7 +3,7 @@ export interface TopologyCloneRecovery {version:1;kind:'clone';phase:'reserved'|'prepared'|'aborting';operation:'add'|'reclone';sourceId:string;incarnation:string;worktreeId:string;ownerHostId:string;ownerEpoch:string;target:string;stage:string;aside:string;beforeHash:string|null;afterHash:string|null;- manifest:{digest:string;files:Record<string,string>;canonical_stamp?:string}|null;+ manifest:{digest:string;file_count?:number;files?:Record<string,string>;canonical_stamp?:string}|null;canonicalStamp:string;checkpoint:string|null;sourceRemoteUrl:string|null;input:SourceLifecycleInput;cloneBudget:number;stageIdentity?:{device:string;inode:string;birthNs:string};failureCode?:string;}diff --git a/src/core/persistence/topology-clone.ts b/src/core/persistence/topology-clone.tsindex ef06c5d9a5..2777f2511a 100644--- a/src/core/persistence/topology-clone.ts+++ b/src/core/persistence/topology-clone.ts@@ -9,7 +9,7 @@ import { isOwnedClone } from '../sources-ops.ts';import { parseSourceConfig } from '../sources-load.ts';import type { SourceLifecycleInput } from './source-lifecycle.ts';import type { TopologyCloneRecovery } from './topology-clone-model.ts';-import { getWorktreeBinding, worktreeManifest } from './ownership.ts';+import { compactStoredManifest, getWorktreeBinding, humanManifestProgress, worktreeManifest } from './ownership.ts';import { localHostId, persistenceHome } from './identity.ts';import { acquireNativeLock, type NativeLockHandle } from './native-lock.ts';import { canonicalFilesystemPath, recordManagedRoots } from './root-registry.ts';@@ -59,7 +59,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifecif(!bindings.some(binding=>binding.worktree_id===worktreeId)){newLock=await acquireNativeLock(coordination!,{timeoutMs:5000});if(!newLock)throw new OperationError('writer_lock_unavailable','The new clone coordination lock is busy.');}let accepted:TopologyChange|undefined;try{- const before=existsSync(target)?worktreeManifest(target):null;+ const before=existsSync(target)?worktreeManifest(target,{progress:humanManifestProgress()}):null;const limits=await readJournalLimits(engine);const reserved=Math.min(limits.worktreeRecoveryBytes,limits.brainRecoveryBytes);const oldBytes=existsSync(target)?await topologyDirectoryBytes(target,reserved):0;@@ -86,7 +86,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifecconst incarnation=source?.incarnation??randomUUID();let canonicalStamp=currentBinding?await topologyCanonicalStamp(tx,worktreeId):'';const [owner]=currentBinding?await tx.executeRaw<{manifest:TopologyCloneRecovery['manifest']}>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid',[worktreeId]):[];- const manifest=before?{...before,canonical_stamp:canonicalStamp}:owner?.manifest??null;+ const manifest=before?{...before,canonical_stamp:canonicalStamp}:owner?.manifest?compactStoredManifest(owner.manifest):null;if(input.operation==='reclone'&&(!manifest||manifest.canonical_stamp!==canonicalStamp))throw new OperationError('recovery_required','The missing checkout has no current verified canonical manifest. Recover it from a verified checkpoint before recloning.');if(manifest&&Buffer.byteLength(JSON.stringify(manifest))>1_048_576)throw new OperationError('request_too_large','The canonical manifest exceeds the 1 MiB recovery metadata bound.');@@ -125,7 +125,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec});await (hooks.clone??cloneTopologyCheckout)(url,recovery.stage,recovery.cloneBudget);const stageBytes=await topologyDirectoryBytes(recovery.stage,recovery.cloneBudget);- const candidate=worktreeManifest(recovery.stage);+ const candidate=worktreeManifest(recovery.stage,{progress:humanManifestProgress()});if(Buffer.byteLength(JSON.stringify(candidate))>1_048_576)throw new OperationError('request_too_large','The cloned canonical manifest exceeds its 1 MiB recovery metadata bound.');if(recovery.manifest&&candidate.digest!==recovery.manifest.digest)throw new OperationError('writer_manifest_mismatch','The cloned checkout differs from the verified canonical manifest, including deletions.');flushTopologyTree(recovery.stage);flushTopologyDirectory(dirname(recovery.stage));diff --git a/src/core/persistence/topology-recovery.ts b/src/core/persistence/topology-recovery.tsindex 68c59982ef..f9a17ed68f 100644--- a/src/core/persistence/topology-recovery.ts+++ b/src/core/persistence/topology-recovery.ts@@ -7,7 +7,7 @@ import { parseSourceConfig } from '../sources-load.ts';import { canonicalFilesystemPath } from './root-registry.ts';import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots, withFilesystemPublication } from './filesystem-guard.ts';import { localHostId } from './identity.ts';-import { worktreeManifest } from './ownership.ts';+import { compactStoredManifest, worktreeManifest } from './ownership.ts';import { advanceTopology, lockTopologyPrincipal, settleTopologyRequests, topologyCanonicalStamp, withTopologyLocks } from './topology-locks.ts';import { withCoordinatedWrite } from './context.ts';import { releaseTopologyReservation, type TopologyChange } from './topology-receipts.ts';@@ -148,7 +148,7 @@ export async function finishTopologyClone(engine:BrainEngine,id:string,hooks:Cloelse await tx.executeRaw('UPDATE sources SET last_commit=NULL,last_sync_at=NULL WHERE id=$1 AND incarnation=$2::uuid',[record.sourceId,record.incarnation]);});await advanceTopology(tx,[record.worktreeId]);- await tx.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid',[record.worktreeId,JSON.stringify({...record.manifest,canonical_stamp:await topologyCanonicalStamp(tx,record.worktreeId)})]);+ await tx.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid',[record.worktreeId,JSON.stringify({...(record.manifest?compactStoredManifest(record.manifest):null),canonical_stamp:await topologyCanonicalStamp(tx,record.worktreeId)})]);await refreshManagedFilesystemRoots(tx,managedFilesystemDatastorePath(engine));await tx.executeRaw("UPDATE persistence_topology_changes SET state='committed',outcome=outcome||$2::text::jsonb,updated_at=now() WHERE id=$1::uuid",[row.id,JSON.stringify({cloned:true,local_path:record.target})]);diff --git a/test/e2e/persistence-large-manifest-50k.test.ts b/test/e2e/persistence-large-manifest-50k.test.tsnew file mode 100644index 0000000000..0444584c19--- /dev/null+++ b/test/e2e/persistence-large-manifest-50k.test.ts@@ -0,0 +1,91 @@+/**+ * #5790 scale record: a 50,000-file worktree on both engines. Records the+ * duration and peak RSS of `sources add`, `claim` and writer transfer prepare+ * and accept with the fixture's total bytes. No duration gate (DX-O10); the+ * stored manifest and peak RSS growth carry ceilings set from measurement.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { cpSync, mkdtempSync, rmSync } from 'node:fs';+import { basename, join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { isPhysicalRootMetadata } from '../../src/core/persistence/physical-root.ts';+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { claimWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';+import { runManagedSourceLifecycle } from '../../src/core/persistence/source-lifecycle.ts';+import { runPersistenceAdministration } from '../../src/core/persistence/administration.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { requirePostgresTestDatabase } from '../helpers/test-backends.ts';+import { reviewedWriterIntent } from '../helpers/writer-admin-intent.ts';+import { withEnv } from '../helpers/with-env.ts';+import { writeLargeWorktree } from '../helpers/large-worktree.ts';++const FILES = 50_000;+const STORED_MANIFEST_CEILING_BYTES = 4096;+const PEAK_RSS_GROWTH_CEILING_MB = 1024;+const databaseUrl = requirePostgresTestDatabase();+const directory = mkdtempSync(join(tmpdir(), 'gbrain-50k-manifest-'));+const template = join(directory, 'template');+let totalBytes = 0;+beforeAll(() => { totalBytes = writeLargeWorktree(template, FILES); }, 300_000);+afterAll(() => rmSync(directory, { recursive: true, force: true }), 300_000);++const peakRssMb = () => process.resourceUsage().maxRSS / 1024;+async function measured<T>(run: () => Promise<T>): Promise<{ value: T; ms: number; peak_rss_mb: number }> {+ const started = performance.now();+ const value = await run();+ return { value, ms: Math.round(performance.now() - started), peak_rss_mb: Math.round(peakRssMb()) };+}+const copy = (to: string) => cpSync(template, to, { recursive: true, filter: path => !isPhysicalRootMetadata(basename(path)) });++for (const backend of ['postgres', 'pglite'] as const) describe(`50,000-file worktree (${backend})`, () => {+ let engine: BrainEngine;+ let close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 120_000);+ afterAll(async () => { if (!engine) return; await disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); });++ test('sources add, claim and writer transfer commit with a compact manifest', async () => {+ const home = join(directory, backend);+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ await registerLocalWriter(engine, 'cli');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const rssBefore = peakRssMb();+ const added = join(home, 'added'), claimed = join(home, 'claimed'), successor = join(home, 'successor');+ copy(added); copy(claimed); copy(successor);+ const add = await measured(() => runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'scale-added', path: added }));+ expect(add.value).toMatchObject({ state: 'committed' });+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");+ await tx.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['scale-claimed', claimed]);+ });+ const claim = await measured(() => claimWorktree(engine, 'scale-claimed', claimed));+ const administer = async (operation: 'writer_transfer_prepare' | 'writer_transfer_accept', params: Record<string, unknown>) =>+ runPersistenceAdministration(engine, operation, { ...params, ...await reviewedWriterIntent(engine, operation) }) as Promise<any>;+ const prepare = await measured(() => administer('writer_transfer_prepare', { source_id: 'scale-claimed' }));+ expect(prepare.value.manifest.file_count).toBe(FILES);+ const accept = await measured(() => administer('writer_transfer_accept', { source_id: 'scale-claimed', path: successor,+ expected_epoch: prepare.value.owner_epoch, manifest: prepare.value.manifest.digest }));+ expect(accept.value).toMatchObject({ transferred: true });+ expect((await getWorktreeBinding(engine, 'scale-claimed'))!.local_path).toBe(successor);+ const rows = await engine.executeRaw<{ manifest: unknown }>('SELECT manifest FROM persistence_worktrees WHERE manifest IS NOT NULL');+ expect(rows).toHaveLength(2);+ for (const { manifest } of rows) {+ const stored = typeof manifest === 'string' ? JSON.parse(manifest) : manifest as Record<string, unknown>;+ expect(stored).toMatchObject({ file_count: FILES });+ expect(stored.files).toBeUndefined();+ expect(Buffer.byteLength(JSON.stringify(stored))).toBeLessThan(STORED_MANIFEST_CEILING_BYTES);+ }+ const record = { backend, files: FILES, total_bytes: totalBytes,+ add: { ms: add.ms, peak_rss_mb: add.peak_rss_mb }, claim: { ms: claim.ms, peak_rss_mb: claim.peak_rss_mb },+ transfer_prepare: { ms: prepare.ms, peak_rss_mb: prepare.peak_rss_mb }, transfer_accept: { ms: accept.ms, peak_rss_mb: accept.peak_rss_mb },+ peak_rss_growth_mb: Math.round(peakRssMb() - rssBefore) };+ console.log(`[5790-scale] ${JSON.stringify(record)}`);+ expect(record.peak_rss_growth_mb).toBeLessThan(PEAK_RSS_GROWTH_CEILING_MB);+ });+ }, 600_000);+});diff --git a/test/e2e/persistence-large-manifest-postgres.test.ts b/test/e2e/persistence-large-manifest-postgres.test.tsnew file mode 100644index 0000000000..5521dc5f7b--- /dev/null+++ b/test/e2e/persistence-large-manifest-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../persistence-large-manifest.test.ts'));diff --git a/test/helpers/large-worktree.ts b/test/helpers/large-worktree.tsnew file mode 100644index 0000000000..b63bc70ee8--- /dev/null+++ b/test/helpers/large-worktree.ts@@ -0,0 +1,33 @@+import { execFileSync } from 'node:child_process';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';++/**+ * Writes `count` small Markdown files under `root` with realistic path lengths,+ * so a per-file manifest map passes the 1 MiB metadata bound near 10k files.+ * Returns the total content bytes written.+ */+export function writeLargeWorktree(root: string, count: number): number {+ let bytes = 0;+ for (let i = 0; i < count; i++) {+ const dir = join(root, 'notes', `batch-${String(Math.floor(i / 500)).padStart(3, '0')}`);+ if (i % 500 === 0) mkdirSync(dir, { recursive: true });+ const body = `---\ntitle: Example ${i}\ntype: note\n---\n\nGeneric example body ${i}.\n`;+ writeFileSync(join(dir, `example-note-${String(i).padStart(6, '0')}.md`), body);+ bytes += Buffer.byteLength(body);+ }+ return bytes;+}++/** Commits a large worktree and returns a local bare repository cloned from it. */+export function largeBareRepository(directory: string, count: number): string {+ const work = join(directory, 'bare-work'), bare = join(directory, 'large.git');+ mkdirSync(work, { recursive: true });+ writeLargeWorktree(work, count);+ const git = (cwd: string, args: string[]) => execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=t', ...args], { cwd, stdio: 'ignore' });+ git(work, ['init', '--quiet']);+ git(work, ['add', '-A']);+ git(work, ['commit', '--quiet', '-m', 'fixture']);+ git(directory, ['clone', '--quiet', '--bare', work, bare]);+ return bare;+}diff --git a/test/persistence-large-manifest.test.ts b/test/persistence-large-manifest.test.tsnew file mode 100644index 0000000000..a7935e465e--- /dev/null+++ b/test/persistence-large-manifest.test.ts@@ -0,0 +1,174 @@+/**+ * #5790: stored worktree manifests carry a digest and a file count instead of+ * the per-file map, so brains past ~10k files can be added, claimed, rebound,+ * archived, removed, cloned, recloned and transferred.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { cpSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';+import { basename, join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { isPhysicalRootMetadata } from '../src/core/persistence/physical-root.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { claimWorktree, getWorktreeBinding, worktreeManifest } from '../src/core/persistence/ownership.ts';+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';+import { runManagedSourceClone } from '../src/core/persistence/topology-clone.ts';+import { topologyPrincipal } from '../src/core/persistence/topology-locks.ts';+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';+import { largeBareRepository, writeLargeWorktree } from './helpers/large-worktree.ts';++const FILES = 12_000;+const REMOTE = 'https://example.invalid/large-brain.git';++for (const backend of testBackends()) describe(`large worktree manifests (${backend})`, () => {+ let engine: BrainEngine;+ let close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 120_000);+ afterAll(async () => { if (!engine) return; await disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); });++ async function fixture(run: (home: string) => Promise<void>) {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-large-manifest-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ await resetPgliteState(engine as PGLiteEngine);+ await registerLocalWriter(engine, 'cli');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try { await run(home); } finally { await disposePersistenceConsumer(engine); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+ }+ async function storedManifest(sourceId: string) {+ const [row] = await engine.executeRaw<{ manifest: Record<string, unknown> | string | null }>(`SELECT w.manifest FROM persistence_worktrees w+ JOIN persistence_source_bindings b ON b.worktree_id=w.id WHERE b.source_id=$1`, [sourceId]);+ return typeof row?.manifest === 'string' ? JSON.parse(row.manifest) : row?.manifest ?? null;+ }+ async function expectCompact(sourceId: string, root: string, count = FILES) {+ const manifest = await storedManifest(sourceId);+ expect(manifest).toMatchObject({ digest: worktreeManifest(root).digest, file_count: count });+ expect(manifest.files).toBeUndefined();+ expect(Buffer.byteLength(JSON.stringify(manifest))).toBeLessThan(4096);+ return manifest;+ }+ const insertSource = (id: string, path: string) => engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");+ await tx.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, path]);+ });+ const copyWorktree = (from: string, to: string) => cpSync(from, to, { recursive: true, filter: path => !isPhysicalRootMetadata(basename(path)) && basename(path) !== '.git' });++ test('a 12k-file source can be added, claimed, rebound, archived, restored and removed', () => fixture(async home => {+ const root = join(home, 'added');+ writeLargeWorktree(root, FILES);+ expect(await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'large-added', path: root })).toMatchObject({ state: 'committed' });+ await expectCompact('large-added', root);++ const claimed = join(home, 'claimed');+ writeLargeWorktree(claimed, FILES);+ await insertSource('large-claimed', claimed);+ expect((await claimWorktree(engine, 'large-claimed', claimed)).local_path).toBe(claimed);+ await expectCompact('large-claimed', claimed);++ const candidate = join(home, 'candidate');+ copyWorktree(root, candidate);+ const deleted = join(candidate, 'notes', 'batch-000', 'example-note-000007.md');+ rmSync(deleted);+ await expect(runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: 'large-added', path: candidate })).rejects.toMatchObject({ code: 'writer_manifest_mismatch' });+ cpSync(join(root, 'notes', 'batch-000', 'example-note-000007.md'), deleted);+ expect(await runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: 'large-added', path: candidate })).toMatchObject({ state: 'committed' });+ expect((await getWorktreeBinding(engine, 'large-added'))!.local_path).toBe(candidate);+ await expectCompact('large-added', candidate);++ expect(await runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: 'large-added' })).toMatchObject({ state: 'committed' });+ expect(await runManagedSourceLifecycle(engine, { operation: 'restore', sourceId: 'large-added' })).toMatchObject({ state: 'committed' });+ expect(await runManagedSourceLifecycle(engine, { operation: 'remove', sourceId: 'large-added', confirmDestructive: true })).toMatchObject({ state: 'committed', storage_retained: true });+ expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', ['large-added'])).toHaveLength(0);+ }), 240_000);++ test('a 12k-file repository clones and reclones from a local bare repository', () => fixture(async home => {+ const bare = largeBareRepository(home, FILES);+ const target = join(home, 'cloned');+ const clone = async (_url: string, stage: string) => { execFileSync('git', ['clone', '--quiet', bare, stage], { stdio: 'ignore' }); };+ const principal = await topologyPrincipal(engine);+ const add = { operation: 'add' as const, sourceId: 'large-clone', path: target, remoteUrl: REMOTE, requestId: randomUUID() };+ expect(await runManagedSourceClone(engine, add, principal, add.requestId, { ...add, requestId: undefined, dryRun: undefined }, { clone }))+ .toMatchObject({ state: 'committed', cloned: true });+ await expectCompact('large-clone', target);+ const reclone = { operation: 'reclone' as const, sourceId: 'large-clone', requestId: randomUUID() };+ expect(await runManagedSourceClone(engine, reclone, principal, reclone.requestId, { ...reclone, requestId: undefined, dryRun: undefined }, { clone }))+ .toMatchObject({ state: 'committed', cloned: true });+ await expectCompact('large-clone', target);+ expect(readdirSync(home).some(name => name.includes('gbrain-old') || name.startsWith('.gbrain-clone'))).toBe(false);+ }), 240_000);++ test('a legacy manifest with a per-file map past 1 MiB is accepted by reclone recovery and compacted', () => fixture(async home => {+ const bare = largeBareRepository(home, 20);+ const target = join(home, 'cloned');+ const clone = async (_url: string, stage: string) => { execFileSync('git', ['clone', '--quiet', bare, stage], { stdio: 'ignore' }); };+ const principal = await topologyPrincipal(engine);+ const add = { operation: 'add' as const, sourceId: 'legacy-clone', path: target, remoteUrl: REMOTE, requestId: randomUUID() };+ await runManagedSourceClone(engine, add, principal, add.requestId, { ...add, requestId: undefined, dryRun: undefined }, { clone });+ await runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: 'legacy-clone' });+ const current = await storedManifest('legacy-clone');+ const files = Object.fromEntries(Array.from({ length: FILES }, (_, i) => [`notes/legacy/example-note-${String(i).padStart(6, '0')}.md`, 'f'.repeat(64)]));+ const legacy = { digest: current.digest, files, canonical_stamp: current.canonical_stamp };+ expect(Buffer.byteLength(JSON.stringify(legacy))).toBeGreaterThan(1_048_576);+ const binding = (await getWorktreeBinding(engine, 'legacy-clone'))!;+ await engine.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [binding.worktree_id, JSON.stringify(legacy)]);+ rmSync(target, { recursive: true, force: true });+ const reclone = { operation: 'reclone' as const, sourceId: 'legacy-clone', requestId: randomUUID() };+ expect(await runManagedSourceClone(engine, reclone, principal, reclone.requestId, { ...reclone, requestId: undefined, dryRun: undefined }, { clone }))+ .toMatchObject({ state: 'committed', cloned: true });+ await expectCompact('legacy-clone', target, 20);+ }), 240_000);++ test('writer transfer prepare and accept, including self-transfer, commit at 12k files', () => fixture(async home => {+ const root = join(home, 'owner');+ writeLargeWorktree(root, FILES);+ await insertSource('large-transfer', root);+ await claimWorktree(engine, 'large-transfer', root);+ const administer = async (operation: 'writer_transfer_prepare' | 'writer_transfer_accept', params: Record<string, unknown>) =>+ runPersistenceAdministration(engine, operation, { ...params, ...await reviewedWriterIntent(engine, operation) }) as Promise<any>;++ const self = await administer('writer_transfer_prepare', { source_id: 'large-transfer', self_transfer: true });+ expect(self.manifest).toEqual({ digest: worktreeManifest(root).digest, file_count: FILES });+ const draining = await storedManifest('large-transfer');+ expect(draining.files).toBeUndefined();+ expect(draining).toMatchObject({ digest: self.manifest.digest, file_count: FILES, self_transfer: expect.any(Object) });+ expect(await administer('writer_transfer_accept', { source_id: 'large-transfer', path: root, expected_epoch: self.owner_epoch, manifest: self.manifest.digest, self_transfer: true }))+ .toMatchObject({ transferred: true });++ const successor = join(home, 'successor');+ copyWorktree(root, successor);+ const prepared = await administer('writer_transfer_prepare', { source_id: 'large-transfer' });+ expect(prepared.manifest).toEqual({ digest: self.manifest.digest, file_count: FILES });+ expect(await administer('writer_transfer_accept', { source_id: 'large-transfer', path: successor, expected_epoch: prepared.owner_epoch, manifest: prepared.manifest.digest }))+ .toMatchObject({ transferred: true, binding: { local_path: successor, state: 'active' } });+ expect((await getWorktreeBinding(engine, 'large-transfer'))!.owner_epoch).toBe('3');+ }), 240_000);++ test('an administrative preview taken before a manifest rewrite refuses afterwards', () => fixture(async home => {+ const root = join(home, 'owner');+ mkdirSync(root);+ writeLargeWorktree(root, 20);+ await insertSource('rewritten', root);+ await claimWorktree(engine, 'rewritten', root);+ const binding = (await getWorktreeBinding(engine, 'rewritten'))!;+ const { digest } = worktreeManifest(root);+ await engine.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [binding.worktree_id, JSON.stringify({ digest, files: { 'example.md': 'f'.repeat(64) } })]);+ const preview = await reviewedWriterIntent(engine, 'writer_transfer_prepare');+ await engine.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [binding.worktree_id, JSON.stringify({ digest, file_count: 20 })]);+ await expect(runPersistenceAdministration(engine, 'writer_transfer_prepare', { source_id: 'rewritten', ...preview })).rejects.toMatchObject({ code: 'writer_admin_state_changed' });+ expect((await getWorktreeBinding(engine, 'rewritten'))!.state).toBe('active');+ }), 120_000);+});diff --git a/test/persistence-manifest-progress.test.ts b/test/persistence-manifest-progress.test.tsnew file mode 100644index 0000000000..37b16e94f2--- /dev/null+++ b/test/persistence-manifest-progress.test.ts@@ -0,0 +1,64 @@+/** #5790 / DX-O10: manifest hashing progress and digest compatibility. */+import { afterEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';+import { join, relative, sep } from 'node:path';+import { tmpdir } from 'node:os';+import { PassThrough } from 'node:stream';+import { compactStoredManifest, humanManifestProgress, MANIFEST_PROGRESS_MIN_FILES, worktreeManifest } from '../src/core/persistence/ownership.ts';+import { digest, sha256 } from '../src/core/persistence/digest.ts';+import { DEFAULT_CLI_OPTIONS, _resetCliOptionsForTest, setCliOptions } from '../src/core/cli-options.ts';+import { writeLargeWorktree } from './helpers/large-worktree.ts';++function sink() {+ const stream = new PassThrough();+ const chunks: string[] = [];+ stream.on('data', chunk => chunks.push(chunk.toString('utf8')));+ return { stream, read: () => chunks.join('') };+}++function withWorktree<T>(count: number, run: (root: string) => T): T {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-manifest-progress-'));+ try { writeLargeWorktree(root, count); return run(root); } finally { rmSync(root, { recursive: true, force: true }); }+}++describe('worktree manifest hashing', () => {+ afterEach(() => _resetCliOptionsForTest());++ test('reports files hashed of total on stderr above 5,000 files', () => withWorktree(MANIFEST_PROGRESS_MIN_FILES + 1, root => {+ const { stream, read } = sink();+ const manifest = worktreeManifest(root, { progress: { mode: 'human', stream, minIntervalMs: 0, minItems: 1 } });+ expect(manifest.file_count).toBe(MANIFEST_PROGRESS_MIN_FILES + 1);+ expect(read()).toContain('sources.manifest_hash');+ expect(read()).toContain(`/${MANIFEST_PROGRESS_MIN_FILES + 1}`);+ }));++ test('stays silent at or below 5,000 files and without a progress request', () => withWorktree(MANIFEST_PROGRESS_MIN_FILES, root => {+ const { stream, read } = sink();+ worktreeManifest(root, { progress: { mode: 'human', stream, minIntervalMs: 0, minItems: 1 } });+ expect(read()).toBe('');+ }));++ test('progress is offered in human mode only', () => {+ expect(humanManifestProgress()).toMatchObject({ mode: 'auto' });+ setCliOptions({ ...DEFAULT_CLI_OPTIONS, progressJson: true });+ expect(humanManifestProgress()).toBeUndefined();+ setCliOptions({ ...DEFAULT_CLI_OPTIONS, quiet: true });+ expect(humanManifestProgress()).toBeUndefined();+ });++ test('the digest is unchanged from the per-file map older binaries stored', () => withWorktree(25, root => {+ const files: Record<string, string> = {};+ const visit = (dir: string) => { for (const name of readdirSync(dir).sort()) {+ const path = join(dir, name);+ if (statSync(path).isDirectory()) visit(path); else files[relative(root, path).split(sep).join('/')] = sha256(readFileSync(path));+ } };+ visit(root);+ expect(worktreeManifest(root)).toEqual({ digest: digest(files), file_count: 25 });+ }));++ test('a legacy stored manifest drops only its per-file map', () => {+ const legacy = { digest: 'd'.repeat(64), files: { 'a.md': 'f'.repeat(64), 'b.md': 'e'.repeat(64) }, canonical_stamp: 'stamp', self_transfer: { hostId: 'h' } };+ expect(compactStoredManifest(legacy)).toEqual({ digest: 'd'.repeat(64), file_count: 2, canonical_stamp: 'stamp', self_transfer: { hostId: 'h' } });+ expect(compactStoredManifest({ digest: 'd'.repeat(64), file_count: 7 })).toEqual({ digest: 'd'.repeat(64), file_count: 7 });+ });+});diff --git a/test/persistence-source-lifecycle.test.ts b/test/persistence-source-lifecycle.test.tsindex 80539be240..f66580628f 100644--- a/test/persistence-source-lifecycle.test.ts+++ b/test/persistence-source-lifecycle.test.ts@@ -265,17 +265,17 @@ test('new clone metadata is counted alongside staging before canonical installatconst result=await runManagedSourceClone(engine,input,await topologyPrincipal(engine),input.requestId,{...input,requestId:undefined,dryRun:undefined},{clone:async(_url,stage,budget)=>{// Directory stat.size varies by filesystem. Fill the measured remaining- // space so raw staging fits and only its new manifest exceeds capacity.- for(let i=0;i<128;i++)writeFileSync(join(stage,`${String(i).padStart(4,'0')}-${'x'.repeat(175)}.md`),'');+ // space so raw staging fits and only the prepared recovery record, which+ // gains the manifest, stage identity and clone digest, exceeds capacity.const payload=join(stage,'payload.md');writeFileSync(payload,'');- const remaining=budget-await topologyDirectoryBytes(stage)-8192;+ const remaining=budget-await topologyDirectoryBytes(stage)-64;writeFileSync(payload,'x'.repeat(Math.max(0,remaining)));cloneBudget=budget;stagedBytes=await topologyDirectoryBytes(stage);manifestBytes=Buffer.byteLength(JSON.stringify(worktreeManifest(stage)));},});- expect(stagedBytes).toBe(cloneBudget-8192);- expect(manifestBytes).toBeGreaterThan(8192);expect(manifestBytes).toBeLessThan(1_048_576);+ expect(stagedBytes).toBe(cloneBudget-64);+ expect(manifestBytes).toBeGreaterThan(64);expect(manifestBytes).toBeLessThan(1024);expect(result).toMatchObject({state:'failed',write_error:'request_too_large'});expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1',[input.sourceId])).toHaveLength(0);expect((await engine.executeRaw<{recovery_bytes:string}>("SELECT recovery_bytes::text FROM persistence_counters WHERE key='brain'"))[0].recovery_bytes).toBe('0');