Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): retire a source without hashing a checkout it never compares (#5200)

garrytan9180b628872c
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 3a5aac5740..f7eae87a0e 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -58,4 +58,4 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast
- `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; `withTopologyLocks(..., { relocation: true })` (rebind only, #5914 P1.3c) verifies a recorded root that now resolves through a symlink to the rebind target with `inspectRelocatedPhysicalRoot` instead of the realpath check, and the rebind transaction then calls `relocatePhysicalRoot` and moves `local_path`, the host binding and `relative_path` in place of a new worktree; 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: manifests are Git-scoped for Git checkouts; see `worktree-manifest.ts` in [managed sync and persistence stalls](persistence-stalls.md).
+- `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; `withTopologyLocks(..., { relocation: true })` (rebind only, #5914 P1.3c) verifies a recorded root that now resolves through a symlink to the rebind target with `inspectRelocatedPhysicalRoot` instead of the realpath check, and the rebind transaction then calls `relocatePhysicalRoot` and moves `local_path`, the host binding and `relative_path` in place of a new worktree; 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. #5200 (W14 P1.4): only a lifecycle operation that compares or records checkout bytes (`add` at an existing root, `claim`, `rebind`, `restore`; `reclone` in `topology-clone.ts`) walks and hashes the checkout; `archive`, `remove` and `purge` skip the walk when every binding of the source already carries a verified `digest` and refresh the stored manifest's `canonical_stamp` in place (`manifest = COALESCE(manifest,'{}') || {canonical_stamp}`), so a symlink that appeared after the claim no longer refuses a retire (a binding claimed before activation has no digest yet, and the retire records that first manifest because clone recovery needs it), and every dry run reports `manifest_required` so preview and real run agree (`test/source-retire-symlink-manifest.test.ts`). The `writer_manifest_unsafe` text names the manifest, not a transfer, since claim and rebind raise it too. 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: manifests are Git-scoped for Git checkouts; see `worktree-manifest.ts` in [managed sync and persistence stalls](persistence-stalls.md).
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index c21751e868..c6be7b6d73 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -379,6 +379,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.156.0', text: 'Schema-pack YAML now decodes quoted scalars: a double-quoted value carries the JSON escape subset and a single-quoted value is literal text with `\'\'` for one quote, so a link-type regex written as `"\\\\b"` loads as `\\b` and a `gbrain schema` mutation writes it back unchanged (before, every mutation doubled the backslashes of every quoted scalar). A hand-written double-quoted value that meant two backslashes now means one. A mutation whose emitted YAML does not read back as the manifest refuses with `schema_pack_emit_mismatch` and leaves the file unchanged; a pack file above 8 MiB refuses to load with `schema_pack_too_large` instead of being read, and `gbrain doctor` warns on a mutable pack above 1 MiB with the hand-repair runbook.' },
// W14 PR1 P1.8 (#5431). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.156.0', text: 'A Git rename onto a slug a soft-deleted page still holds now moves the page onto that slug with its id, history, edges, facts and aliases in one transaction; the tombstone keeps its own history under `<slug>~purged-<id>`, a name no file can take, so nothing is hard-deleted. A rename whose destination a live page holds still imports the renamed content there, but the old row\'s edges, timeline, versions, facts, withdrawals and aliases now move to that page (with `[[old-slug]]` recorded as an alias) before the old row is soft-deleted, instead of being stranded on the tombstone. Any other database error on the rename fails the file and leaves the sync checkpoint where it was, where it used to be swallowed. The renamed page\'s `source_path` is repaired inside the rename transaction, so a later `gbrain sync --full` cannot read the live page as a removed file.' },
+ // W14 PR1 P1.4 (#5200). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.156.0', text: '`gbrain sources archive`, `remove` and `purge` no longer walk and hash a canonical checkout that already has a verified manifest: they compare no bytes, so a symlink or submodule that appeared in the checkout after it was claimed no longer refuses them with `writer_manifest_unsafe` while their dry run said they would succeed. The stored manifest keeps its digest and gets a fresh `canonical_stamp`; a source claimed before activation, whose manifest was never recorded, still records it on retire. Claim, set-path (rebind), restore and reclone still hash the checkout, and every lifecycle dry run now reports `manifest_required`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.ts
index e827a0a537..354fa5514e 100644
--- a/src/core/persistence/source-lifecycle.ts
+++ b/src/core/persistence/source-lifecycle.ts
@@ -146,7 +146,16 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
if(input.expectedIncarnation&&input.expectedIncarnation!==before?.incarnation) throw opError('source_changed','The source was replaced.',
`Source '${input.sourceId}' was removed and re-added after expected_incarnation was read, so nothing was changed. Read its current incarnation with the command in fix and confirm the ${input.operation} still applies before running it again.`,
{fix:ownerStatusFix(input.sourceId)});
- if(input.dryRun) return {dry_run:true,operation:input.operation,source_id:input.sourceId,source_incarnation:before?.incarnation??null,path:root?.source??before?.local_path??null};
+ // #5200 (W14 P1.4): only an operation that compares or records checkout bytes hashes the manifest (add at an existing
+ // root, claim, rebind, restore; reclone hashes in topology-clone.ts). Retiring a source (archive, remove, purge) compares
+ // nothing, so when every binding already carries a verified digest it skips the walk and refreshes the stored manifest's
+ // canonical_stamp in place; a symlink that appeared in the checkout after the claim no longer refuses a retire its dry
+ // run said would succeed. A binding claimed before activation has no digest yet, and the retire records that first
+ // manifest (clone recovery needs it), so its dry run says so.
+ const retire=['archive','remove','purge'].includes(input.operation);
+ const manifestRequired=!retire||(await engine.executeRaw<{digest:string|null}>(
+ `SELECT w.manifest->>'digest' AS digest FROM persistence_source_bindings b JOIN persistence_worktrees w ON w.id=b.worktree_id WHERE b.source_id=$1`,[input.sourceId])).some(row=>!row.digest);
+ if(input.dryRun) return {dry_run:true,operation:input.operation,source_id:input.sourceId,source_incarnation:before?.incarnation??null,path:root?.source??before?.local_path??null,manifest_required:manifestRequired};
return 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.
@@ -156,9 +165,10 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
if(!existsSync(path)) {
if(input.operation==='add'&&input.createDirectory&&path===root?.worktree)continue;
// #5219: retiring may skip a vanished checkout; the transaction proves the source is empty and its sole member.
- if(['archive','remove','purge'].includes(input.operation)&&!root){missingCheckout=path;continue;}
+ if(retire&&!root){missingCheckout=path;continue;}
throw missingCheckoutError(input.sourceId,path);
}
+ if(!manifestRequired)continue;
const manifest=worktreeManifest(path,{progress:humanManifestProgress()});
manifests.set(path,manifest);
}
@@ -272,6 +282,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
for(const id of worktrees){
const [host]=await tx.executeRaw<{local_path:string}>('SELECT local_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[id,localHostId()]);
if(host&&manifests.has(host.local_path)) await tx.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid',[id,JSON.stringify({...manifests.get(host.local_path),canonical_stamp:await topologyCanonicalStamp(tx,id)})]);
+ else if(!manifestRequired&&host) await tx.executeRaw(`UPDATE persistence_worktrees SET manifest=COALESCE(manifest,'{}'::jsonb)||jsonb_build_object('canonical_stamp',$2::text) WHERE id=$1::uuid`,[id,await topologyCanonicalStamp(tx,id)]);
}
// This durable registry intentionally retains old checkout paths, so
// stale installations cannot write after a source moved or disappeared.
diff --git a/src/core/persistence/worktree-manifest.ts b/src/core/persistence/worktree-manifest.ts
index 5cc02e976e..151e2d1759 100644
--- a/src/core/persistence/worktree-manifest.ts
+++ b/src/core/persistence/worktree-manifest.ts
@@ -105,8 +105,8 @@ function treePaths(canonical: string): { paths: string[]; untracked?: number } {
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.isSymbolicLink()) throw unsafe('The canonical checkout manifest requires a symlink-free checkout.',
+ `${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 step again.`);
if (info.isDirectory()) visit(path);
else if (info.isFile()) paths.push(relative(canonical, path).split(sep).join('/'));
}
@@ -129,8 +129,8 @@ function trackedPaths(canonical: string): { paths: string[]; untracked: number }
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.`);
+ if (mode === '120000') throw unsafe('The canonical checkout manifest requires a symlink-free checkout.',
+ `${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 step again.`);
paths.add(rel);
}
const others = hardenedGitSync(canonical, ['ls-files', '-z', '--others', '--exclude-standard'], GIT_LIMITS);
@@ -157,8 +157,8 @@ function trackedBytes(canonical: string, rel: string): Buffer | null {
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 (real !== path || lstatSync(path).isSymbolicLink()) throw unsafe('The canonical checkout manifest requires a symlink-free checkout.',
+ `${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 step again.`);
if (!lstatSync(path).isFile()) return null;
return readFileSync(path);
}
diff --git a/test/e2e/source-retire-symlink-manifest.test.ts b/test/e2e/source-retire-symlink-manifest.test.ts
new file mode 100644
index 0000000000..612d42b9cb
--- /dev/null
+++ b/test/e2e/source-retire-symlink-manifest.test.ts
@@ -0,0 +1,4 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+// #5200 (W14 P1.4): retire skips the manifest walk and refreshes canonical_stamp in place on Postgres.
+await registerPostgresTests(() => import('../source-retire-symlink-manifest.test.ts'));
diff --git a/test/source-retire-symlink-manifest.test.ts b/test/source-retire-symlink-manifest.test.ts
new file mode 100644
index 0000000000..3a877da964
--- /dev/null
+++ b/test/source-retire-symlink-manifest.test.ts
@@ -0,0 +1,123 @@
+/**
+ * #5200 (W14 P1.4): retiring a source (archive / remove / purge) compares no
+ * bytes, so it must not walk and hash the canonical checkout; before, a
+ * symlink that appeared in the checkout after the claim made every retire
+ * refuse `writer_manifest_unsafe` while the dry run said it would succeed.
+ * Retire now refreshes `manifest.canonical_stamp` in place and the dry run
+ * reports `manifest_required: false`. Operations that compare or record bytes
+ * (claim, rebind) still hash, and their refusal no longer talks about a
+ * "transfer" when raised from a claim.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { 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 { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const databaseUrl = process.env.DATABASE_URL;
+for (const flavor of ['pglite', ...(databaseUrl ? ['postgres'] : [])] as const) describe(`retire a source whose checkout grew a symlink (${flavor})`, () => {
+ let engine: BrainEngine;
+ let closePostgres: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (flavor === 'postgres') { const pg = await isolatedPersistencePostgres(databaseUrl!); engine = pg.engine; closePostgres = pg.close; }
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { if (!engine) return; await disposePersistenceConsumer(engine); if (closePostgres) await closePostgres(); else await engine.disconnect(); });
+
+ const manifest = async (source: string) => (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`, [source]))
+ .map(r => typeof r.manifest === 'string' ? JSON.parse(r.manifest) as Record<string, unknown> : r.manifest)[0] ?? null;
+ const recorded = async (source: string) => { const m = await manifest(source); if (!m) throw new Error(`no manifest for ${source}`); return m; };
+
+ /** Claims the source (managed, so the claim records a manifest) at a symlink-free checkout, then drops a symlink into it. */
+ async function fixture(source: string, run: (home: string, checkout: string) => Promise<void>, opts: { classicClaim?: boolean } = {}) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-retire-symlink-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ if (flavor === 'pglite') await resetPgliteState(engine as PGLiteEngine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await registerLocalWriter(engine, 'cli');
+ const checkout = join(home, 'profile');
+ mkdirSync(checkout);
+ writeFileSync(join(checkout, 'example.md'), '---\ntitle: Example\ntype: note\n---\n\nCanonical\n');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, checkout]);
+ if (opts.classicClaim) await claimWorktree(engine, source, checkout);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ if (!opts.classicClaim) await claimWorktree(engine, source, checkout);
+ writeFileSync(join(home, 'outside.md'), 'linked\n');
+ symlinkSync(join(home, 'outside.md'), join(checkout, 'linked.md'));
+ try { await run(home, checkout); }
+ finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [source]);
+ }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }
+
+ test('archive and purge skip the manifest walk, refresh canonical_stamp in place and agree with their dry runs', () => fixture('linked-profile', async () => {
+ const before = await recorded('linked-profile');
+ expect(typeof before.digest).toBe('string');
+ // A stale stamp written over the claim's makes the in-place refresh observable.
+ await engine.executeRaw(`UPDATE persistence_worktrees SET manifest=manifest||'{"canonical_stamp":"stale"}'::jsonb WHERE id IN (SELECT worktree_id FROM persistence_source_bindings WHERE source_id=$1)`, ['linked-profile']);
+
+ const preview = await runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: 'linked-profile', dryRun: true });
+ expect(preview).toMatchObject({ dry_run: true, operation: 'archive', manifest_required: false });
+
+ const archived = await runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: 'linked-profile' });
+ expect(archived).toMatchObject({ operation: 'archive', source_id: 'linked-profile' });
+ expect((await engine.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', ['linked-profile']))[0].archived).toBe(true);
+ const after = await recorded('linked-profile');
+ expect(after.digest).toBe(before.digest);
+ expect(after.file_count).toBe(before.file_count);
+ expect(typeof after.canonical_stamp).toBe('string');
+ expect(after.canonical_stamp).not.toBe('stale');
+
+ const purgePreview = await runManagedSourceLifecycle(engine, { operation: 'purge', sourceId: 'linked-profile', confirmDestructive: true, dryRun: true });
+ expect(purgePreview).toMatchObject({ dry_run: true, operation: 'purge', manifest_required: false });
+ const purged = await runManagedSourceLifecycle(engine, { operation: 'purge', sourceId: 'linked-profile', confirmDestructive: true });
+ expect(purged).toMatchObject({ operation: 'purge', pages_deleted: 0 });
+ expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', ['linked-profile'])).toEqual([]);
+ }), 60_000);
+
+ test('remove skips the walk too', () => fixture('linked-remove', async () => {
+ expect(await runManagedSourceLifecycle(engine, { operation: 'remove', sourceId: 'linked-remove', confirmDestructive: true, dryRun: true }))
+ .toMatchObject({ dry_run: true, operation: 'remove', manifest_required: false });
+ const removed = await runManagedSourceLifecycle(engine, { operation: 'remove', sourceId: 'linked-remove', confirmDestructive: true });
+ expect(removed).toMatchObject({ operation: 'remove', pages_deleted: 0 });
+ expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', ['linked-remove'])).toEqual([]);
+ }), 60_000);
+
+ test('a binding claimed before activation has no digest yet: the retire records that first manifest and its dry run says so', () => fixture('classic-profile', async () => {
+ expect(await manifest('classic-profile')).toBeNull();
+ expect(await runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: 'classic-profile', dryRun: true }))
+ .toMatchObject({ dry_run: true, operation: 'archive', manifest_required: true });
+ const error = await runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: 'classic-profile' }).catch((e: Error) => e) as Error & Record<string, string>;
+ expect(error).toMatchObject({ code: 'writer_manifest_unsafe' });
+ rmSync(join(process.env.GBRAIN_HOME!, 'profile', 'linked.md'));
+ await runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: 'classic-profile' });
+ expect(typeof (await recorded('classic-profile')).digest).toBe('string');
+ }, { classicClaim: true }), 60_000);
+
+ test('rebind still hashes: the symlink refuses, and the refusal does not call a non-transfer step a transfer', () => fixture('linked-rebind', async home => {
+ const next = join(home, 'next');
+ mkdirSync(next);
+ writeFileSync(join(next, 'example.md'), '---\ntitle: Example\ntype: note\n---\n\nCanonical\n');
+ expect(await runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: 'linked-rebind', path: next, dryRun: true }))
+ .toMatchObject({ dry_run: true, operation: 'rebind', manifest_required: true });
+ const error = await runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: 'linked-rebind', path: next }).catch((e: Error) => e) as Error & Record<string, string>;
+ expect(error).toMatchObject({ code: 'writer_manifest_unsafe' });
+ expect(error.message).not.toContain('transfer');
+ expect(error.suggestion).toContain('linked.md');
+ expect(error.suggestion).not.toContain('transfer step');
+ }), 60_000);
+});