Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(hcc): resolve workspace-layout round-trip collision with newest-wins backup

Alfredo Lopezf738b2cb2a79
diff --git a/host-context-controller/src/statelessDeployment.ts b/host-context-controller/src/statelessDeployment.ts
index 301d90492..c7c52df60 100644
--- a/host-context-controller/src/statelessDeployment.ts
+++ b/host-context-controller/src/statelessDeployment.ts
@@ -17,6 +17,10 @@ export const STATELESS_PULL_POLICY_REJECTED_CONDITION_TYPE = 'StatelessPullPolic
const IMMUTABLE_IMAGE_TAG_PATTERN = /^sha-[0-9a-f]{7,}$/
/** Where the workspace-layout initContainer mounts the workspace PVC ROOT. */
const WORKSPACE_PVC_ROOT_MOUNT_PATH = '/mnt/workspace-root'
+
+function shellSingleQuote(value: string): string {
+ return `'${value.replace(/'/g, `'"'"'`)}'`
+}
/**
* Idempotent workspace-layout migration run before mcp-host starts on
* STATELESS Hosts only (Stage 1.2). The initContainer mounts the workspace
@@ -25,29 +29,163 @@ const WORKSPACE_PVC_ROOT_MOUNT_PATH = '/mnt/workspace-root'
* state/ → durable session state (mounted at /var/lib/clerum/state)
* Legacy content at the PVC root moves into workspace/; legacy SQLite files
* (state.db + WAL/SHM) move into state/. Every move is a same-filesystem
- * rename and `sync` flushes the directory updates, so a crash mid-migration
- * never loses data and a re-run is a no-op. lost+found stays put: it is
- * root-owned on ext4 volumes and never user data. No chown/chmod — the
- * container runs as the same uid/fsGroup (1001) that owns the PVC content.
+ * rename and `sync` flushes the directory updates.
+ *
+ * Round-trip resolution (Addendum 6 item 6): a stateful<->stateless round-trip
+ * on the shared PVC can leave BOTH a root state.db (the freshest data, from the
+ * stateful life the operator just left) AND an earlier stateless life's
+ * state/state.db. Newest-source-wins: the older destination is preserved (never
+ * deleted) as state/<db>.pre-<timestamp>.bak, the fresher root source then
+ * migrates in via the normal path, and the resolution is logged loudly. This is
+ * genuinely idempotent across round-trips — a post-migration run (no source) is
+ * a no-op, and each later collision backs up under a NEW unique suffix.
+ *
+ * Genuinely ambiguous states still fail before the first move, preserving every
+ * source for operator recovery: SQLite sources SPLIT across root and workspace,
+ * a workspace SQLite source colliding with the durable destination, duplicate
+ * non-SQLite entries, symlinks, and non-directory managed paths.
+ * lost+found stays put: it is root-owned on ext4 volumes and never user data.
+ * No chown/chmod — the container runs as the same uid/fsGroup (1001) that owns
+ * the PVC content.
*/
-const WORKSPACE_LAYOUT_INIT_SCRIPT = `set -eu
-root=${WORKSPACE_PVC_ROOT_MOUNT_PATH}
-mkdir -p "$root/workspace" "$root/state"
+export function buildWorkspaceLayoutInitScript(root = WORKSPACE_PVC_ROOT_MOUNT_PATH): string {
+ return `set -eu
+root=${shellSingleQuote(root)}
+fail_layout() {
+ echo "workspace layout migration unsafe: $1" >&2
+ exit 1
+}
+canonical_dir() {
+ (CDPATH= cd -P "$1" 2>/dev/null && pwd -P)
+}
+assert_managed_dir() {
+ path="$1"
+ label="$2"
+ [ ! -L "$path" ] || fail_layout "$label directory is a symlink: $path"
+ [ -d "$path" ] || fail_layout "$label path is not a directory: $path"
+ resolved="$(canonical_dir "$path")" || fail_layout "cannot resolve $label directory: $path"
+ case "$resolved" in
+ "$root_real"/*) ;;
+ *) fail_layout "$label directory escapes the workspace PVC root: $path" ;;
+ esac
+}
+
+[ ! -L "$root" ] || fail_layout "workspace PVC root is a symlink: $root"
+[ -d "$root" ] || fail_layout "workspace PVC root is not a directory: $root"
+root_real="$(canonical_dir "$root")" || fail_layout "cannot resolve workspace PVC root: $root"
+[ "$root_real" != "/" ] || fail_layout "workspace PVC root resolves to /"
+
+# Validate both managed paths before creating either one. A symlink or regular
+# file must never redirect a migration outside the mounted PVC.
+for dir in workspace state; do
+ path="$root/$dir"
+ [ ! -L "$path" ] || fail_layout "$dir directory is a symlink: $path"
+ if [ -e "$path" ] && [ ! -d "$path" ]; then
+ fail_layout "$dir path is not a directory: $path"
+ fi
+done
+for dir in workspace state; do
+ path="$root/$dir"
+ [ -d "$path" ] || mkdir "$path"
+ assert_managed_dir "$path" "$dir"
+done
+# Validate every destination before the first rename: a later SQLite collision
+# must not leave earlier root entries moved into a partial layout.
for entry in "$root"/* "$root"/.[!.]* "$root"/..?*; do
[ -e "$entry" ] || [ -L "$entry" ] || continue
base="$(basename "$entry")"
case "$base" in
workspace|state|lost+found) continue ;;
esac
+ [ ! -L "$entry" ] || fail_layout "legacy source is a symlink: $entry"
+ case "$base" in
+ state.db|state.db-wal|state.db-shm) continue ;;
+ esac
+ if [ -e "$root/workspace/$base" ] || [ -L "$root/workspace/$base" ]; then
+ echo "workspace layout migration collision: destination exists: $root/workspace/$base" >&2
+ exit 1
+ fi
+done
+root_sqlite_source=0
+workspace_sqlite_source=0
+for db in state.db state.db-wal state.db-shm; do
+ [ ! -L "$root/$db" ] || fail_layout "legacy SQLite source is a symlink: $root/$db"
+ [ ! -L "$root/workspace/$db" ] || fail_layout "workspace SQLite source is a symlink: $root/workspace/$db"
+ [ ! -L "$root/state/$db" ] || fail_layout "durable SQLite destination is a symlink: $root/state/$db"
+ if [ -e "$root/$db" ] || [ -L "$root/$db" ]; then root_sqlite_source=1; fi
+ if [ -e "$root/workspace/$db" ] || [ -L "$root/workspace/$db" ]; then workspace_sqlite_source=1; fi
+done
+if [ "$root_sqlite_source" -eq 1 ] && [ "$workspace_sqlite_source" -eq 1 ]; then
+ echo "workspace layout migration collision: SQLite artifacts are split across root and workspace" >&2
+ exit 1
+fi
+# Newest-source-wins round-trip resolution (Addendum 6 item 6). A confirmed ROOT
+# SQLite source colliding with an existing durable state/ destination is a
+# stateful<->stateless round-trip: the operator just left the stateful life
+# (root state.db is the freshest data) over an earlier stateless life's
+# state/state.db. Preserve the older destination as state/<db>.pre-<ts>.bak
+# (NOTHING is ever deleted), then let the fresher root source migrate in via the
+# normal path below. The destination is proven non-symlink above.
+root_dest_collision=0
+if [ "$root_sqlite_source" -eq 1 ]; then
+ for db in state.db state.db-wal state.db-shm; do
+ if [ -e "$root/state/$db" ] || [ -L "$root/state/$db" ]; then root_dest_collision=1; fi
+ done
+fi
+if [ "$root_dest_collision" -eq 1 ]; then
+ # One timestamped backup namespace per collision; guard uniqueness so two
+ # round-trips within the same second (or a re-collision) never overwrite an
+ # existing backup.
+ bak_ts="$(date -u +%Y%m%d%H%M%S)"
+ bak_suffix="$bak_ts"
+ bak_seq=0
+ while [ -e "$root/state/state.db.pre-$bak_suffix.bak" ] \
+ || [ -e "$root/state/state.db-wal.pre-$bak_suffix.bak" ] \
+ || [ -e "$root/state/state.db-shm.pre-$bak_suffix.bak" ]; do
+ bak_seq=$((bak_seq + 1))
+ bak_suffix="$bak_ts-$bak_seq"
+ done
+ backed_up=""
+ for db in state.db state.db-wal state.db-shm; do
+ if [ -e "$root/state/$db" ]; then
+ mv "$root/state/$db" "$root/state/$db.pre-$bak_suffix.bak"
+ backed_up="$backed_up $db"
+ fi
+ done
+ echo "workspace layout migration: newest-source-wins round-trip resolution -- backed up prior destination(s)$backed_up under state/*.pre-$bak_suffix.bak; migrating the fresher root SQLite source into state/" >&2
+fi
+# A WORKSPACE SQLite source colliding with the durable destination is a genuinely
+# ambiguous partial-migration state (not a clean round-trip): fail loud,
+# preserving every source for operator recovery.
+for db in state.db state.db-wal state.db-shm; do
+ if [ -e "$root/workspace/$db" ] || [ -L "$root/workspace/$db" ]; then
+ if [ -e "$root/state/$db" ] || [ -L "$root/state/$db" ]; then
+ echo "workspace layout migration collision: destination exists: $root/state/$db" >&2
+ exit 1
+ fi
+ fi
+done
+for entry in "$root"/* "$root"/.[!.]* "$root"/..?*; do
+ [ -e "$entry" ] || [ -L "$entry" ] || continue
+ base="$(basename "$entry")"
+ case "$base" in
+ workspace|state|lost+found) continue ;;
+ esac
+ assert_managed_dir "$root/workspace" workspace
+ [ ! -L "$entry" ] || fail_layout "legacy source became a symlink: $entry"
mv "$entry" "$root/workspace/$base"
done
for db in state.db state.db-wal state.db-shm; do
if [ -e "$root/workspace/$db" ]; then
+ assert_managed_dir "$root/workspace" workspace
+ assert_managed_dir "$root/state" state
+ [ ! -L "$root/workspace/$db" ] || fail_layout "workspace SQLite source became a symlink: $root/workspace/$db"
mv "$root/workspace/$db" "$root/state/$db"
fi
done
sync
`
+}
/**
* True when an image reference cannot change contents under the same name:
@@ -184,7 +322,7 @@ export function buildWorkspaceLayoutInitContainer(
name: 'workspace-layout-init',
image,
imagePullPolicy,
- command: ['/bin/sh', '-c', WORKSPACE_LAYOUT_INIT_SCRIPT],
+ command: ['/bin/sh', '-c', buildWorkspaceLayoutInitScript()],
volumeMounts: [{ name: 'workspace', mountPath: WORKSPACE_PVC_ROOT_MOUNT_PATH }],
resources: {
requests: { memory: '32Mi', cpu: '10m' },
diff --git a/host-context-controller/test/hostReconciler.lifecycle.test.ts b/host-context-controller/test/hostReconciler.lifecycle.test.ts
index 8a937827b..c8d653513 100644
--- a/host-context-controller/test/hostReconciler.lifecycle.test.ts
+++ b/host-context-controller/test/hostReconciler.lifecycle.test.ts
@@ -1697,7 +1697,8 @@ describe('HostReconciler stateless lifecycle — initContainer and mounts', () =
expect(init.name).toBe('workspace-layout-init')
expect(init.image).toBe('clerum/mcp-host:0.6.0')
expect(init.command?.[0]).toBe('/bin/sh')
- expect(init.command?.[2]).toContain('mkdir -p "$root/workspace" "$root/state"')
+ expect(init.command?.[2]).toContain('assert_managed_dir "$root/workspace" workspace')
+ expect(init.command?.[2]).toContain('directory is a symlink')
expect(init.command?.[2]).toContain('state.db-wal')
expect(init.volumeMounts).toEqual([{ name: 'workspace', mountPath: '/mnt/workspace-root' }])
expect(init.securityContext).toEqual({
diff --git a/host-context-controller/test/statelessDeployment.workspaceLayout.test.ts b/host-context-controller/test/statelessDeployment.workspaceLayout.test.ts
new file mode 100644
index 000000000..790d3833b
--- /dev/null
+++ b/host-context-controller/test/statelessDeployment.workspaceLayout.test.ts
@@ -0,0 +1,331 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { execFileSync, spawnSync } from 'node:child_process'
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { buildWorkspaceLayoutInitScript } from '../src/statelessDeployment'
+
+const roots: string[] = []
+
+function makeRoot(): string {
+ const root = mkdtempSync(join(tmpdir(), 'clerum-workspace-layout-'))
+ roots.push(root)
+ return root
+}
+
+function runMigration(root: string): void {
+ execFileSync('/bin/sh', ['-c', buildWorkspaceLayoutInitScript(root)], { stdio: 'pipe' })
+}
+
+function migrationFailure(root: string): { stderr?: Buffer } {
+ try {
+ runMigration(root)
+ } catch (error) {
+ return error as { stderr?: Buffer }
+ }
+ throw new Error('expected workspace layout migration to fail')
+}
+
+// Captures stderr even on SUCCESS (execFileSync only surfaces stderr on throw),
+// so the loud round-trip resolution log can be asserted on a passing migration.
+function runMigrationCapture(root: string): { status: number; stderr: string } {
+ const res = spawnSync('/bin/sh', ['-c', buildWorkspaceLayoutInitScript(root)], {
+ encoding: 'utf8',
+ })
+ if (res.error) throw res.error
+ return { status: res.status ?? -1, stderr: res.stderr ?? '' }
+}
+
+function stateBackups(root: string, prefix = 'state.db'): string[] {
+ return readdirSync(join(root, 'state'))
+ .filter(name => name.startsWith(`${prefix}.pre-`) && name.endsWith('.bak'))
+ .sort()
+}
+
+afterEach(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
+})
+
+describe('stateless workspace layout migration', () => {
+ it('moves legacy workspace and SQLite files once and is idempotent', () => {
+ const root = makeRoot()
+ writeFileSync(join(root, 'notes.md'), 'workspace-data')
+ writeFileSync(join(root, 'state.db'), 'durable-db')
+
+ runMigration(root)
+ runMigration(root)
+
+ expect(readFileSync(join(root, 'workspace', 'notes.md'), 'utf8')).toBe('workspace-data')
+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('durable-db')
+ }, // This is the only case that launches the migration shell twice. Keep its
+ // runner budget above the generic 5s limit so CI process contention cannot
+ // turn a completed idempotency check into a harness timeout.
+ 15_000)
+
+ it('finishes a partial migration whose SQLite source is already under workspace', () => {
+ const root = makeRoot()
+ mkdirSync(join(root, 'workspace'))
+ writeFileSync(join(root, 'workspace', 'state.db'), 'durable-db')
+
+ runMigration(root)
+
+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('durable-db')
+ })
+
+ it.each([
+ {
+ rootArtifact: 'state.db',
+ workspaceArtifact: 'state.db-wal',
+ },
+ {
+ rootArtifact: 'state.db-shm',
+ workspaceArtifact: 'state.db',
+ },
+ ])(
+ 'fails closed when $rootArtifact and $workspaceArtifact split SQLite source authority',
+ ({ rootArtifact, workspaceArtifact }) => {
+ const root = makeRoot()
+ mkdirSync(join(root, 'workspace'))
+ writeFileSync(join(root, 'notes.md'), 'must-stay-root')
+ writeFileSync(join(root, rootArtifact), 'root-artifact')
+ writeFileSync(join(root, 'workspace', workspaceArtifact), 'workspace-artifact')
+
+ expect(String(migrationFailure(root).stderr)).toContain(
+ 'SQLite artifacts are split across root and workspace'
+ )
+ expect(readFileSync(join(root, 'notes.md'), 'utf8')).toBe('must-stay-root')
+ expect(readFileSync(join(root, rootArtifact), 'utf8')).toBe('root-artifact')
+ expect(readFileSync(join(root, 'workspace', workspaceArtifact), 'utf8')).toBe(
+ 'workspace-artifact'
+ )
+ }
+ )
+
+ it('fails closed without overwriting a duplicate workspace entry', () => {
+ const root = makeRoot()
+ mkdirSync(join(root, 'workspace'))
+ writeFileSync(join(root, 'notes.md'), 'legacy-data')
+ writeFileSync(join(root, 'workspace', 'notes.md'), 'current-data')
+
+ expect(String(migrationFailure(root).stderr)).toContain('workspace layout migration collision')
+ expect(readFileSync(join(root, 'notes.md'), 'utf8')).toBe('legacy-data')
+ expect(readFileSync(join(root, 'workspace', 'notes.md'), 'utf8')).toBe('current-data')
+ })
+
+ it('fails closed without overwriting an existing durable SQLite file', () => {
+ const root = makeRoot()
+ mkdirSync(join(root, 'workspace'))
+ mkdirSync(join(root, 'state'))
+ writeFileSync(join(root, 'workspace', 'state.db'), 'legacy-db')
+ writeFileSync(join(root, 'state', 'state.db'), 'current-db')
+
+ expect(String(migrationFailure(root).stderr)).toContain('workspace layout migration collision')
+ expect(readFileSync(join(root, 'workspace', 'state.db'), 'utf8')).toBe('legacy-db')
+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('current-db')
+ })
+
+ it('resolves a root SQLite round-trip collision: backs up the older destination and migrates the fresher root source', () => {
+ // Addendum 6 item 6 (newest-source-wins): a stateful<->stateless round-trip
+ // leaves BOTH root state.db (freshest — the stateful life just left) and an
+ // earlier stateless life's state/state.db. The migration must self-heal, not
+ // deadlock: back up the older destination (never delete) and migrate the
+ // fresher root source in, while non-SQLite root content still moves to
+ // workspace/.
+ const root = makeRoot()
+ mkdirSync(join(root, 'workspace'))
+ mkdirSync(join(root, 'state'))
+ writeFileSync(join(root, 'notes.md'), 'must-migrate-to-workspace')
+ writeFileSync(join(root, 'state.db'), 'fresh-stateful-db')
+ writeFileSync(join(root, 'state', 'state.db'), 'older-stateless-db')
+
+ const { status, stderr } = runMigrationCapture(root)
+
+ expect(status).toBe(0)
+ // Fresher root data migrated into the durable destination.
+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('fresh-stateful-db')
+ expect(existsSync(join(root, 'state.db'))).toBe(false)
+ // Non-SQLite root content still migrated to workspace/.
+ expect(readFileSync(join(root, 'workspace', 'notes.md'), 'utf8')).toBe(
+ 'must-migrate-to-workspace'
+ )
+ // Older destination preserved (never deleted) as a timestamped backup.
+ const backups = stateBackups(root)
+ expect(backups).toHaveLength(1)
+ expect(readFileSync(join(root, 'state', backups[0]), 'utf8')).toBe('older-stateless-db')
+ // Loud one-line resolution log naming the backup + migration.
+ expect(stderr).toContain('newest-source-wins round-trip resolution')
+ expect(stderr).toContain('.pre-')
+ })
+
+ it('renames wal/shm destination companions in lockstep with the state.db backup', () => {
+ const root = makeRoot()
+ mkdirSync(join(root, 'state'))
+ for (const db of ['state.db', 'state.db-wal', 'state.db-shm']) {
+ writeFileSync(join(root, db), `fresh-${db}`)
+ writeFileSync(join(root, 'state', db), `older-${db}`)
+ }
+
+ const { status } = runMigrationCapture(root)
+ expect(status).toBe(0)
+
+ // All three fresher root companions migrated into state/.
+ for (const db of ['state.db', 'state.db-wal', 'state.db-shm']) {
+ expect(readFileSync(join(root, 'state', db), 'utf8')).toBe(`fresh-${db}`)
+ expect(existsSync(join(root, db))).toBe(false)
+ }
+ // All three older destinations backed up under ONE shared timestamp suffix.
+ const backups = readdirSync(join(root, 'state'))
+ .filter(name => name.endsWith('.bak'))
+ .sort()
+ expect(backups).toHaveLength(3)
+ const suffixes = new Set(
+ backups.map(name => name.replace(/^state\.db(-wal|-shm)?\.pre-/, '').replace(/\.bak$/, ''))
+ )
+ expect(suffixes.size).toBe(1)
+ expect(
+ readFileSync(join(root, 'state', backups.find(f => f.startsWith('state.db.pre-'))!), 'utf8')
+ ).toBe('older-state.db')
+ expect(
+ readFileSync(
+ join(root, 'state', backups.find(f => f.startsWith('state.db-wal.pre-'))!),
+ 'utf8'
+ )
+ ).toBe('older-state.db-wal')
+ expect(
+ readFileSync(
+ join(root, 'state', backups.find(f => f.startsWith('state.db-shm.pre-'))!),
+ 'utf8'
+ )
+ ).toBe('older-state.db-shm')
+ })
+
+ it('is idempotent after a backup: a second run with no root source is a no-op', () => {
+ const root = makeRoot()
+ mkdirSync(join(root, 'state'))
+ writeFileSync(join(root, 'state.db'), 'fresh-db')
+ writeFileSync(join(root, 'state', 'state.db'), 'older-db')
+
+ const first = runMigrationCapture(root)
+ expect(first.status).toBe(0)
+ const afterFirst = stateBackups(root)
+ expect(afterFirst).toHaveLength(1)
+
+ const second = runMigrationCapture(root)
+ expect(second.status).toBe(0)
+ // No new backup, destination unchanged, no resolution log on the no-op run.
+ expect(stateBackups(root)).toEqual(afterFirst)
+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('fresh-db')
+ expect(second.stderr).not.toContain('newest-source-wins')
+ })
+
+ it('backs up under a NEW unique suffix on each later round-trip collision', () => {
+ const root = makeRoot()
+ mkdirSync(join(root, 'state'))
+ writeFileSync(join(root, 'state.db'), 'stateful-life-1')
+ writeFileSync(join(root, 'state', 'state.db'), 'stateless-life-0')
+
+ expect(runMigrationCapture(root).status).toBe(0)
+ // A new stateful life re-creates the root source for a second round-trip.
+ writeFileSync(join(root, 'state.db'), 'stateful-life-2')
+ expect(runMigrationCapture(root).status).toBe(0)
+
+ // Two distinct backups: nothing was overwritten across the two collisions.
+ const backups = stateBackups(root)
+ expect(backups).toHaveLength(2)
+ const contents = backups.map(name => readFileSync(join(root, 'state', name), 'utf8')).sort()
+ expect(contents).toEqual(['stateful-life-1', 'stateless-life-0'].sort())
+ // Final durable state is the newest life.
+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('stateful-life-2')
+ })
+
+ it('keeps a WORKSPACE SQLite source colliding with the destination fail-loud (genuinely ambiguous)', () => {
+ // Only the ROOT round-trip collision self-heals. A workspace SQLite source
+ // (an interrupted partial migration) colliding with an existing durable
+ // destination stays fail-loud, preserving every source for recovery.
+ const root = makeRoot()
+ mkdirSync(join(root, 'workspace'))
+ mkdirSync(join(root, 'state'))
+ writeFileSync(join(root, 'workspace', 'state.db'), 'legacy-db')
+ writeFileSync(join(root, 'state', 'state.db'), 'current-db')
+
+ expect(String(migrationFailure(root).stderr)).toContain('workspace layout migration collision')
+ expect(readFileSync(join(root, 'workspace', 'state.db'), 'utf8')).toBe('legacy-db')
+ expect(readFileSync(join(root, 'state', 'state.db'), 'utf8')).toBe('current-db')
+ expect(stateBackups(root)).toHaveLength(0)
+ })
+
+ it.each(['workspace', 'state'])(
+ 'rejects a symlinked %s directory without writing through it',
+ managedDir => {
+ const root = makeRoot()
+ const outside = makeRoot()
+ symlinkSync(outside, join(root, managedDir), 'dir')
+ writeFileSync(join(root, managedDir === 'workspace' ? 'notes.md' : 'state.db'), 'must-stay')
+
+ expect(String(migrationFailure(root).stderr)).toContain(
+ `${managedDir} directory is a symlink`
+ )
+ expect(
+ readFileSync(join(root, managedDir === 'workspace' ? 'notes.md' : 'state.db'), 'utf8')
+ ).toBe('must-stay')
+ expect(existsSync(join(outside, 'notes.md'))).toBe(false)
+ expect(existsSync(join(outside, 'state.db'))).toBe(false)
+ }
+ )
+
+ it('rejects a symlinked PVC root without touching its target', () => {
+ const target = makeRoot()
+ const parent = makeRoot()
+ const linkedRoot = join(parent, 'workspace-root')
+ writeFileSync(join(target, 'notes.md'), 'target-data')
+ symlinkSync(target, linkedRoot, 'dir')
+
+ expect(String(migrationFailure(linkedRoot).stderr)).toContain('PVC root is a symlink')
+ expect(readFileSync(join(target, 'notes.md'), 'utf8')).toBe('target-data')
+ expect(existsSync(join(target, 'workspace'))).toBe(false)
+ expect(existsSync(join(target, 'state'))).toBe(false)
+ })
+
+ it('rejects a symlinked legacy source without moving it or touching its target', () => {
+ const root = makeRoot()
+ const outside = makeRoot()
+ const outsideTarget = join(outside, 'target.txt')
+ const source = join(root, 'notes.md')
+ writeFileSync(outsideTarget, 'outside-data')
+ symlinkSync(outsideTarget, source)
+
+ expect(String(migrationFailure(root).stderr)).toContain('legacy source is a symlink')
+ expect(lstatSync(source).isSymbolicLink()).toBe(true)
+ expect(readFileSync(outsideTarget, 'utf8')).toBe('outside-data')
+ expect(existsSync(join(root, 'workspace', 'notes.md'))).toBe(false)
+ })
+
+ it.each(['workspace', 'state'])(
+ 'rejects a symlinked SQLite artifact under %s without touching its target',
+ sqliteDir => {
+ const root = makeRoot()
+ const outside = makeRoot()
+ const outsideTarget = join(outside, 'outside-state.db')
+ mkdirSync(join(root, sqliteDir))
+ writeFileSync(outsideTarget, 'outside-db')
+ symlinkSync(outsideTarget, join(root, sqliteDir, 'state.db'))
+ if (sqliteDir === 'state') writeFileSync(join(root, 'state.db'), 'legacy-db')
+
+ expect(String(migrationFailure(root).stderr)).toContain('SQLite')
+ expect(readFileSync(outsideTarget, 'utf8')).toBe('outside-db')
+ expect(lstatSync(join(root, sqliteDir, 'state.db')).isSymbolicLink()).toBe(true)
+ if (sqliteDir === 'state')
+ expect(readFileSync(join(root, 'state.db'), 'utf8')).toBe('legacy-db')
+ }
+ )
+})