Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): hash only Git-tracked files in writer manifests and purge legacy per-file maps (#6099)
garrytan6821a6bf53ee
diff --git a/docs/architecture/key-files/company-brain.md b/docs/architecture/key-files/company-brain.mdindex ca8da34d1f..5a915ab499 100644--- a/docs/architecture/key-files/company-brain.md+++ b/docs/architecture/key-files/company-brain.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.For the operator workflow, see the [company-brain ingestion guide](../../guides/company-brain-ingestion.md).-- `src/core/company-brain/{inspection,revision,types}.ts` — bounded, database-free company repository plans from verified committed Git blobs. Selection, aliases, source-local references, audience requirements, dirty inputs, and schema identities are inspected without executing repository hooks, filters, or instructions. Saved plans are revalidated rather than treated as authority; search-hiding markers block readiness. `source-local-reference-index.ts` is shared with graph reconciliation so inspection never promises a different frontmatter target resolver.+- `src/core/company-brain/{inspection,revision,types}.ts` — bounded, database-free company repository plans from verified committed Git blobs. Selection, aliases, source-local references, audience requirements, dirty inputs, and schema identities are inspected without executing repository hooks, filters, or instructions. Saved plans are revalidated rather than treated as authority; search-hiding markers block readiness. `source-local-reference-index.ts` is shared with graph reconciliation so inspection never promises a different frontmatter target resolver. Its Git hardening (argv prefix and scrubbed environment) lives in `src/core/hardened-git.ts`, shared with the writer manifest (`persistence/worktree-manifest.ts`, which uses the synchronous `hardenedGitSync` with a timeout and byte cap).- `src/core/company-brain/{admission,profile,runtime,verification,receipts,receipt-schema}.ts` — trusted local new-source admission, persistent keyless source policy, exact-revision managed/legacy sync, durable phase receipts, and exact content/relationship/history verification. Admission composes with topology locks and request replay; managed sync retains owner/incarnation/revision fencing and refuses canonical file overlays. Incomplete receipt-owned checkpoints survive age-based cleanup. Completed state requires verified source content and graph, not just an advanced import bookmark. The receipt table is authoritative; saved JSON is an export.diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 98573a4ed8..dd83ccba8b 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -60,6 +60,6 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `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. 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/{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. #6099: the manifest lives in `worktree-manifest.ts` (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v217 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`). Tests: `test/persistence-manifest-git-scope.test.ts`.- `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 (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only 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. `--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), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`; 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), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.mdindex b30b8827cb..606d81ebb9 100644--- a/docs/architecture/topologies.md+++ b/docs/architecture/topologies.md@@ -454,6 +454,26 @@ intent and state checks. Explicit noninteractive provisioning uses the sameprocedure and preconditions. A transfer still requires the prepared epoch and anexact successor manifest; stale heartbeats never authorize takeover.+<a id="transfer-manifest-scope"></a>**What the manifest covers.** In a Git checkout, the transfer, `sources+set-path` (rebind), clone and reclone manifest covers the files Git tracks+(`git ls-files --cached`), hashed from their bytes in the working tree; a+tracked file missing on disk counts as deleted (#6099). Files Git ignores (such+as `.env.local` or `node_modules`) are never opened, hashed or stored, and never+need copying: a clean `git clone` of the same commit verifies. Untracked files+that Git does not ignore are not covered; `transfer prepare` reports how many as+`untracked_files` with a warning to commit or ignore them. Git runs with the+checkout's own hooks, fsmonitor and submodule recursion disabled. Symlinks and+submodules refuse with `writer_manifest_unsafe`. A directory that is not the top+of its own Git work tree keeps the exact-copy manifest over every file. A+mismatch names the first differing paths for a local rebind (tracked paths only+in a Git checkout). A transfer an older release prepared covers every file,+ignored ones included; if the successor is a Git checkout and does not match,+accept refuses `writer_manifest_rescope_required`: prepare the transfer again+on the owner host instead of copying ignored files. Upgrading removes the+per-file path and hash maps releases before v0.60.69 stored with prepared+transfers and clone recovery records (migration v217); only digests and counts+remain.+Live, young or foreign legacy locks block activation regardless of expiry. Forexact dead same-host holders only, preview with`--cleanup-dead-local-locks --dry-run` and explicitly opt in on the revieweddiff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex ae7de005ab..7c4f16dd55 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2594,13 +2594,23 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| Successor checkout differs from the recorded canonical manifest. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### writer_manifest_rescope_required++<a id="writer_manifest_rescope_required"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A writer transfer prepared by an older release covers every file of the old checkout, ignored files included, so a clean Git clone cannot match it. | Transfer manifests now cover the files Git tracks, so ignored secrets such as .env files are never read, hashed or required on the successor; a manifest recorded before that change is prepared again instead of asking the user to copy ignored files. | On the owner host, run gbrain sources writer transfer prepare <source> again with its admin intent and state, then accept with the new epoch and manifest. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/architecture/topologies.md#transfer-manifest-scope](../../docs/architecture/topologies.md#transfer-manifest-scope)+### writer_manifest_unsafe<a id="writer_manifest_unsafe"></a>| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| Canonical worktree transfer requires a symlink-free manifest. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+| The canonical worktree manifest cannot be recorded safely: the checkout holds a symlink or a Git submodule, or a Git-scoped comparison ran on a directory Git cannot list. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |### writer_not_initializeddiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 114c7eaa07..a201b8fb6b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -259,6 +259,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },{ since: '0.0.0-wave11', text: 'Doctor\'s new `persistence_write_stall` check warns when a managed write has held its claim longer than `persistence.max_claim_ms` (default 10 minutes) and names the stuck phase; `gbrain sources writer status --json` shows each running request\'s `claim` phase.' },{ since: '0.0.0-wave11', text: 'On a brain whose managed persistence was never activated, `gbrain sources writer deactivate` now releases sources claimed before activation (the dry run lists them as `pre_activation_claims`), so classic `gbrain sync` of them works again; `gbrain sources writer deactivate --dry-run --json` previews it.' },+ { since: '0.0.0-wave11', text: 'Writer transfer, `gbrain sources set-path` and reclone now compare only the files Git tracks in a Git checkout, so ignored files such as `.env.local` are never read or need copying and a clean `git clone` verifies; a transfer prepared before this release is prepared again (`writer_manifest_rescope_required`), and upgrading drops the per-file path and hash maps older releases stored.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/company-brain/revision.ts b/src/core/company-brain/revision.tsindex 4cc9e1df46..6dbddb8bb6 100644--- a/src/core/company-brain/revision.ts+++ b/src/core/company-brain/revision.ts@@ -4,6 +4,7 @@ import { constants, existsSync, lstatSync, openSync, fstatSync, readSync, closeSimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import type { Action } from '../agent-output.ts';import { opError } from '../ops/contract.ts';+import { HARDENED_GIT_ARGS, hardenedGitEnvironment } from '../hardened-git.ts';import {COMPANY_BRAIN_MAX_ENTRIES, COMPANY_BRAIN_MAX_FILE_BYTES, COMPANY_BRAIN_MAX_METADATA_BYTES,type CommittedEntry, type InspectionLimits, type RevisionIdentity, type UncommittedEntry,@@ -31,19 +32,10 @@ export function safeRepositoryPath(path: string): boolean {path.split('/').every(part => part !== '' && part !== '.' && part !== '..' && part.toLowerCase() !== '.git');}-function gitEnvironment(): NodeJS.ProcessEnv {- const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));- return { ...env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_OPTIONAL_LOCKS: '0',- GIT_NO_LAZY_FETCH: '1', GIT_NO_REPLACE_OBJECTS: '1', GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', LC_ALL: 'C' };-}-async function gitRead(root: string, args: string[], maxBytes: number, onChunk?: (chunk: Buffer) => void): Promise<Buffer> {return await new Promise((accept, reject) => {- const child = spawn('git', ['--no-pager', '--no-optional-locks', '--no-replace-objects',- '-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', '-c', 'core.untrackedCache=false',- '-c', 'submodule.recurse=false', '-c', 'protocol.allow=never', '-c', 'credential.helper=',- '-c', 'maintenance.auto=false', '-c', 'gc.auto=0', '-C', root, ...args],- { env: gitEnvironment(), stdio: ['ignore', 'pipe', 'pipe'] });+ const child = spawn('git', [...HARDENED_GIT_ARGS, '-C', root, ...args],+ { env: hardenedGitEnvironment(), stdio: ['ignore', 'pipe', 'pipe'] });const chunks: Buffer[] = [];let bytes = 0;let failure: Error | undefined;diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex aaddcec0fd..8f98b72d83 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -348,7 +348,8 @@ export const CODES = {writer_identity_publish_failed: { class: 'host_only', summary: "The replacement writer is durable but its credential file could not be published." },writer_lock_unavailable: { class: 'retryable', summary: "Another activation probe is running." },writer_manifest_mismatch: { class: 'caller', summary: "Successor checkout differs from the recorded canonical manifest." },- writer_manifest_unsafe: { class: 'caller', summary: "Canonical worktree transfer requires a symlink-free manifest." },+ writer_manifest_rescope_required: { class: 'host_only', summary: "A writer transfer prepared by an older release covers every file of the old checkout, ignored files included, so a clean Git clone cannot match it.", why: "Transfer manifests now cover the files Git tracks, so ignored secrets such as .env files are never read, hashed or required on the successor; a manifest recorded before that change is prepared again instead of asking the user to copy ignored files.", docs: 'docs/architecture/topologies.md#transfer-manifest-scope', suggestion: 'On the owner host, run gbrain sources writer transfer prepare <source> again with its admin intent and state, then accept with the new epoch and manifest.' },+ writer_manifest_unsafe: { class: 'caller', summary: "The canonical worktree manifest cannot be recorded safely: the checkout holds a symlink or a Git submodule, or a Git-scoped comparison ran on a directory Git cannot list." },writer_not_initialized: { class: 'host_only', summary: "Persistence identity is missing." },writer_not_quiesced: { class: 'host_only', summary: "Older writers or maintenance jobs are still running." },writer_pool_capacity: { class: 'retryable', summary: "Mirror recovery is waiting for publication capacity." },diff --git a/src/core/hardened-git.ts b/src/core/hardened-git.tsnew file mode 100644index 0000000000..e62a0a3983--- /dev/null+++ b/src/core/hardened-git.ts@@ -0,0 +1,36 @@+/**+ * Git invocation for directories gbrain does not trust (a user-chosen checkout,+ * a candidate clone): the repository's own configuration must not run code or+ * reach the network. Every call scrubs `GIT_*` from the environment, ignores+ * system and global config, and disables fsmonitor, hooks, the untracked+ * cache, submodule recursion, protocols, credential helpers and automatic+ * maintenance. Arguments are an argv array, never a shell string. Callers+ * bound time and output (`company-brain/revision.ts` streams with its own+ * caps; `hardenedGitSync` takes a timeout and a byte cap).+ */+import { spawnSync } from 'node:child_process';++export const HARDENED_GIT_ARGS: readonly string[] = ['--no-pager', '--no-optional-locks', '--no-replace-objects',+ '-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', '-c', 'core.untrackedCache=false',+ '-c', 'submodule.recurse=false', '-c', 'protocol.allow=never', '-c', 'credential.helper=',+ '-c', 'maintenance.auto=false', '-c', 'gc.auto=0'];++export function hardenedGitEnvironment(): NodeJS.ProcessEnv {+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));+ return { ...env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_OPTIONAL_LOCKS: '0',+ GIT_NO_LAZY_FETCH: '1', GIT_NO_REPLACE_OBJECTS: '1', GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', LC_ALL: 'C' };+}++export type HardenedGitResult = { ok: true; stdout: Buffer } | { ok: false; reason: 'exit' | 'timeout' | 'too_large' | 'unavailable' };++/** Runs `git -C <root> <args>` synchronously under the hardening above, within `timeoutMs` and `maxBytes` of stdout. */+export function hardenedGitSync(root: string, args: string[], limits: { timeoutMs: number; maxBytes: number }): HardenedGitResult {+ const run = spawnSync('git', [...HARDENED_GIT_ARGS, '-C', root, ...args],+ { env: hardenedGitEnvironment(), stdio: ['ignore', 'pipe', 'ignore'], timeout: limits.timeoutMs, maxBuffer: limits.maxBytes, killSignal: 'SIGKILL' });+ const code = (run.error as NodeJS.ErrnoException | undefined)?.code;+ if (code === 'ETIMEDOUT') return { ok: false, reason: 'timeout' };+ if (code === 'ENOBUFS') return { ok: false, reason: 'too_large' };+ if (run.error) return { ok: false, reason: 'unavailable' };+ if (run.status !== 0) return { ok: false, reason: 'exit' };+ return { ok: true, stdout: run.stdout };+}diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex 06511a841f..1c30196e57 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, humanManifestProgress, prepareWriterTransfer, worktreeManifest } from './ownership.ts';+import { acceptWriterTransfer, claimWorktree, getWorktreeBinding, humanManifestProgress, prepareWriterTransfer, storedManifestScope, worktreeManifest, type StoredWorktreeManifest } 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';@@ -299,8 +299,11 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio}const expectedState = await requireWriterAdminIntent(engine, operation, params);const prepared = await prepareWriterTransfer(engine, sourceId, undefined, expectedState, { selfTransfer: params.self_transfer === true });+ // #6099: a Git-scoped manifest covers tracked files only; untracked files Git does not ignore are reported as a count.+ const untracked = prepared.manifest.untracked_count ?? 0;return { prepared: true, source_id: sourceId, worktree_id: prepared.worktree_id, owner_epoch: prepared.owner_epoch,- manifest: { digest: prepared.manifest.digest, file_count: prepared.manifest.file_count } };+ manifest: { digest: prepared.manifest.digest, file_count: prepared.manifest.file_count, ...(prepared.manifest.scope ? { scope: prepared.manifest.scope } : {}) },+ ...(untracked ? { untracked_files: untracked, warning: `${untracked} untracked file(s) in the checkout that Git does not ignore are not part of the transfer manifest and are not carried to the successor; commit them, or add them to .gitignore, before the successor clones.` } : {}) };}if (operation === 'writer_transfer_accept') {keys(params, ['source_id', 'path', 'expected_epoch', 'manifest', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer']);@@ -312,8 +315,13 @@ 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.',`Pass --manifest with the 64-character manifest digest that gbrain sources writer transfer prepare ${sourceId} printed.`, transferStatusFix(sourceId));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, { progress: humanManifestProgress() }).digest === params.manifest, expected_epoch: params.expected_epoch };+ if (params.dry_run) {+ const current = await getWorktreeBinding(engine, sourceId, existingLocalHostId());+ const [prepared] = current ? await engine.executeRaw<{ manifest: StoredWorktreeManifest | null }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [current.worktree_id]) : [];+ const candidate = worktreeManifest(root, { progress: humanManifestProgress(), scope: storedManifestScope(prepared?.manifest) });+ return { dry_run: true, action: operation, source_id: sourceId, current, manifest_matches: candidate.digest === params.manifest, expected_epoch: params.expected_epoch,+ ...(candidate.scope ? { manifest_scope: candidate.scope } : {}), ...(candidate.untracked_count ? { untracked_files: candidate.untracked_count } : {}) };+ }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 8092a77876..cb3cff03e4 100644--- a/src/core/persistence/ownership.ts+++ b/src/core/persistence/ownership.ts@@ -1,5 +1,5 @@import { randomUUID } from 'node:crypto';-import { lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';+import { realpathSync, statSync } from 'node:fs';import { isAbsolute, join, relative, resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import { OperationError, opError } from '../ops/contract.ts';@@ -7,14 +7,14 @@ import { readFix } from '../ops/op-fix.ts';import type { Action } from '../agent-output.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 type { ProgressOptions } from '../progress.ts';+import { detectManifestScope, storedManifestScope, worktreeManifest, type StoredWorktreeManifest, type WorktreeManifest } from './worktree-manifest.ts';import { localHostId, persistenceHome } from './identity.ts';import type { SqlEngine, WriteRequest } from './model.ts';import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';import { acquireShared, yieldLease } from './worktree-lease.ts';import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';-import { assertPhysicalRoot, claimPhysicalRoot, isPhysicalRootMetadata, preparePhysicalRootTransfer, readPhysicalRootReservation, restampPhysicalRoot } from './physical-root.ts';+import { assertPhysicalRoot, claimPhysicalRoot, preparePhysicalRootTransfer, readPhysicalRootReservation, restampPhysicalRoot } from './physical-root.ts';import { readPhysicalRootStamp } from './physical-root-record.ts';import { canonicalFilesystemPath, nativeFilesystemPath } from './root-registry.ts';import { assertWriterAdminState } from './admin-intent.ts';@@ -197,38 +197,30 @@ export async function activateManagedPersistence(engine: BrainEngine, opts: { coawait activatePersistence(engine, opts);}-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;+export { MANIFEST_PROGRESS_MIN_FILES, compactStoredManifest, storedManifestScope, worktreeManifest,+ type StoredWorktreeManifest, type WorktreeManifest, type WorktreeManifestScope } from './worktree-manifest.ts';/**- * 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.+ * #6099: why a successor checkout does not verify, agent-first. A transfer an older release prepared in tree scope+ * (every file, ignored ones included) is re-prepared in Git scope rather than asking the user to copy ignored files.*/-export function worktreeManifest(root: string, opts: { progress?: ProgressOptions } = {}): WorktreeManifest {- const canonical = realpathSync(root);- 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 opError('writer_manifest_unsafe', 'Canonical worktree transfer requires a symlink-free manifest.',- `${relative(canonical, path).split(sep).join('/')} in the checkout is a symlink, so no manifest was recorded. Ask the user to replace it with a real file or directory (or remove it), then run the transfer step again.`);- if (info.isDirectory()) visit(path);- else if (info.isFile()) paths.push(path);- }- };- visit(canonical);- 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 };+export function successorManifestMismatch(sourceId: string, root: string, expected: string, prepared: StoredWorktreeManifest | null,+ candidate: WorktreeManifest): OperationError {+ if (storedManifestScope(prepared) === 'tree' && detectManifestScope(root) === 'git') return opError('writer_manifest_rescope_required',+ 'The transfer was prepared over every file of the old checkout, ignored files included; prepare it again so it covers tracked Git files only.',+ `Source ${sourceId}'s transfer manifest ${expected} was recorded by an older release over every file in the owner's checkout, including files Git ignores (such as .env files), so a clean clone at ${root} cannot match it and nothing was accepted. `+ + `Do not copy ignored files across. On the owner host, prepare the transfer again (it now records tracked Git files only), then accept with the new epoch and manifest it prints.`,+ { fix: { argv: ['gbrain', 'sources', 'writer', 'transfer', 'prepare', sourceId, '--admin-intent', 'writer_transfer_prepare', '--expected-state', '<admin_state>'],+ inputs: [{ name: 'admin_state', how: `admin_state from gbrain sources writer status ${sourceId} --json on the owner host` }],+ consent: [], actor: 'host_admin', requires_exclusive: false, docs: 'docs/architecture/topologies.md#transfer-manifest-scope',+ why: 'Re-records the transfer manifest over tracked Git files on the owner host; the successor then accepts with the printed epoch and manifest.' } });+ const untracked = candidate.scope === 'git' && candidate.untracked_count ? ` ${candidate.untracked_count} untracked file(s) here that Git does not ignore are not part of the manifest and do not cause this.` : '';+ return opError('writer_manifest_mismatch', 'Successor checkout differs from the recorded canonical manifest.',+ candidate.scope === 'git'+ ? `The tracked Git files at ${root} (${candidate.file_count} present) do not hash to manifest ${expected} that the owner recorded for source ${sourceId}; nothing was accepted. A tracked file differs, is missing or is extra.${untracked} `+ + `Make ${root} a clean clone of the owner's repository at the same commit (git clone <owner repository> ${root}, then git -C ${root} checkout <owner commit>), compare with git -C ${root} status, then accept again.`+ : `The checkout at ${root} does not hash to manifest ${expected} that the owner recorded for source ${sourceId}; nothing was accepted. Bring it to exactly the prepared content (same files, no extras or deletions), then accept again.`,+ { fix: writerStatusFix(sourceId) });}/** Human-mode progress for manifest hashing; JSON and quiet modes report nothing. */@@ -237,11 +229,6 @@ export function humanManifestProgress(): ProgressOptions | undefined {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: StoredWorktreeManifest }> {const binding = await getWorktreeBinding(engine, sourceId, hostId);@@ -310,10 +297,10 @@ export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string`Another gbrain process holds the successor checkout's coordination lock, so source ${sourceId}'s transfer was not accepted. Run transfer accept again once that process has finished.`,{ fix: writerStatusFix(sourceId) });try {- if (worktreeManifest(root, { progress: humanManifestProgress() }).digest !== expectedManifest)- throw opError('writer_manifest_mismatch', 'Successor checkout differs from the recorded canonical manifest.',- `The checkout at ${root} does not hash to manifest ${expectedManifest} that the owner recorded for source ${sourceId}; nothing was accepted. Bring it to exactly the prepared content (same files, no extras or deletions), then accept again.`,- { fix: writerStatusFix(sourceId) });+ // #6099: verify in the scope the owner recorded (a manifest an older release prepared is in tree scope).+ const [prepared] = await engine.executeRaw<{ manifest: StoredWorktreeManifest | null }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [binding.worktree_id]);+ const candidate = worktreeManifest(root, { progress: humanManifestProgress(), scope: storedManifestScope(prepared?.manifest) });+ if (candidate.digest !== expectedManifest) throw successorManifestMismatch(sourceId, root, expectedManifest, prepared?.manifest ?? null, candidate);await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");await assertWriterAdminState(tx, expectedAdminState);diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.tsindex c963820b31..158871fccf 100644--- a/src/core/persistence/source-lifecycle.ts+++ b/src/core/persistence/source-lifecycle.ts@@ -14,6 +14,7 @@ import { redactSourceConfig } from '../source-config-redact.ts';import { discoverGitRoot } from '../sync-git.ts';import { isInsideGitRepo, hasTrackedContent } from '../git-remote.ts';import { containsPath, getWorktreeBinding, humanManifestProgress, type WorktreeBinding, type WorktreeManifest, worktreeManifest } from './ownership.ts';+import { manifestDifferences, storedManifestScope, type WorktreeManifestScope } from './worktree-manifest.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';@@ -160,6 +161,11 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLconst manifest=worktreeManifest(path,{progress:humanManifestProgress()});manifests.set(path,manifest);}+ // #6099: a rebind compares the new directory in the scope of the current checkout's manifest (Git-tracked files for a Git checkout).+ const currentRoot=bindings.find(binding=>binding.source_id===input.sourceId)?.local_path;+ if(input.operation==='rebind'&&root&¤tRoot&¤tRoot!==root.worktree&&manifests.has(currentRoot)&&manifests.has(root.worktree)+ &&storedManifestScope(manifests.get(currentRoot))!==storedManifestScope(manifests.get(root.worktree)))+ manifests.set(root.worktree,worktreeManifest(root.worktree,{progress:humanManifestProgress(),scope:storedManifestScope(manifests.get(currentRoot))}));return topologyTransaction(engine,async tx=>{await assertWriterAdminState(tx,input.expectedAdminState);await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");@@ -213,9 +219,8 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLif(!binding?.local_path || !existsSync(binding.local_path)) throw opError('recovery_required','The original checkout is unavailable; recover its last verified manifest before rebinding.',`Nothing was rebound. Restore the original checkout of '${input.sourceId}' at the path the command in fix reports, with its last verified contents, then rerun set-path.`,{fix:ownerStatusFix(input.sourceId)});- if(manifests.get(binding.local_path)!.digest!==manifests.get(root!.worktree)!.digest) throw opError('writer_manifest_mismatch','The new checkout differs from the current canonical manifest, including deletions.',- `Nothing was rebound. Make the new directory an exact copy of the current checkout of '${input.sourceId}' (same files, nothing extra or missing), then rerun set-path.`,- {fix:ownerStatusFix(input.sourceId)});+ if(manifests.get(binding.local_path)!.digest!==manifests.get(root!.worktree)!.digest) throw rebindManifestMismatch(input.sourceId,binding.local_path,root!.worktree,+ storedManifestScope(manifests.get(binding.local_path)));}const ownedSourcePath=currentBinding?.local_path?join(currentBinding.local_path,currentBinding.relative_path):source?.local_path;if(input.operation==='restore'&&ownedSourcePath&&!existsSync(ownedSourcePath)) throw opError('recovery_required','Restore requires the verified canonical checkout. Reclone it before restoring the source.',@@ -269,3 +274,15 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL});},root?.worktree);}++/** #6099: a rebind's new directory does not match the current checkout; names the first differing paths (Git-tracked paths in git scope). */+function rebindManifestMismatch(sourceId:string,current:string,candidate:string,scope:WorktreeManifestScope):OperationError{+ const diff=manifestDifferences(current,candidate,scope);+ const named=diff.total?` ${diff.total} file(s) differ, are missing or are extra${scope==='git'?' among the tracked Git files':''}: ${diff.paths.join(', ')}${diff.total>diff.paths.length?', …':''}.`:'';+ return opError('writer_manifest_mismatch','The new checkout differs from the current canonical manifest, including deletions.',+ scope==='git'+ ?`Nothing was rebound.${named} The comparison covers files Git tracks, so ignored files (such as .env files) never need copying. Make ${candidate} a clean clone of the current checkout `+ +`(for example move it aside, then git clone ${current} ${candidate}), then rerun gbrain sources set-path ${sourceId} ${candidate}.`+ :`Nothing was rebound.${named} Make the new directory an exact copy of the current checkout of '${sourceId}' (same files, nothing extra or missing), then rerun set-path.`,+ {fix:ownerStatusFix(sourceId)});+}diff --git a/src/core/persistence/topology-clone-model.ts b/src/core/persistence/topology-clone-model.tsindex 498818e382..e0cd8cdc22 100644--- a/src/core/persistence/topology-clone-model.ts+++ b/src/core/persistence/topology-clone-model.ts@@ -3,7 +3,9 @@ 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;file_count?:number;files?:Record<string,string>;canonical_stamp?:string}|null;+ manifest:{digest:string;file_count?:number;files?:Record<string,string>;canonical_stamp?:string;scope?:'git'}|null;+ /** #6099: the manifest scope beforeHash and afterHash are computed in; absent on records older releases wrote (tree). */+ hashScope?:'git'|'tree';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 e8be80470e..4f02041caf 100644--- a/src/core/persistence/topology-clone.ts+++ b/src/core/persistence/topology-clone.ts@@ -11,7 +11,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 { compactStoredManifest, getWorktreeBinding, humanManifestProgress, worktreeManifest } from './ownership.ts';+import { compactStoredManifest, getWorktreeBinding, humanManifestProgress, storedManifestScope, 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';@@ -130,7 +130,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec{fix:writerStatusFix(input.sourceId)});const recovery:TopologyCloneRecovery={version:1,kind:'clone',phase:'reserved',operation:input.operation as 'add'|'reclone',sourceId:input.sourceId,incarnation,worktreeId,ownerHostId:localHostId(),ownerEpoch:String(currentBinding?.owner_epoch??preparedOwner?.owner_epoch??1),target,stage,aside,- beforeHash:before?.digest??null,afterHash:null,manifest,canonicalStamp,checkpoint:source?.last_commit??null,sourceRemoteUrl:source?.config.remote_url as string??null,input,cloneBudget:0};+ beforeHash:before?.digest??null,afterHash:null,manifest,...(manifest?{hashScope:storedManifestScope(manifest)}:{}),canonicalStamp,checkpoint:source?.last_commit??null,sourceRemoteUrl:source?.config.remote_url as string??null,input,cloneBudget:0};recovery.cloneBudget=reserved-oldBytes-Buffer.byteLength(JSON.stringify(recovery))-65_536;if(recovery.cloneBudget<65_536)throw opError('request_too_large','The old checkout leaves insufficient configured recovery space for a staged clone.',`The current checkout of source ${input.sourceId} (${oldBytes} bytes) uses nearly all of the ${reserved}-byte recovery capacity, so nothing was cloned. Ask the user to raise persistence.limits.worktree_recovery_bytes and persistence.limits.brain_recovery_bytes (more disk reserved for recovery), then run the ${input.operation} again.`,@@ -167,12 +167,12 @@ 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,{progress:humanManifestProgress()});+ const candidate=worktreeManifest(recovery.stage,{progress:humanManifestProgress(),scope:recovery.hashScope});if(recovery.manifest&&candidate.digest!==recovery.manifest.digest)throw opError('writer_manifest_mismatch','The cloned checkout differs from the verified canonical manifest, including deletions.',`A fresh clone from the remote does not match source ${input.sourceId}'s canonical content exactly (including deletions), so the clone is rolled back and the original kept. Make sure every canonical commit is pushed to the remote, then run gbrain sources reclone ${input.sourceId} again under a new request id.`,{fix:writerStatusFix(input.sourceId)});flushTopologyTree(recovery.stage);flushTopologyDirectory(dirname(recovery.stage));- recovery.afterHash=candidate.digest;recovery.phase='prepared';recovery.manifest={...candidate,canonical_stamp:recovery.canonicalStamp};+ recovery.afterHash=candidate.digest;recovery.hashScope=candidate.scope??'tree';recovery.phase='prepared';recovery.manifest={...candidate,canonical_stamp:recovery.canonicalStamp};if(oldBytes+stageBytes+Buffer.byteLength(JSON.stringify(recovery))+65_536>Number(admission.recovery_bytes))throw opError('request_too_large','The complete staged clone and recovery metadata exceed the reserved capacity.',`The cloned repository (${stageBytes} bytes) plus the old checkout exceed the ${admission.recovery_bytes}-byte recovery reservation, so the clone is rolled back. Ask the user to raise persistence.limits.worktree_recovery_bytes and persistence.limits.brain_recovery_bytes, then run the ${input.operation} again under a new request id.`,diff --git a/src/core/persistence/topology-recovery.ts b/src/core/persistence/topology-recovery.tsindex a7fd265122..8b75d91e9f 100644--- a/src/core/persistence/topology-recovery.ts+++ b/src/core/persistence/topology-recovery.ts@@ -50,11 +50,11 @@ function validateRecord(record:TopologyCloneRecovery):void{throw retainedClone('The recorded clone paths no longer belong to this owner.',record,`The recovery record names paths or an owner host that this host (${localHostId()}) cannot vouch for.`);}-function treeHash(path:string):string|null{+function treeHash(path:string,scope:'git'|'tree'):string|null{if(!existsSync(path))return null;if(lstatSync(path).isSymbolicLink())throw opError('recovery_required','Recovery refuses a substituted symbolic link.',`${path} was replaced by a symbolic link, so clone recovery stopped without following or removing it. Show the user the path; the owner re-checks it on every recovery pass and stays blocked until the link is replaced by the recorded directory (docs/architecture/topologies.md).`);- return worktreeManifest(path).digest;+ return worktreeManifest(path,{scope}).digest;}function assertRetainedRoot(record:TopologyCloneRecovery,path:string):void{const reservation=readPhysicalRootReservation(record.target);@@ -69,7 +69,7 @@ function assertStagingOwned(record:TopologyCloneRecovery):void{throw retainedClone('Unexpected staging directory identity; recovery retained its bytes.',record,`The staging directory ${record.stage} is not the one this clone created (device/inode differ).`);if(record.afterHash!==null){- if(treeHash(record.stage)!==record.afterHash)throw retainedClone('Unexpected staged clone bytes; recovery retained them.',record,+ if(treeHash(record.stage,record.hashScope??'tree')!==record.afterHash)throw retainedClone('Unexpected staged clone bytes; recovery retained them.',record,`The staged clone at ${record.stage} no longer matches the bytes this clone wrote.`);assertRetainedRoot(record,record.stage);}@@ -110,7 +110,7 @@ async function abortClone(engine:BrainEngine,row:TopologyChange,record:TopologyC// Restore only this attempt's exact bytes. A newer withdrawal remains in// the database; its mirror resumes after the root becomes available.assertStagingOwned(record);- const aside=treeHash(record.aside),target=treeHash(record.target);+ const aside=treeHash(record.aside,record.hashScope??'tree'),target=treeHash(record.target,record.hashScope??'tree');if(target!==null)assertPhysicalRoot(record.target,{worktreeId:record.worktreeId});if(aside!==null){assertRetainedRoot(record,record.aside);@@ -156,7 +156,7 @@ export async function finishTopologyClone(engine:BrainEngine,id:string,hooks:Clo{fix:cloneStatusFix(record.sourceId)});await settleTopologyRequests(tx,sources,[record.worktreeId],row.principal_id);assertStagingOwned(record);- const stage=treeHash(record.stage),target=treeHash(record.target),aside=treeHash(record.aside);+ const stage=treeHash(record.stage,record.hashScope??'tree'),target=treeHash(record.target,record.hashScope??'tree'),aside=treeHash(record.aside,record.hashScope??'tree');if(stage!==null){assertRetainedRoot(record,record.stage);if(aside!==null)assertRetainedRoot(record,record.aside);@@ -198,9 +198,9 @@ export async function finishTopologyClone(engine:BrainEngine,id:string,hooks:Clo}}assertPhysicalRoot(record.target,{worktreeId:record.worktreeId});- if(treeHash(record.target)!==record.afterHash)throw retainedClone('The committed clone changed before recovery cleanup.',record,+ if(treeHash(record.target,record.hashScope??'tree')!==record.afterHash)throw retainedClone('The committed clone changed before recovery cleanup.',record,`The clone is committed, but ${record.target} changed before its cleanup ran.`);- const aside=treeHash(record.aside);+ const aside=treeHash(record.aside,record.hashScope??'tree');if(aside!==null&&aside!==record.beforeHash)throw retainedClone('The retained old checkout changed; cleanup requires inspection.',record,`The clone is committed, but the retained original at ${record.aside} changed, so it was not removed.`);if(existsSync(record.stage))throw retainedClone('Unexpected staging bytes remain after clone commitment.',record,diff --git a/src/core/persistence/worktree-manifest.ts b/src/core/persistence/worktree-manifest.tsnew file mode 100644index 0000000000..e9f7782bf0--- /dev/null+++ b/src/core/persistence/worktree-manifest.ts@@ -0,0 +1,142 @@+/**+ * The canonical worktree manifest that writer transfer, rebind (`sources+ * set-path`), clone and reclone compare: a digest over relative path ->+ * sha256 of the file's bytes, plus the file count, with deletions caught by+ * exact path-set equality. Stored manifests carry only the digest, count and+ * scope, so their size does not grow with the worktree.+ *+ * #6099: a Git checkout is hashed in `git` scope, over the paths Git tracks+ * (`git ls-files -z --cached --stage`, hashed from the working-tree bytes; an+ * index entry missing on disk counts as deleted). Ignored files (a `.env.local`,+ * `node_modules`) are never opened, so a clean clone verifies and secrets are+ * never read or hashed. Untracked files Git does not ignore are reported as a+ * count only. A directory that is not the top of its own Git work tree keeps the+ * `tree` scope: every file except `.git`, `.gbrain-managed` and physical-root+ * metadata. A manifest without `scope` is in `tree` scope, which is also what every+ * manifest an older release stored is, so those keep verifying in that scope.+ *+ * Git runs through `hardened-git.ts` (the candidate directory's config is+ * untrusted). Symlinks, submodules (gitlinks) and tracked paths that resolve+ * outside the root refuse with `writer_manifest_unsafe`.+ */+import { lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs';+import { join, relative, sep } from 'node:path';+import { opError } from '../ops/contract.ts';+import { createProgress, type ProgressOptions } from '../progress.ts';+import { hardenedGitSync } from '../hardened-git.ts';+import { digest, sha256 } from './digest.ts';+import { isPhysicalRootMetadata } from './root-metadata.ts';+import type { PhysicalRootRecovery } from './physical-root-recovery.ts';++export type WorktreeManifestScope = 'git' | 'tree';+export interface WorktreeManifest { digest: string; file_count: number;+ /** `git` for a Git-scoped manifest; absent means `tree` (the only scope older releases recorded). */+ scope?: 'git';+ /** Git scope only: untracked files Git does not ignore, which the manifest does not cover (count only, never names). */+ untracked_count?: number }+export type StoredWorktreeManifest = WorktreeManifest & { canonical_stamp?: string; self_transfer?: PhysicalRootRecovery };+export const MANIFEST_PROGRESS_MIN_FILES = 5000;+const GIT_LIMITS = { timeoutMs: 60_000, maxBytes: 256 * 1024 * 1024 };++/** The scope a stored manifest was recorded in (older releases recorded `tree` without saying so). */+export function storedManifestScope(manifest: { scope?: WorktreeManifestScope } | null | undefined): WorktreeManifestScope {+ return manifest?.scope === 'git' ? 'git' : 'tree';+}++/** `git` when `root` is the top of its own Git work tree, else `tree`. */+export function detectManifestScope(root: string): WorktreeManifestScope {+ const canonical = realpathSync(root);+ const top = hardenedGitSync(canonical, ['rev-parse', '--show-toplevel'], { timeoutMs: 10_000, maxBytes: 64 * 1024 });+ if (!top.ok) return 'tree';+ try { return realpathSync(top.stdout.toString('utf8').trim()) === canonical ? 'git' : 'tree'; } catch { return 'tree'; }+}++const unsafe = (message: string, suggestion: string) => opError('writer_manifest_unsafe', message, suggestion);+const excluded = (rel: string) => rel.split('/').some(part => part === '.git' || part === '.gbrain-managed' || isPhysicalRootMetadata(part));++/**+ * The manifest of `root` in `scope` (detected when omitted). `withFiles` also+ * returns the per-file map, for a caller that compares two local checkouts.+ */+export function worktreeManifest(root: string, opts: { progress?: ProgressOptions; scope?: WorktreeManifestScope; withFiles?: boolean } = {}): WorktreeManifest & { files?: Record<string, string> } {+ const canonical = realpathSync(root);+ const scope = opts.scope ?? detectManifestScope(canonical);+ const listed = scope === 'git' ? trackedPaths(canonical) : treePaths(canonical);+ const progress = opts.progress && listed.paths.length > MANIFEST_PROGRESS_MIN_FILES ? createProgress(opts.progress) : undefined;+ progress?.start('sources.manifest_hash', listed.paths.length);+ const files: Record<string, string> = {};+ for (const rel of listed.paths) {+ const bytes = scope === 'git' ? trackedBytes(canonical, rel) : readFileSync(join(canonical, ...rel.split('/')));+ if (bytes) files[rel] = sha256(bytes);+ progress?.tick();+ }+ progress?.finish();+ const count = Object.keys(files).length;+ return { digest: digest(files), file_count: count, ...(scope === 'git' ? { scope, untracked_count: listed.untracked ?? 0 } : {}),+ ...(opts.withFiles ? { files } : {}) };+}++function treePaths(canonical: string): { paths: string[]; untracked?: number } {+ 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 unsafe('Canonical worktree transfer requires a symlink-free manifest.',+ `${relative(canonical, path).split(sep).join('/')} in the checkout is a symlink, so no manifest was recorded. Ask the user to replace it with a real file or directory (or remove it), then run the transfer step again.`);+ if (info.isDirectory()) visit(path);+ else if (info.isFile()) paths.push(relative(canonical, path).split(sep).join('/'));+ }+ };+ visit(canonical);+ return { paths };+}++function trackedPaths(canonical: string): { paths: string[]; untracked: number } {+ const listed = hardenedGitSync(canonical, ['ls-files', '-z', '--cached', '--stage'], GIT_LIMITS);+ if (!listed.ok) throw unsafe('The canonical manifest is recorded from tracked Git files, and Git could not list them here.',+ `Git could not list the tracked files of ${canonical} (${listed.reason === 'exit' ? 'it is not the top of a Git checkout, or its index is unreadable' : listed.reason}), so no manifest was compared. `+ + 'Use a Git checkout of the same repository: for example git clone <the owner\'s repository> <this directory>, check out the same commit, then run the step again.');+ const paths = new Set<string>();+ for (const record of listed.stdout.toString('utf8').split('\0')) {+ if (!record) continue;+ const tab = record.indexOf('\t');+ const mode = record.slice(0, record.indexOf(' ')), rel = record.slice(tab + 1);+ if (excluded(rel)) continue;+ if (mode === '160000') throw unsafe('Canonical worktree transfer does not support Git submodules.',+ `${rel} in ${canonical} is a Git submodule, so no manifest was recorded. Ask the user to replace the submodule with ordinary tracked files (or remove it), then run the step again.`);+ if (mode === '120000') throw unsafe('Canonical worktree transfer requires a symlink-free manifest.',+ `${rel} in the checkout is a tracked symlink, so no manifest was recorded. Ask the user to replace it with a real file (or remove it), then run the transfer step again.`);+ paths.add(rel);+ }+ const others = hardenedGitSync(canonical, ['ls-files', '-z', '--others', '--exclude-standard'], GIT_LIMITS);+ const untracked = others.ok ? others.stdout.toString('utf8').split('\0').filter(rel => rel && !excluded(rel)).length : 0;+ return { paths: [...paths].sort(), untracked };+}++/** The working-tree bytes of a tracked path; null when it is missing on disk (counted as deleted). */+function trackedBytes(canonical: string, rel: string): Buffer | null {+ const path = join(canonical, ...rel.split('/'));+ let real: string;+ try { real = realpathSync(path); } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' || (error as NodeJS.ErrnoException).code === 'ENOTDIR') return null;+ throw error;+ }+ if (real !== path || lstatSync(path).isSymbolicLink()) throw unsafe('Canonical worktree transfer requires a symlink-free manifest.',+ `${rel} in the checkout resolves through a symlink, so no manifest was recorded. Ask the user to replace the link with a real file or directory (or remove it), then run the transfer step again.`);+ if (!lstatSync(path).isFile()) return null;+ return readFileSync(path);+}++/** 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 };+}++/** The first `limit` relative paths whose bytes differ, or that only one of two local checkouts has, in `scope`. */+export function manifestDifferences(left: string, right: string, scope: WorktreeManifestScope, limit = 5): { paths: string[]; total: number } {+ const a = worktreeManifest(left, { scope, withFiles: true }).files!, b = worktreeManifest(right, { scope, withFiles: true }).files!;+ const differing = [...new Set([...Object.keys(a), ...Object.keys(b)])].sort().filter(path => a[path] !== b[path]);+ return { paths: differing.slice(0, limit), total: differing.length };+}diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 763315cc1e..515410417d 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -217,6 +217,7 @@ import { v213 } from './v213-core-edit-notices.ts';import { v214 } from './v214-wanted-links.ts';import { v215 } from './v215-facts-attributed-to.ts';import { v216 } from './v216-persistence-request-claim-phase.ts';+import { v217 } from './v217-purge-legacy-worktree-manifest-files.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -432,4 +433,5 @@ export const MIGRATIONS: Migration[] = [v214,v215,v216,+ v217,];diff --git a/src/core/schema-migrations/v217-purge-legacy-worktree-manifest-files.ts b/src/core/schema-migrations/v217-purge-legacy-worktree-manifest-files.tsnew file mode 100644index 0000000000..f11fc45720--- /dev/null+++ b/src/core/schema-migrations/v217-purge-legacy-worktree-manifest-files.ts@@ -0,0 +1,30 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// #6099 (privacy): releases before v0.60.69 stored a writer manifest's full+// per-file map (`files`: relative path -> unsalted sha256 of the file bytes) in+// persistence_worktrees.manifest and in clone recovery records+// (persistence_topology_changes.recovery.manifest). Those maps can name and+// fingerprint files Git ignores, such as `.env.local`. Nothing reads them: only+// the digest and file count are compared (persistence/worktree-manifest.ts+// `compactStoredManifest` keeps exactly those). This drops every remaining map,+// keeping `file_count` (counted from the map when it was not stored). Data-only+// and idempotent: a second run matches no row.+export const v217: Migration = {+ version: 217,+ name: 'purge_legacy_worktree_manifest_files',+ idempotent: true,+ sql: `+ UPDATE persistence_worktrees+ SET manifest = (manifest - 'files') || jsonb_build_object('file_count',+ COALESCE(manifest->'file_count', to_jsonb((SELECT count(*) FROM jsonb_object_keys(manifest->'files')))))+ WHERE jsonb_typeof(manifest) = 'object' AND jsonb_typeof(manifest->'files') = 'object';+ UPDATE persistence_topology_changes+ SET recovery = jsonb_set(recovery, '{manifest}', ((recovery->'manifest') - 'files') || jsonb_build_object('file_count',+ COALESCE(recovery->'manifest'->'file_count', to_jsonb((SELECT count(*) FROM jsonb_object_keys(recovery->'manifest'->'files'))))))+ WHERE jsonb_typeof(recovery) = 'object' AND jsonb_typeof(recovery->'manifest') = 'object'+ AND jsonb_typeof(recovery->'manifest'->'files') = 'object';+ `,+};diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 21cb2746b7..6bf4ee0d4c 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 211,+ "count": 212,"gaps": [17,18,@@ -35,7 +35,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 216,+ "latest": 217,"records": [{"handler": {@@ -3204,6 +3204,19 @@"transaction": "absent","verify": "absent","version": 216+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "purge_legacy_worktree_manifest_files",+ "sql": {+ "length": 798,+ "sha256": "60e812f52a977b94f1c0a3fa3657a3ec9394f09ff48dbef04550eb2b89f7d084"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 217}],"versions": [@@ -3417,7 +3430,8 @@213,214,215,- 216+ 216,+ 217]},"normalizer": "migrations-record-v1"diff --git a/test/persistence-manifest-git-scope.test.ts b/test/persistence-manifest-git-scope.test.tsnew file mode 100644index 0000000000..0959a8c91a--- /dev/null+++ b/test/persistence-manifest-git-scope.test.ts@@ -0,0 +1,179 @@+/**+ * #6099 (privacy): a Git checkout's writer manifest covers the files Git tracks, hashed from the working tree.+ * Gitignored files (secrets, build output) are never opened or hashed, so rebinding to a clean clone works+ * without copying them; a modified, missing or extra tracked file still refuses; a directory that is not a Git+ * checkout keeps the exact-copy manifest; a transfer an older release prepared in tree scope refuses with a+ * re-prepare fix instead of asking for ignored files; and migration v217 drops the legacy per-file maps.+ * PGLite always; Postgres too when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { chmodSync, cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } 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 { acceptWriterTransfer, getWorktreeBinding, prepareWriterTransfer, successorManifestMismatch, worktreeManifest } from '../src/core/persistence/ownership.ts';+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { v217 } from '../src/core/schema-migrations/v217-purge-legacy-worktree-manifest-files.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';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+function gitCheckout(root: string): void {+ mkdirSync(join(root, 'notes'), { recursive: true });+ mkdirSync(join(root, 'node_modules', 'pkg'), { recursive: true });+ git(root, 'init', '-q');+ writeFileSync(join(root, '.gitignore'), '.env.local\nnode_modules/\n');+ writeFileSync(join(root, 'notes', 'alice-example.md'), '---\ntitle: Alice Example\n---\nWorks at acme-example.\n');+ writeFileSync(join(root, 'notes', 'acme-example.md'), '---\ntitle: Acme Example\n---\nA company.\n');+ writeFileSync(join(root, '.env.local'), 'API_TOKEN=not-a-real-token\n');+ writeFileSync(join(root, 'node_modules', 'pkg', 'index.js'), 'module.exports = 1;\n');+ git(root, 'add', '.');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');+}++test('git scope hashes tracked files only and never opens an ignored one', () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-manifest-scope-'));+ try {+ const root = join(home, 'brain'); gitCheckout(root);+ // An unreadable ignored file would throw if it were opened.+ chmodSync(join(root, '.env.local'), 0o000);+ writeFileSync(join(root, 'notes', 'draft.md'), 'untracked, not ignored\n');+ const manifest = worktreeManifest(root);+ expect(manifest).toMatchObject({ scope: 'git', file_count: 3, untracked_count: 1 });+ const clone = join(home, 'clone'); execFileSync('git', ['clone', '-q', root, clone]);+ expect(worktreeManifest(clone).digest).toBe(manifest.digest);+ writeFileSync(join(clone, 'notes', 'alice-example.md'), 'changed\n');+ expect(worktreeManifest(clone).digest).not.toBe(manifest.digest);+ git(clone, 'checkout', '-q', '--', 'notes/alice-example.md');+ rmSync(join(clone, 'notes', 'acme-example.md'));+ expect(worktreeManifest(clone).digest).not.toBe(manifest.digest);+ // A plain directory nested inside an unrelated repository keeps the exact-copy tree scope.+ const nested = join(root, 'notes');+ expect(worktreeManifest(nested).scope).toBeUndefined();+ } finally { rmSync(home, { recursive: true, force: true }); }+});++test('a tracked submodule or symlink refuses writer_manifest_unsafe', () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-manifest-unsafe-'));+ try {+ const root = join(home, 'brain'); gitCheckout(root);+ execFileSync('ln', ['-s', 'alice-example.md', join(root, 'notes', 'link.md')]);+ git(root, 'add', 'notes/link.md');+ expect(() => worktreeManifest(root)).toThrow(expect.objectContaining({ code: 'writer_manifest_unsafe' }));+ } finally { rmSync(home, { recursive: true, force: true }); }+});++test('a tree-scope transfer an older release prepared refuses with a re-prepare fix on a Git successor', () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-manifest-rescope-'));+ try {+ const root = join(home, 'clone'); gitCheckout(root);+ const legacy = { digest: 'a'.repeat(64), file_count: 5 };+ const error = successorManifestMismatch('notes-example', root, legacy.digest, legacy, worktreeManifest(root, { scope: 'tree' }));+ expect(error).toMatchObject({ code: 'writer_manifest_rescope_required' });+ expect((error as { fix?: { argv: string[] } }).fix?.argv.slice(0, 6)).toEqual(['gbrain', 'sources', 'writer', 'transfer', 'prepare', 'notes-example']);+ expect(error.suggestion).toContain('Do not copy ignored files');+ const current = successorManifestMismatch('notes-example', root, 'b'.repeat(64), { ...legacy, scope: 'git' }, worktreeManifest(root));+ expect(current).toMatchObject({ code: 'writer_manifest_mismatch' });+ expect(current.suggestion).toContain('git clone');+ } finally { rmSync(home, { recursive: true, force: true }); }+});++for (const backend of testBackends()) describe(`#6099 git-scoped 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-manifest-git-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ if (backend === 'pglite') 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 }); }+ }+ const sourceId = (name: string) => `${name}-${backend}`;++ test('set-path to a clean clone commits without the ignored files; a changed tracked file names its path', () => fixture(async home => {+ const id = sourceId('git-rebind');+ const root = join(home, 'brain'); gitCheckout(root);+ expect(await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: id, path: root })).toMatchObject({ state: 'committed' });+ const [stored] = await engine.executeRaw<{ manifest: Record<string, unknown> }>(+ 'SELECT w.manifest FROM persistence_worktrees w JOIN persistence_source_bindings b ON b.worktree_id=w.id WHERE b.source_id=$1', [id]);+ expect(stored?.manifest).toMatchObject({ scope: 'git', file_count: 3 });+ expect(JSON.stringify(stored?.manifest)).not.toContain('.env.local');++ const dirty = join(home, 'dirty'); execFileSync('git', ['clone', '-q', root, dirty]);+ writeFileSync(join(dirty, 'notes', 'acme-example.md'), 'edited\n');+ await expect(runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: id, path: dirty }))+ .rejects.toMatchObject({ code: 'writer_manifest_mismatch', suggestion: expect.stringContaining('notes/acme-example.md') });++ const clone = join(home, 'clone'); execFileSync('git', ['clone', '-q', root, clone]);+ expect(await runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: id, path: clone })).toMatchObject({ state: 'committed' });+ expect((await getWorktreeBinding(engine, id))?.local_path).toBe(clone);+ }), 120_000);++ test('a directory that is not a Git checkout keeps exact-copy semantics', () => fixture(async home => {+ const id = sourceId('tree-rebind');+ const root = join(home, 'plain'); mkdirSync(join(root, 'notes'), { recursive: true });+ writeFileSync(join(root, 'notes', 'alice-example.md'), 'one\n');+ writeFileSync(join(root, '.env.local'), 'API_TOKEN=not-a-real-token\n');+ expect(await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: id, path: root })).toMatchObject({ state: 'committed' });+ const partial = join(home, 'partial');+ cpSync(root, partial, { recursive: true, filter: path => !isPhysicalRootMetadata(basename(path)) && basename(path) !== '.env.local' });+ await expect(runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: id, path: partial })).rejects.toMatchObject({ code: 'writer_manifest_mismatch' });+ writeFileSync(join(partial, '.env.local'), 'API_TOKEN=not-a-real-token\n');+ expect(await runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: id, path: partial })).toMatchObject({ state: 'committed' });+ }), 120_000);++ test('an in-flight transfer prepared in tree scope before the upgrade refuses with a re-prepare fix; re-prepared, a clean clone accepts', () => fixture(async home => {+ const id = sourceId('legacy-transfer');+ const root = join(home, 'owner'); gitCheckout(root);+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: id, path: root });+ const prepared = await prepareWriterTransfer(engine, id);+ // What an older release stored: the tree-scope digest over every file, ignored ones included, without a scope.+ const legacy = worktreeManifest(root, { scope: 'tree' });+ expect(legacy.scope).toBeUndefined();+ await engine.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [prepared.worktree_id, JSON.stringify(legacy)]);+ const clone = join(home, 'successor'); execFileSync('git', ['clone', '-q', root, clone]);+ await expect(acceptWriterTransfer(engine, id, clone, prepared.owner_epoch, legacy.digest)).rejects.toMatchObject({ code: 'writer_manifest_rescope_required' });+ const again = await prepareWriterTransfer(engine, id);+ expect(again.manifest).toMatchObject({ scope: 'git', file_count: 3 });+ await acceptWriterTransfer(engine, id, clone, again.owner_epoch, again.manifest.digest);+ expect((await getWorktreeBinding(engine, id))?.local_path).toBe(clone);+ }), 120_000);++ test('migration v217 drops legacy per-file manifest maps and keeps the count; a rerun changes nothing', () => fixture(async home => {+ const id = sourceId('legacy-map');+ const root = join(home, 'legacy'); gitCheckout(root);+ await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: id, path: root });+ const [binding] = await engine.executeRaw<{ worktree_id: string }>('SELECT worktree_id::text FROM persistence_source_bindings WHERE source_id=$1', [id]);+ const legacy = { digest: 'c'.repeat(64), files: { '.env.local': 'd'.repeat(64), 'notes/a.md': 'e'.repeat(64) }, canonical_stamp: 'stamp' };+ await engine.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [binding!.worktree_id, JSON.stringify(legacy)]);+ await engine.executeRaw(`INSERT INTO persistence_topology_changes(principal_id,request_id,digest,operation,source_id,state,recovery)+ VALUES(gen_random_uuid(),gen_random_uuid(),'legacy','reclone',$1,'recovering',$2::text::jsonb)`,+ [id, JSON.stringify({ kind: 'clone', manifest: { digest: 'f'.repeat(64), files: { '.env.local': 'd'.repeat(64) } } })]);+ await engine.transaction(tx => tx.runMigration(v217.version, v217.sql));+ const [after] = await engine.executeRaw<{ manifest: Record<string, unknown> }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [binding!.worktree_id]);+ expect(after?.manifest).toEqual({ digest: 'c'.repeat(64), file_count: 2, canonical_stamp: 'stamp' });+ const [record] = await engine.executeRaw<{ manifest: Record<string, unknown> }>(`SELECT recovery->'manifest' AS manifest FROM persistence_topology_changes WHERE source_id=$1 AND digest='legacy'`, [id]);+ expect(record?.manifest).toEqual({ digest: 'f'.repeat(64), file_count: 1 });+ await engine.executeRaw(`DELETE FROM persistence_topology_changes WHERE source_id=$1 AND digest='legacy'`, [id]);+ await engine.transaction(tx => tx.runMigration(v217.version, v217.sql));+ const [again] = await engine.executeRaw<{ manifest: Record<string, unknown> }>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid', [binding!.worktree_id]);+ expect(again?.manifest).toEqual(after!.manifest);+ }), 120_000);+});