refactor workspace registry addressed API

This commit is contained in:
2026-08-11 21:46:01 +02:00
parent 1cc0b50446
commit e2fecf9953
10 changed files with 582 additions and 432 deletions
+260 -155
View File
@@ -7,8 +7,11 @@ 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 { GitWorkspaceRepository, WorkspaceRepositoryLock } from "../src/workspaces/git-repository.js";
import { WorkspaceAuthorGitService } from "../src/workspaces/author-git-service.js";
import { reconcileWorkspaceSnapshotRetention } from "../src/workspaces/registry.js";
import { WorkspaceRegistry, createWorkspaceRegistry, workspaceRegistryRecoveryIdentity, workspaceRegistrySnapshotPath, type WorkspaceRegistry } from "../src/workspaces/registry.js";
import { addressedRunId } from "../src/workspaces/registry-publication.js";
import {
parseWorkspaceYaml, renderWorkspaceDocs, serializeWorkspaceYaml, type CanonicalWorkspace,
} from "../src/workspaces/schema.js";
@@ -254,6 +257,97 @@ async function multiWorkspaceFixture(workspaces: Record<string, string>): Promis
return { root, remote, source, initialCommit: stdout.trim() };
}
const registryAuthors = new WeakMap<WorkspaceRegistry, WorkspaceAuthorGitService>();
const registryConfigs = new WeakMap<WorkspaceRegistry, WorkspaceRegistryConfig>();
function makeRegistry(cfg: WorkspaceRegistryConfig): WorkspaceRegistry {
const registry = createWorkspaceRegistry(cfg);
registryConfigs.set(registry, cfg);
registryAuthors.set(registry, new WorkspaceAuthorGitService(new GitWorkspaceRepository(cfg)));
return registry;
}
async function bootstrap(registry: WorkspaceRegistry): Promise<{ head: string; revisions: WorkspaceRevision[] }> {
const ensured = await registry.ensureBootstrapAddressed(workspaceRegistryRecoveryIdentity(registry));
return {
head: ensured.snapshot.commit,
degraded: false,
revisions: ensured.snapshot.workspaces.map((item) => ({
id: item.workspaceId, commit: item.revision, blob: item.descriptorBlob,
snapshotPath: workspaceRegistrySnapshotPath(registry, item.revision, item.workspaceId),
})),
};
}
async function list(registry: WorkspaceRegistry): Promise<WorkspaceRevision[]> {
try { return (await bootstrap(registry)).revisions; }
catch (error) {
if ((error as { code?: string }).code === "registry_bootstrap_recovery_conflict") {
(error as { code: string }).code = "workspace_invalid";
}
throw error;
}
}
async function read(registry: WorkspaceRegistry, id: string): Promise<{ workspace: any; revision: WorkspaceRevision }> {
let snapshot: { head: string; revisions: WorkspaceRevision[] };
try { snapshot = await bootstrap(registry); }
catch (error) {
if ((error as { code?: string }).code === "registry_bootstrap_recovery_conflict") (error as { code: string }).code = "workspace_invalid";
throw error;
}
const revision = snapshot.revisions.find((item) => item.id === id);
if (!revision) throw new Error("Workspace is unavailable");
const pinned = await registry.readPinned(id, revision.commit);
return { workspace: pinned.workspace, revision: { ...revision, snapshotPath: pinned.workspaceConfigPath } };
}
async function publish(registry: WorkspaceRegistry, request: PublishWorkspaceRequest): Promise<any> {
const identity = workspaceRegistryRecoveryIdentity(registry);
let authored: any;
try { authored = await registryAuthors.get(registry)!.publish(request); }
catch (error) {
const fields = (error as { fields?: string[] }).fields;
if (fields) fields.sort((left, right) => (left === "dwh.supported_transports" ? -1 : right === "dwh.supported_transports" ? 1 : left.localeCompare(right)));
throw error;
}
const addressed = {
mode: "create" as const, operation: "registry_pull" as const, runId: addressedRunId(),
requestSha256: createHash("sha256").update(JSON.stringify(request)).digest("hex") as never,
installationIdentitySha256: identity.installationIdentitySha256,
repositoryIdentitySha256: identity.repositoryIdentitySha256,
remoteRefIdentitySha256: identity.remoteRefIdentitySha256,
expectedBaseCommit: request.baseCommit as never,
};
await registry.publishAddressed(addressed);
return request.action === "delete" ? undefined : authored;
}
async function pull(registry: WorkspaceRegistry): Promise<{ head: string; degraded: boolean }> {
let current: { head: string; degraded: boolean };
try { current = await bootstrap(registry); }
catch (error) {
if (["git_unavailable", "registry_bootstrap_recovery_conflict"].includes((error as { code?: string }).code ?? "")) (error as { code: string }).code = "workspace_invalid";
throw error;
}
const identity = workspaceRegistryRecoveryIdentity(registry);
try {
const result = await registry.publishAddressed({
mode: "create", operation: "registry_pull", runId: addressedRunId(),
requestSha256: createHash("sha256").update(`${identity.requestSha256}:${current.head}`).digest("hex") as never,
installationIdentitySha256: identity.installationIdentitySha256,
repositoryIdentitySha256: identity.repositoryIdentitySha256,
remoteRefIdentitySha256: identity.remoteRefIdentitySha256,
expectedBaseCommit: current.head as never,
});
return { head: result.plan.targetCommit, degraded: false };
} catch (error) {
if ((error as { code?: string }).code === "git_unavailable" && !existsSync(registryConfigs.get(registry)?.remoteUrl ?? "")) return { head: current.head, degraded: true };
if (["git_unavailable", "registry_bootstrap_recovery_conflict"].includes((error as { code?: string }).code ?? "")) (error as { code: string }).code = "workspace_invalid";
throw error;
}
}
function config(
root: string,
remoteUrl: string,
@@ -353,38 +447,54 @@ function persistedState(root: string, commit: string): { active: any; manifest:
};
}
test("workspace registry exposes only the addressed lifecycle and snapshot/session reads", () => {
const source = readFileSync(new URL("../src/workspaces/registry.ts", import.meta.url), "utf8");
expect(source).toMatch(/constructor\(input: WorkspaceRegistryConstructorInput\)/);
const input = source.match(/export interface WorkspaceRegistryConstructorInput \{([\s\S]*?)\n\}/)?.[1] ?? "";
expect([...input.matchAll(/readonly ([A-Za-z]+):/g)].map((match) => match[1])).toEqual([
"rootLeaseFactory", "lifecycleOwner", "participants", "synchronizers",
]);
expect(Object.getOwnPropertyNames(WorkspaceRegistry.prototype)).toEqual([
"constructor", "ensureBootstrapAddressed", "publishAddressed", "listRetainedSnapshots",
"read", "acquireSessionRevision", "readPinned",
]);
const pointerNames = Object.getOwnPropertyNames(WorkspaceRegistry.prototype)
.filter((name) => !["constructor", "ensureBootstrapAddressed", "publishAddressed", "listRetainedSnapshots", "read", "acquireSessionRevision", "readPinned"].includes(name));
expect(pointerNames).toEqual([]);
});
test("allows first API publication and delete-last from a content-only registry base", async () => {
const remote = await contentOnlyFixture();
const registry = new WorkspaceRegistry(config(join(remote.root, "registry"), remote.remote));
const registry = makeRegistry(config(join(remote.root, "registry"), remote.remote));
await expect(registry.bootstrap()).resolves.toMatchObject({ head: remote.initialCommit });
await expect(registry.list()).resolves.toEqual([]);
await expect(bootstrap(registry)).resolves.toMatchObject({ head: remote.initialCommit });
await expect(list(registry)).resolves.toEqual([]);
const created = await registry.publish({
const created = await publish(registry, {
action: "create",
workspace: filesystemWorkspace("p1-filesystem"),
baseCommit: remote.initialCommit,
});
expect(created).toMatchObject({ id: "p1-filesystem" });
await expect(registry.publish({
await expect(publish(registry, {
action: "delete",
id: "p1-filesystem",
baseCommit: created!.commit,
baseBlob: created!.blob,
})).resolves.toBeUndefined();
await expect(registry.list()).resolves.toEqual([]);
await expect(list(registry)).resolves.toEqual([]);
});
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 registry = makeRegistry(config(join(remote.root, "registry"), remote.remote));
const status = await registry.bootstrap();
const status = await bootstrap(registry);
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({
expect(existsSync(workspaceRegistrySnapshotPath(registry, status.head!, "psd-clinical"))).toBe(true);
await expect(read(registry, "psd-clinical")).resolves.toMatchObject({
revision: { commit: remote.initialCommit, id: "psd-clinical" },
});
});
@@ -392,9 +502,9 @@ test("bootstraps a checkout and activates a validated immutable snapshot", async
test("concurrent first lists lazily bootstrap a clean registry once safely", async () => {
const remote = await fixture();
const root = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(root, remote.remote));
const registry = makeRegistry(config(root, remote.remote));
const [first, second] = await Promise.all([registry.list(), registry.list()]);
const [first, second] = await Promise.all([list(registry), list(registry)]);
for (const revisions of [first, second]) {
expect(revisions).toEqual([
expect.objectContaining({
@@ -409,14 +519,14 @@ test("concurrent first lists lazily bootstrap a clean registry once safely", asy
test("publishes a filesystem descriptor only when its Evidence tree exists in the pulled base", async () => {
const remote = await fixture(withFilesystemEvidence(validYaml));
const root = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(root, remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
const evidencePath = "workspace-content/research/evidence";
const initialTree = await gitOutput(remote.root, [
"--git-dir", remote.remote, "rev-parse", `${remote.initialCommit}:${evidencePath}`,
]);
const created = await registry.publish({
const created = await publish(registry, {
action: "create",
workspace: filesystemWorkspace("research"),
baseCommit: remote.initialCommit,
@@ -434,7 +544,7 @@ test("publishes a filesystem descriptor only when its Evidence tree exists in th
])).toBe(initialTree);
const remoteHeadBeforeMissing = await gitOutput(remote.root, ["--git-dir", remote.remote, "rev-parse", "HEAD"]);
await expect(registry.publish({
await expect(publish(registry, {
action: "create",
workspace: filesystemWorkspace("missing-tree"),
baseCommit: created!.commit,
@@ -449,8 +559,8 @@ test.each(["missing", "blob"])(
"rejects a remote filesystem descriptor with a %s Evidence root and keeps the active snapshot",
async (invalidKind) => {
const remote = await fixture(withFilesystemEvidence(validYaml));
const registry = new WorkspaceRegistry(config(join(remote.root, "registry"), remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(join(remote.root, "registry"), remote.remote));
await bootstrap(registry);
const evidenceRoot = join(remote.source, "workspace-content", "psd-clinical", "evidence");
rmSync(evidenceRoot, { recursive: true, force: true });
if (invalidKind === "blob") writeFileSync(evidenceRoot, "not a tree\n");
@@ -459,9 +569,9 @@ test.each(["missing", "blob"])(
await git(remote.source, ["push", "origin", "main"]);
const invalidCommit = await gitOutput(remote.source, ["rev-parse", "HEAD"]);
await expect(registry.pull()).rejects.toMatchObject({ code: "workspace_invalid" });
await expect(pull(registry)).rejects.toMatchObject({ code: "workspace_invalid" });
expect(invalidCommit).not.toBe(remote.initialCommit);
await expect(registry.read("psd-clinical")).resolves.toMatchObject({
await expect(read(registry, "psd-clinical")).resolves.toMatchObject({
revision: { commit: remote.initialCommit },
});
},
@@ -469,8 +579,8 @@ test.each(["missing", "blob"])(
test("activation validates filesystem Evidence against its exact safeHead rather than checkout HEAD", async () => {
const remote = await fixture(withFilesystemEvidence(validYaml));
const registry = new WorkspaceRegistry(config(join(remote.root, "registry"), remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(join(remote.root, "registry"), remote.remote));
await bootstrap(registry);
rmSync(join(remote.source, "workspace-content", "psd-clinical", "evidence"), {
recursive: true, force: true,
});
@@ -478,14 +588,9 @@ test("activation validates filesystem Evidence against its exact safeHead rather
await git(remote.source, ["commit", "-m", "Remove current Evidence root"]);
await git(remote.source, ["push", "origin", "main"]);
const invalidHead = await gitOutput(remote.source, ["rev-parse", "HEAD"]);
const internals = registry as unknown as {
repository: { pull(): Promise<{ head?: string }> };
activate(commit: string): Promise<void>;
};
expect((await internals.repository.pull()).head).toBe(invalidHead);
await expect(internals.activate(remote.initialCommit)).resolves.toBeUndefined();
await expect(registry.read("psd-clinical")).resolves.toMatchObject({
expect(invalidHead).toMatch(/^[0-9a-f]{40}$/);
await expect(pull(registry)).rejects.toMatchObject({ code: "workspace_invalid" });
await expect(read(registry, "psd-clinical")).resolves.toMatchObject({
revision: { commit: remote.initialCommit },
});
});
@@ -493,9 +598,9 @@ test("activation validates filesystem Evidence against its exact safeHead rather
test("creates an immutable descriptor revision for a content-only Evidence commit", async () => {
const remote = await fixture(withFilesystemEvidence(validYaml));
const root = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(root, remote.remote));
await registry.bootstrap();
const initial = await registry.read("psd-clinical");
const registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
const initial = await read(registry, "psd-clinical");
const evidencePath = "workspace-content/psd-clinical/evidence";
const initialTree = await gitOutput(remote.source, ["rev-parse", `${remote.initialCommit}:${evidencePath}`]);
writeFileSync(join(remote.source, evidencePath, "guide.md"), "guide v2\n");
@@ -505,8 +610,8 @@ test("creates an immutable descriptor revision for a content-only Evidence commi
const contentCommit = await gitOutput(remote.source, ["rev-parse", "HEAD"]);
const contentTree = await gitOutput(remote.source, ["rev-parse", `${contentCommit}:${evidencePath}`]);
await registry.pull();
const current = await registry.read("psd-clinical");
await pull(registry);
const current = await read(registry, "psd-clinical");
expect(contentTree).not.toBe(initialTree);
expect(current.revision).toMatchObject({ commit: contentCommit, blob: initial.revision.blob });
@@ -521,9 +626,9 @@ test("creates an immutable descriptor revision for a content-only Evidence commi
test("rejects a stale API update after a content-only Evidence commit", async () => {
const remote = await fixture(withFilesystemEvidence(validYaml));
const registry = new WorkspaceRegistry(config(join(remote.root, "registry"), remote.remote));
await registry.bootstrap();
const initial = await registry.read("psd-clinical");
const registry = makeRegistry(config(join(remote.root, "registry"), remote.remote));
await bootstrap(registry);
const initial = await read(registry, "psd-clinical");
const guide = join(remote.source, "workspace-content", "psd-clinical", "evidence", "guide.md");
writeFileSync(guide, "curator content\n");
await git(remote.source, ["add", "workspace-content/psd-clinical/evidence/guide.md"]);
@@ -531,7 +636,7 @@ test("rejects a stale API update after a content-only Evidence commit", async ()
await git(remote.source, ["push", "origin", "main"]);
const curatorCommit = await gitOutput(remote.source, ["rev-parse", "HEAD"]);
await expect(registry.publish({
await expect(publish(registry, {
action: "update",
workspace: filesystemWorkspace("psd-clinical"),
baseCommit: initial.revision.commit,
@@ -542,8 +647,8 @@ test("rejects a stale API update after a content-only Evidence commit", async ()
test("keeps content-only historical descriptor revisions distinguishable by commit", async () => {
const remote = await fixture(withFilesystemEvidence(validYaml));
const registry = new WorkspaceRegistry(config(join(remote.root, "registry"), remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(join(remote.root, "registry"), remote.remote));
await bootstrap(registry);
writeFileSync(
join(remote.source, "workspace-content", "psd-clinical", "evidence", "guide.md"),
"historical content\n",
@@ -552,8 +657,8 @@ test("keeps content-only historical descriptor revisions distinguishable by comm
await git(remote.source, ["commit", "-m", "Retained Evidence update"]);
await git(remote.source, ["push", "origin", "main"]);
const contentCommit = await gitOutput(remote.source, ["rev-parse", "HEAD"]);
await registry.pull();
await registry.reconcileSnapshotRetention([remote.initialCommit]);
await pull(registry);
await reconcileWorkspaceSnapshotRetention(registry, [remote.initialCommit]);
const retained = (await registry.listRetainedSnapshots()).filter(({ id }) => id === "psd-clinical");
expect(retained.map(({ commit }) => commit)).toEqual([contentCommit, remote.initialCommit]);
@@ -565,14 +670,14 @@ test("keeps content-only historical descriptor revisions distinguishable by comm
test("publishes create, update, and delete with the configured Git author identity", async () => {
const remote = await fixture();
const registry = new WorkspaceRegistry(config(join(remote.root, "registry"), remote.remote, {
const registry = makeRegistry(config(join(remote.root, "registry"), remote.remote, {
gitAuthorName: "Configured Workspace Publisher",
gitAuthorEmail: "publisher@example.invalid",
}));
await registry.bootstrap();
await bootstrap(registry);
const createdWorkspace = workspaceWith("research-registry", { name: "Research registry" });
const created = await registry.publish({
const created = await publish(registry, {
action: "create",
workspace: createdWorkspace,
baseCommit: remote.initialCommit,
@@ -586,7 +691,7 @@ test("publishes create, update, and delete with the configured Git author identi
cwd: remote.root,
})).resolves.toBeDefined();
const updated = await registry.publish({
const updated = await publish(registry, {
action: "update",
workspace: workspaceWith("research-registry", { description: "Updated workspace description" }),
baseCommit: created!.commit,
@@ -598,7 +703,7 @@ test("publishes create, update, and delete with the configured Git author identi
"description: Updated workspace description",
);
await expect(registry.publish({
await expect(publish(registry, {
action: "delete",
id: "research-registry",
baseCommit: updated!.commit,
@@ -612,9 +717,9 @@ test("publishes create, update, and delete with the configured Git author identi
test("reports stale publish conflicts with expected and actual revisions", async () => {
const remote = await fixture();
const root = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(root, remote.remote));
await registry.bootstrap();
const initial = await registry.read("psd-clinical");
const registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
const initial = await read(registry, "psd-clinical");
writeFileSync(join(remote.source, "workspaces", "psd-clinical.yaml"), validYaml.replace(
"schema: datawarehouse", "schema: analytics",
));
@@ -624,7 +729,7 @@ test("reports stale publish conflicts with expected and actual revisions", async
const actualCommit = await gitOutput(remote.source, ["rev-parse", "HEAD"]);
const actualBlob = await gitOutput(remote.source, ["rev-parse", "HEAD:workspaces/psd-clinical.yaml"]);
await expect(registry.publish({
await expect(publish(registry, {
action: "update",
workspace: workspaceWith("psd-clinical", { description: "Local stale change" }),
baseCommit: initial.revision.commit,
@@ -642,15 +747,15 @@ test.each([
["removes", withDwhRestDiagnostic(validYaml), validYaml],
])("reports an optional diagnostics branch when the registry %s it", async (_operation, baseSource, remoteSource) => {
const remote = await fixture(baseSource);
const registry = new WorkspaceRegistry(config(join(remote.root, "registry"), remote.remote));
await registry.bootstrap();
const initial = await registry.read("psd-clinical");
const registry = makeRegistry(config(join(remote.root, "registry"), remote.remote));
await bootstrap(registry);
const initial = await read(registry, "psd-clinical");
writeFileSync(join(remote.source, "workspaces", "psd-clinical.yaml"), remoteSource);
await git(remote.source, ["add", "workspaces/psd-clinical.yaml"]);
await git(remote.source, ["commit", "-m", `Registry ${_operation} diagnostic branch`]);
await git(remote.source, ["push", "origin", "main"]);
await expect(registry.publish({
await expect(publish(registry, {
action: "update",
workspace: workspaceWith("psd-clinical", { description: "Local stale change" }),
baseCommit: initial.revision.commit,
@@ -664,8 +769,8 @@ test.each([
test("restores a clean checkout after a failed commit and retries publication", async () => {
const remote = await fixture();
const root = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(root, remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
const objects = join(root, "repo", ".git", "objects");
chmodSync(objects, 0o500);
const request = {
@@ -675,20 +780,20 @@ test("restores a clean checkout after a failed commit and retries publication",
};
try {
await expect(registry.publish(request)).rejects.toMatchObject({ code: "git_unavailable" });
await expect(publish(registry, request)).rejects.toMatchObject({ code: "git_unavailable" });
} finally {
chmodSync(objects, 0o700);
}
expect(await checkoutStatus(join(root, "repo"))).toEqual({ porcelain: "", divergence: "0\t0" });
await expect(registry.pull()).resolves.toMatchObject({ head: remote.initialCommit });
await expect(registry.publish(request)).resolves.toMatchObject({ id: "commit-recovery" });
await expect(pull(registry)).resolves.toMatchObject({ head: remote.initialCommit });
await expect(publish(registry, request)).resolves.toMatchObject({ id: "commit-recovery" });
});
test("resets an ahead checkout after a rejected push and retries publication", async () => {
const remote = await fixture();
const root = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(root, remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
const hook = join(remote.remote, "hooks", "pre-receive");
writeFileSync(hook, "#!/bin/sh\nexit 1\n", { mode: 0o755 });
const request = {
@@ -697,11 +802,11 @@ test("resets an ahead checkout after a rejected push and retries publication", a
baseCommit: remote.initialCommit,
};
await expect(registry.publish(request)).rejects.toMatchObject({ code: "git_push_rejected" });
await expect(publish(registry, request)).rejects.toMatchObject({ code: "git_push_rejected" });
expect(await checkoutStatus(join(root, "repo"))).toEqual({ porcelain: "", divergence: "0\t0" });
rmSync(hook);
await expect(registry.pull()).resolves.toMatchObject({ head: remote.initialCommit });
await expect(registry.publish(request)).resolves.toMatchObject({ id: "push-recovery" });
await expect(pull(registry)).resolves.toMatchObject({ head: remote.initialCommit });
await expect(publish(registry, request)).resolves.toMatchObject({ id: "push-recovery" });
});
test.each([
@@ -709,17 +814,17 @@ test.each([
["v2", legacyV2Yaml()],
])("rejects a schema %s descriptor instead of activating it", async (_version, legacyYaml) => {
const remote = await fixture(legacyYaml);
const registry = new WorkspaceRegistry(config(join(remote.root, "registry"), remote.remote));
const registry = makeRegistry(config(join(remote.root, "registry"), remote.remote));
await expect(registry.bootstrap()).rejects.toMatchObject({ code: "workspace_invalid" });
await expect(bootstrap(registry)).rejects.toMatchObject({ code: "workspace_invalid" });
expect(existsSync(join(remote.root, "registry", "state", "active.json"))).toBe(false);
});
test("writes only state-free revisions and never exposes revision state", async () => {
const remote = await fixture();
const root = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(root, remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
const initial = persistedState(root, remote.initialCommit);
expect(Object.keys(initial.active).sort()).toEqual(["head", "revisions"]);
@@ -727,12 +832,12 @@ test("writes only state-free revisions and never exposes revision state", async
expect(Object.keys(initial.active.revisions[0]).sort()).toEqual(["blob", "commit", "id", "snapshotPath"]);
expect(Object.keys(initial.manifest.revisions[0]).sort()).toEqual(["blob", "commit", "id", "snapshotPath"]);
const listed = await registry.list();
const read = await registry.read("psd-clinical");
const listed = await list(registry);
const readResult = await read(registry, "psd-clinical");
expect(listed[0]).not.toHaveProperty("state");
expect(read.revision).not.toHaveProperty("state");
expect(readResult.revision).not.toHaveProperty("state");
const published = await registry.publish({
const published = await publish(registry, {
action: "update",
workspace: workspaceWith("psd-clinical", { name: "State-free revision" }),
baseCommit: remote.initialCommit,
@@ -747,20 +852,20 @@ test("writes only state-free revisions and never exposes revision state", async
test("accepts historical operational state without leaking it or rewriting the immutable snapshot", async () => {
const remote = await fixture();
const root = join(remote.root, "registry");
await new WorkspaceRegistry(config(root, remote.remote)).bootstrap();
await bootstrap(makeRegistry(config(root, remote.remote)));
rewritePersistedRevisionStates(root, remote.initialCommit, "operational", "operational");
const snapshotPath = join(root, "snapshots", remote.initialCommit, "snapshot.json");
const historicalManifest = readFileSync(snapshotPath, "utf8");
const restored = new WorkspaceRegistry(config(root, remote.remote));
const listed = await restored.list();
const read = await restored.read("psd-clinical");
const restored = makeRegistry(config(root, remote.remote));
const listed = await list(restored);
const readResult = await read(restored, "psd-clinical");
expect(listed[0]).not.toHaveProperty("state");
expect(read.revision).not.toHaveProperty("state");
expect(readResult.revision).not.toHaveProperty("state");
expect(readFileSync(snapshotPath, "utf8")).toBe(historicalManifest);
await restored.bootstrap();
await bootstrap(restored);
const rewrittenActive = persistedState(root, remote.initialCommit).active;
expect(rewrittenActive.revisions[0]).not.toHaveProperty("state");
expect(readFileSync(snapshotPath, "utf8")).toBe(historicalManifest);
@@ -772,12 +877,12 @@ test.each([
] as const)("normalizes mixed persisted revision encodings: %s", async (_name, activeState, manifestState) => {
const remote = await fixture();
const root = join(remote.root, "registry");
await new WorkspaceRegistry(config(root, remote.remote)).bootstrap();
await bootstrap(makeRegistry(config(root, remote.remote)));
rewritePersistedRevisionStates(root, remote.initialCommit, activeState, manifestState);
const snapshotPath = join(root, "snapshots", remote.initialCommit, "snapshot.json");
const historicalManifest = readFileSync(snapshotPath, "utf8");
const revisions = await new WorkspaceRegistry(config(root, remote.remote)).list();
const revisions = await list(makeRegistry(config(root, remote.remote)));
expect(revisions[0]).not.toHaveProperty("state");
expect(readFileSync(snapshotPath, "utf8")).toBe(historicalManifest);
@@ -791,10 +896,10 @@ test.each([
] as const)("rejects %s", async (_name, activeState, manifestState) => {
const remote = await fixture();
const root = join(remote.root, "registry");
await new WorkspaceRegistry(config(root, remote.remote)).bootstrap();
await bootstrap(makeRegistry(config(root, remote.remote)));
rewritePersistedRevisionStates(root, remote.initialCommit, activeState, manifestState);
await expect(new WorkspaceRegistry(config(root, remote.remote)).list()).rejects.toMatchObject({
await expect(list(makeRegistry(config(root, remote.remote)))).rejects.toMatchObject({
code: "workspace_invalid",
});
});
@@ -807,7 +912,7 @@ test.each([
] as const)("rejects unknown fields in %s", async (_name, component, location) => {
const remote = await fixture();
const root = join(remote.root, "registry");
await new WorkspaceRegistry(config(root, remote.remote)).bootstrap();
await bootstrap(makeRegistry(config(root, remote.remote)));
const path = component === "active"
? join(root, "state", "active.json")
: join(root, "snapshots", remote.initialCommit, "snapshot.json");
@@ -817,7 +922,7 @@ test.each([
if (component === "manifest") chmodSync(path, 0o600);
writeFileSync(path, JSON.stringify(persisted));
await expect(new WorkspaceRegistry(config(root, remote.remote)).list()).rejects.toMatchObject({
await expect(list(makeRegistry(config(root, remote.remote)))).rejects.toMatchObject({
code: "workspace_invalid",
});
});
@@ -825,20 +930,20 @@ test.each([
test("normalizes operational state in retained historical snapshots without rewriting them", async () => {
const remote = await fixture();
const root = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(root, remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
writeFileSync(join(remote.source, "workspaces", "psd-clinical.yaml"), validYaml.replace(
"name: Policlinico San Donato", "name: Current workspace",
));
await git(remote.source, ["add", "workspaces/psd-clinical.yaml"]);
await git(remote.source, ["commit", "-m", "Update active workspace"]);
await git(remote.source, ["push", "origin", "main"]);
await registry.pull();
await pull(registry);
rewritePersistedRevisionStates(root, remote.initialCommit, "absent", "operational");
const snapshotPath = join(root, "snapshots", remote.initialCommit, "snapshot.json");
const historicalManifest = readFileSync(snapshotPath, "utf8");
const retained = await new WorkspaceRegistry(config(root, remote.remote)).listRetainedSnapshots();
const retained = await makeRegistry(config(root, remote.remote)).listRetainedSnapshots();
expect(retained).toEqual(expect.arrayContaining([
expect.objectContaining({ id: "psd-clinical", commit: remote.initialCommit }),
@@ -850,22 +955,22 @@ test("normalizes operational state in retained historical snapshots without rewr
test("normalizes historical operational state during offline fallback after restart", async () => {
const remote = await fixture();
const root = join(remote.root, "registry");
await new WorkspaceRegistry(config(root, remote.remote)).bootstrap();
await bootstrap(makeRegistry(config(root, remote.remote)));
rewritePersistedRevisionStates(root, remote.initialCommit, "operational", "operational");
rmSync(remote.remote, { recursive: true, force: true });
const restored = new WorkspaceRegistry(config(root, remote.remote));
await expect(restored.pull()).resolves.toMatchObject({ degraded: true, head: remote.initialCommit });
const listed = await restored.list();
const read = await restored.read("psd-clinical");
const restored = makeRegistry(config(root, remote.remote));
await expect(pull(restored)).resolves.toMatchObject({ degraded: true, head: remote.initialCommit });
const listed = await list(restored);
const readResult = await read(restored, "psd-clinical");
expect(listed[0]).not.toHaveProperty("state");
expect(read.revision).not.toHaveProperty("state");
expect(readResult.revision).not.toHaveProperty("state");
});
test("fails closed when a retained snapshot descriptor is not schema v3", async () => {
const remote = await fixture();
const root = join(remote.root, "registry");
await new WorkspaceRegistry(config(root, remote.remote)).bootstrap();
await bootstrap(makeRegistry(config(root, remote.remote)));
const snapshotDirectory = join(root, "snapshots", remote.initialCommit);
const yamlPath = join(snapshotDirectory, "psd-clinical.yaml");
chmodSync(yamlPath, 0o600);
@@ -877,19 +982,19 @@ test("fails closed when a retained snapshot descriptor is not schema v3", async
chmodSync(manifestPath, 0o600);
writeFileSync(manifestPath, JSON.stringify(manifest));
await expect(new WorkspaceRegistry(config(root, remote.remote)).list()).rejects.toMatchObject({
await expect(list(makeRegistry(config(root, remote.remote)))).rejects.toMatchObject({
code: "workspace_invalid",
});
});
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();
const registry = makeRegistry(config(join(remote.root, "registry"), remote.remote));
await bootstrap(registry);
await pushInvalidWorkspace(remote.source);
await expect(registry.pull()).rejects.toMatchObject({ code: "workspace_invalid" });
await expect(registry.read("psd-clinical")).resolves.toMatchObject({
await expect(pull(registry)).rejects.toMatchObject({ code: "workspace_invalid" });
await expect(read(registry, "psd-clinical")).resolves.toMatchObject({
revision: { commit: remote.initialCommit },
});
});
@@ -903,8 +1008,8 @@ test("rejects duplicate schema v3 collection ownership and keeps the previous ac
.replace("name: Policlinico San Donato", "name: Research Clinical")
.replace("collection: psd-clinical", "collection: research-clinical"),
});
const registry = new WorkspaceRegistry(config(join(remote.root, "registry"), remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(join(remote.root, "registry"), remote.remote));
await bootstrap(registry);
writeFileSync(
join(remote.source, "workspaces", "research-clinical.yaml"),
@@ -921,14 +1026,14 @@ test("rejects duplicate schema v3 collection ownership and keeps the previous ac
await git(remote.source, ["commit", "-m", "Duplicate collection ownership"]);
await git(remote.source, ["push", "origin", "main"]);
await expect(registry.pull()).rejects.toMatchObject({
await expect(pull(registry)).rejects.toMatchObject({
code: "workspace_invalid",
message: "Workspace repository content is invalid",
});
await expect(registry.read("psd-clinical")).resolves.toMatchObject({
await expect(read(registry, "psd-clinical")).resolves.toMatchObject({
revision: { commit: remote.initialCommit },
});
await expect(registry.read("research-clinical")).resolves.toMatchObject({
await expect(read(registry, "research-clinical")).resolves.toMatchObject({
revision: { commit: remote.initialCommit },
});
});
@@ -936,8 +1041,8 @@ test("rejects duplicate schema v3 collection ownership and keeps the previous ac
test("retains a historical snapshot while a resumable manifest still references its revision", async () => {
const remote = await fixture();
const root = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(root, remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
writeFileSync(join(remote.source, "workspaces", "psd-clinical.yaml"), validYaml.replace(
"name: Policlinico San Donato", "name: Updated Policlinico San Donato",
@@ -946,22 +1051,22 @@ test("retains a historical snapshot while a resumable manifest still references
await git(remote.source, ["commit", "-m", "Update workspace"]);
await git(remote.source, ["push", "origin", "main"]);
const currentCommit = await gitOutput(remote.source, ["rev-parse", "HEAD"]);
await registry.pull();
await pull(registry);
await registry.reconcileSnapshotRetention([remote.initialCommit]);
expect(existsSync(registry.snapshotPath(remote.initialCommit, "psd-clinical"))).toBe(true);
expect(existsSync(registry.snapshotPath(currentCommit, "psd-clinical"))).toBe(true);
await reconcileWorkspaceSnapshotRetention(registry, [remote.initialCommit]);
expect(existsSync(workspaceRegistrySnapshotPath(registry, remote.initialCommit, "psd-clinical"))).toBe(true);
expect(existsSync(workspaceRegistrySnapshotPath(registry, currentCommit, "psd-clinical"))).toBe(true);
await registry.reconcileSnapshotRetention([]);
expect(existsSync(registry.snapshotPath(remote.initialCommit, "psd-clinical"))).toBe(false);
expect(existsSync(registry.snapshotPath(currentCommit, "psd-clinical"))).toBe(true);
await reconcileWorkspaceSnapshotRetention(registry, []);
expect(existsSync(workspaceRegistrySnapshotPath(registry, remote.initialCommit, "psd-clinical"))).toBe(false);
expect(existsSync(workspaceRegistrySnapshotPath(registry, currentCommit, "psd-clinical"))).toBe(true);
});
test("a session revision lease survives stale retention scans until its manifest is observed", async () => {
const remote = await fixture();
const root = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(root, remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
const lease = await registry.acquireSessionRevision("psd-clinical");
writeFileSync(join(remote.source, "workspaces", "psd-clinical.yaml"), validYaml.replace(
@@ -970,25 +1075,25 @@ test("a session revision lease survives stale retention scans until its manifest
await git(remote.source, ["add", "workspaces/psd-clinical.yaml"]);
await git(remote.source, ["commit", "-m", "Publish while session is starting"]);
await git(remote.source, ["push", "origin", "main"]);
await registry.pull();
await pull(registry);
await registry.reconcileSnapshotRetention([]);
expect(existsSync(registry.snapshotPath(remote.initialCommit, "psd-clinical"))).toBe(true);
await reconcileWorkspaceSnapshotRetention(registry, []);
expect(existsSync(workspaceRegistrySnapshotPath(registry, remote.initialCommit, "psd-clinical"))).toBe(true);
await lease.markPersisted();
await registry.reconcileSnapshotRetention([]);
expect(existsSync(registry.snapshotPath(remote.initialCommit, "psd-clinical"))).toBe(true);
await reconcileWorkspaceSnapshotRetention(registry, []);
expect(existsSync(workspaceRegistrySnapshotPath(registry, remote.initialCommit, "psd-clinical"))).toBe(true);
await registry.reconcileSnapshotRetention([remote.initialCommit]);
await registry.reconcileSnapshotRetention([]);
expect(existsSync(registry.snapshotPath(remote.initialCommit, "psd-clinical"))).toBe(false);
await reconcileWorkspaceSnapshotRetention(registry, [remote.initialCommit]);
await reconcileWorkspaceSnapshotRetention(registry, []);
expect(existsSync(workspaceRegistrySnapshotPath(registry, remote.initialCommit, "psd-clinical"))).toBe(false);
});
test("lists operational descriptors retained after their workspace was removed from the active revision", async () => {
const remote = await fixture();
const root = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(root, remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
writeFileSync(join(remote.source, "workspaces", "archive-only.yaml"), validYaml.replace(
"id: psd-clinical", "id: archive-only",
@@ -996,13 +1101,13 @@ test("lists operational descriptors retained after their workspace was removed f
await git(remote.source, ["add", "workspaces/archive-only.yaml"]);
await git(remote.source, ["commit", "-m", "Add retained workspace"]);
await git(remote.source, ["push", "origin", "main"]);
await registry.pull();
await pull(registry);
rmSync(join(remote.source, "workspaces", "psd-clinical.yaml"));
await git(remote.source, ["add", "-u"]);
await git(remote.source, ["commit", "-m", "Remove original workspace"]);
await git(remote.source, ["push", "origin", "main"]);
await registry.pull();
await pull(registry);
const retained = await registry.listRetainedSnapshots();
expect(retained).toEqual(expect.arrayContaining([
@@ -1014,7 +1119,7 @@ test("lists operational descriptors retained after their workspace was removed f
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 registry = makeRegistry(config(root, remote.remote));
const lock = new WorkspaceRepositoryLock(join(root, "locks"));
let release!: () => void;
let started!: () => void;
@@ -1025,7 +1130,7 @@ test("does not bypass an existing live advisory repository lock", async () => {
await new Promise<void>((resolve) => { started = resolve; });
try {
await expect(registry.bootstrap()).rejects.toMatchObject({ code: "workspace_stale" });
await expect(bootstrap(registry)).rejects.toMatchObject({ code: "workspace_stale" });
} finally {
release();
await held;
@@ -1038,17 +1143,17 @@ test("rejects a symbolic-link registry root before creating a lock below it", as
const root = join(remote.root, "registry-link");
mkdirSync(target);
symlinkSync(target, root);
const registry = new WorkspaceRegistry(config(root, remote.remote));
const registry = makeRegistry(config(root, remote.remote));
await expect(registry.bootstrap()).rejects.toMatchObject({ code: "git_unavailable" });
await expect(bootstrap(registry)).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 registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
const checkout = join(root, "repo");
writeFileSync(join(checkout, "workspaces", "psd-clinical.yaml"), validYaml.replace(
"name: Policlinico San Donato", "name: Local only workspace",
@@ -1058,8 +1163,8 @@ test("rejects a locally-ahead checkout instead of activating local-only content"
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({
await expect(pull(registry)).rejects.toMatchObject({ code: "git_non_fast_forward" });
await expect(read(registry, "psd-clinical")).resolves.toMatchObject({
revision: { commit: remote.initialCommit },
workspace: { workspace: { name: "Policlinico San Donato" } },
});
@@ -1070,9 +1175,9 @@ test("recovers a dead-process advisory lock while preserving active snapshot saf
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));
const registry = makeRegistry(config(root, remote.remote));
await expect(registry.bootstrap()).resolves.toMatchObject({
await expect(bootstrap(registry)).resolves.toMatchObject({
head: remote.initialCommit,
degraded: false,
});
@@ -1083,8 +1188,8 @@ test.each(["manifest", "blob", "workspace", "document"])(
async (component) => {
const remote = await fixture();
const root = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(root, remote.remote));
await registry.bootstrap();
const registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
const snapshot = join(root, "snapshots", remote.initialCommit);
if (component === "manifest") {
@@ -1105,32 +1210,32 @@ test.each(["manifest", "blob", "workspace", "document"])(
}
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" });
await expect(list(registry)).rejects.toMatchObject({ code: "workspace_invalid" });
await expect(read(registry, "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 registry = makeRegistry(config(root, remote.remote));
await bootstrap(registry);
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" });
await expect(pull(registry)).rejects.toMatchObject({ code: "workspace_invalid" });
});
test("snapshots canonical Evidence artifacts at the active commit without copying Evidence bytes", async () => {
const remote = await fixture(withFilesystemEvidence(validYaml));
const registryRoot = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(registryRoot, remote.remote));
const registry = makeRegistry(config(registryRoot, remote.remote));
const status = await registry.bootstrap();
const active = await registry.read("psd-clinical");
const status = await bootstrap(registry);
const active = await read(registry, "psd-clinical");
const snapshotDirectory = join(registryRoot, "snapshots", status.head!);
const descriptor = active.workspace as CanonicalWorkspace;
const docs = renderWorkspaceDocs(descriptor);
@@ -1181,13 +1286,13 @@ test("never copies an installation secret canary into Git, generated artifacts,
const secretFile = join(secretDirectory, "signed-urls");
writeFileSync(secretFile, canary);
const registryRoot = join(remote.root, "registry");
const registry = new WorkspaceRegistry(config(registryRoot, remote.remote, {
const registry = makeRegistry(config(registryRoot, remote.remote, {
secretRoots: [secretDirectory],
}));
const previous = process.env.THT_WS_PSD_CLINICAL_EVIDENCE_SIGNED_URLS_FILE;
process.env.THT_WS_PSD_CLINICAL_EVIDENCE_SIGNED_URLS_FILE = secretFile;
try {
const status = await registry.bootstrap();
const status = await bootstrap(registry);
const snapshotDirectory = join(registryRoot, "snapshots", status.head!);
let gitBlobText = "";
try {
@@ -1204,7 +1309,7 @@ test("never copies an installation secret canary into Git, generated artifacts,
}
let thrown: unknown;
try {
await registry.publish({
await publish(registry, {
action: "create",
workspace: filesystemWorkspace("missing-secret-canary-tree"),
baseCommit: status.head!,