import { execFile } from "node:child_process"; import { chmodSync, existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { promisify } from "node:util"; import { afterEach, expect, test } from "vitest"; import { WorkspaceRepositoryLock } from "../src/workspaces/git-repository.js"; import { WorkspaceRegistry } from "../src/workspaces/registry.js"; import type { WorkspaceRegistryConfig } from "../src/workspaces/types.js"; const validYaml = `workspace: schema_version: 2 id: psd-clinical name: Policlinico San Donato language: it dwh: engine: postgres database: postgres schema: datawarehouse supported_transports: [postgres_direct] semantic_index: vector_store: engine: pgvector database: postgres schema: vectors collection: clinical_documents dimensions: 768 distance: cosine supported_transports: [pgvector_direct] embedding: provider: ollama_compatible model: nomic-embed-text-v2-moe dimensions: 768 llm_policy: allowed: [zai/glm-5.2] `; const runFile = promisify(execFile); const temporaryRoots: string[] = []; afterEach(() => { temporaryRoots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })); }); async function git(cwd: string, args: string[]): Promise { await runFile("git", args, { cwd }); } async function fixture(workspaceSource = validYaml): Promise<{ root: string; remote: string; source: string; initialCommit: string; }> { const root = mkdtempSync(join(tmpdir(), "thoth-workspace-registry-")); temporaryRoots.push(root); const remote = join(root, "remote.git"); const source = join(root, "source"); await git(root, ["init", "--bare", "--initial-branch=main", remote]); mkdirSync(source); await git(source, ["init", "--initial-branch=main"]); await git(source, ["config", "user.name", "Workspace Registry Test"]); await git(source, ["config", "user.email", "workspace-registry@example.invalid"]); mkdirSync(join(source, "workspaces")); writeFileSync(join(source, "workspaces", "psd-clinical.yaml"), workspaceSource); await git(source, ["add", "workspaces/psd-clinical.yaml"]); await git(source, ["commit", "-m", "Initial workspace"]); await git(source, ["remote", "add", "origin", remote]); await git(source, ["push", "origin", "main"]); const { stdout } = await runFile("git", ["rev-parse", "HEAD"], { cwd: source }); return { root, remote, source, initialCommit: stdout.trim() }; } function config(root: string, remoteUrl: string): WorkspaceRegistryConfig { return { root, remoteUrl, branch: "main", gitAuthorName: "Workspace Registry Test", gitAuthorEmail: "workspace-registry@example.invalid", installationId: "test", secretRoots: [], maxImportBytes: 1024, maxImportEntries: 1, }; } async function pushInvalidWorkspace(source: string): Promise { writeFileSync(join(source, "workspaces", "psd-clinical.yaml"), "workspace: invalid\n"); await git(source, ["add", "workspaces/psd-clinical.yaml"]); await git(source, ["commit", "-m", "Invalid workspace"]); await git(source, ["push", "origin", "main"]); } test("bootstraps a checkout and activates a validated immutable snapshot", async () => { const remote = await fixture(); const registry = new WorkspaceRegistry(config(join(remote.root, "registry"), remote.remote)); const status = await registry.bootstrap(); expect(status.head).toMatch(/^[0-9a-f]{40}$/); expect(existsSync(registry.snapshotPath(status.head!, "psd-clinical"))).toBe(true); await expect(registry.read("psd-clinical")).resolves.toMatchObject({ revision: { commit: remote.initialCommit, id: "psd-clinical" }, }); }); test("lists a v1 descriptor in migration-required state without rendering operational artifacts", async () => { const legacyYaml = validYaml.replace( " database: postgres\n schema: vectors\n", "", ).replace("schema_version: 2", "schema_version: 1"); const remote = await fixture(legacyYaml); const registry = new WorkspaceRegistry(config(join(remote.root, "registry"), remote.remote)); const status = await registry.bootstrap(); const [revision] = await registry.list(); expect(revision).toMatchObject({ state: "migration_required" }); await expect(registry.read("psd-clinical")).resolves.toMatchObject({ workspace: { workspace: { schema_version: 1 } }, }); expect(existsSync(join(remote.root, "registry", "snapshots", status.head!, "psd-clinical.env.example"))).toBe(false); expect(existsSync(join(remote.root, "registry", "snapshots", status.head!, "psd-clinical.md"))).toBe(false); }); test("keeps the last valid snapshot when a pulled commit has invalid YAML", async () => { const remote = await fixture(); const registry = new WorkspaceRegistry(config(join(remote.root, "registry"), remote.remote)); await registry.bootstrap(); await pushInvalidWorkspace(remote.source); await expect(registry.pull()).rejects.toMatchObject({ code: "workspace_invalid" }); await expect(registry.read("psd-clinical")).resolves.toMatchObject({ revision: { commit: remote.initialCommit }, }); }); test("does not bypass an existing live advisory repository lock", async () => { const remote = await fixture(); const root = join(remote.root, "registry"); const registry = new WorkspaceRegistry(config(root, remote.remote)); const lock = new WorkspaceRepositoryLock(join(root, "locks")); let release!: () => void; let started!: () => void; const held = lock.run(async () => { started(); await new Promise((resolve) => { release = resolve; }); }); await new Promise((resolve) => { started = resolve; }); try { await expect(registry.bootstrap()).rejects.toMatchObject({ code: "workspace_stale" }); } finally { release(); await held; } }); test("rejects a symbolic-link registry root before creating a lock below it", async () => { const remote = await fixture(); const target = join(remote.root, "registry-target"); const root = join(remote.root, "registry-link"); mkdirSync(target); symlinkSync(target, root); const registry = new WorkspaceRegistry(config(root, remote.remote)); await expect(registry.bootstrap()).rejects.toMatchObject({ code: "git_unavailable" }); expect(existsSync(join(target, "locks"))).toBe(false); }); test("rejects a locally-ahead checkout instead of activating local-only content", async () => { const remote = await fixture(); const root = join(remote.root, "registry"); const registry = new WorkspaceRegistry(config(root, remote.remote)); await registry.bootstrap(); const checkout = join(root, "repo"); writeFileSync(join(checkout, "workspaces", "psd-clinical.yaml"), validYaml.replace( "name: Policlinico San Donato", "name: Local only workspace", )); await git(checkout, ["config", "user.name", "Workspace Registry Test"]); await git(checkout, ["config", "user.email", "workspace-registry@example.invalid"]); await git(checkout, ["add", "workspaces/psd-clinical.yaml"]); await git(checkout, ["commit", "-m", "Local-only workspace"]); await expect(registry.pull()).rejects.toMatchObject({ code: "git_non_fast_forward" }); await expect(registry.read("psd-clinical")).resolves.toMatchObject({ revision: { commit: remote.initialCommit }, workspace: { workspace: { name: "Policlinico San Donato" } }, }); }); test("recovers a dead-process advisory lock while preserving active snapshot safety", async () => { const remote = await fixture(); const root = join(remote.root, "registry"); mkdirSync(join(root, "locks"), { recursive: true }); writeFileSync(join(root, "locks", "repository.lock"), JSON.stringify({ pid: 999_999_999 })); const registry = new WorkspaceRegistry(config(root, remote.remote)); await expect(registry.bootstrap()).resolves.toMatchObject({ head: remote.initialCommit, degraded: false, }); }); test.each(["manifest", "blob", "workspace", "document"])( "rejects a corrupted %s snapshot component instead of reporting it active", async (component) => { const remote = await fixture(); const root = join(remote.root, "registry"); const registry = new WorkspaceRegistry(config(root, remote.remote)); await registry.bootstrap(); const snapshot = join(root, "snapshots", remote.initialCommit); if (component === "manifest") { const file = join(snapshot, "snapshot.json"); chmodSync(file, 0o600); writeFileSync(file, "{"); } if (component === "blob") { const activePath = join(root, "state", "active.json"); const active = JSON.parse(readFileSync(activePath, "utf8")); active.revisions[0].blob = "not-a-git-blob"; writeFileSync(activePath, JSON.stringify(active)); } if (component === "workspace") { const file = join(snapshot, "psd-clinical.yaml"); chmodSync(file, 0o600); writeFileSync(file, "truncated"); } if (component === "document") rmSync(join(snapshot, "psd-clinical.md")); await expect(registry.list()).rejects.toMatchObject({ code: "workspace_invalid" }); await expect(registry.read("psd-clinical")).rejects.toMatchObject({ code: "workspace_invalid" }); }, ); test("rejects a corrupt fallback snapshot instead of returning degraded active state", async () => { const remote = await fixture(); const root = join(remote.root, "registry"); const registry = new WorkspaceRegistry(config(root, remote.remote)); await registry.bootstrap(); const document = join(root, "snapshots", remote.initialCommit, "psd-clinical.md"); chmodSync(document, 0o600); writeFileSync(document, "corrupt"); rmSync(remote.remote, { recursive: true, force: true }); await expect(registry.pull()).rejects.toMatchObject({ code: "workspace_invalid" }); });