Implement workspace evolution, migrations, and runtime continuity
Enable evolution by default for source-backed workspaces. Add stable conformance ownership, semantic-major review, candidate typechecking, and durable fenced cutover with explicit migrations and forward recovery. Independently supervise package runtimes so unchanged resource owners keep their processes and connections across cutover. Add scoped invocation authority, resource sessions, and typed callback rebinding. Wire opaque object references through generated bindings and RPCs. Add canonical relationship sets, keyed maps, and ordered lists with scoped transactional mutations, revision checks, and inverse consistency. Support planned cascade deletion, protection, tombstones, and lifecycle foundations. Add journaled structural edits, package/function/migration scaffolding, managed repository creation, and resumable bottom-up dependency pin publication. Document lifetime boundaries, revision pinning, prototype compatibility policy, commands, and deferred work. Validate with 210 tests, user-systemd process/connection continuity, generated-package TypeScript checks, and Nix host/protocol checks. TTL handoff, physical reclamation, general multi-step migrations, and root-systemd migration isolation acceptance remain deferred.
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import { execFile as callback } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { snapshotRepository, checkWorkspaceCandidate } from "../src/capability-language/candidate-check.js";
|
||||
const execFile = promisify(callback);
|
||||
|
||||
test("candidate snapshots include dirty and new files without changing Git history or index", async (context) => {
|
||||
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "qx-candidate-test-"));
|
||||
context.after(() => fs.rm(directory, { recursive: true, force: true }));
|
||||
const root = path.join(directory, "source");
|
||||
await fs.mkdir(root);
|
||||
const git = (...args: string[]) => execFile("git", ["-C", root, ...args]);
|
||||
await git("init");
|
||||
await fs.writeFile(path.join(root, "tracked"), "original");
|
||||
await fs.writeFile(path.join(root, ".gitignore"), "ignored\n");
|
||||
await git("add", ".");
|
||||
const index = await fs.readFile(path.join(root, ".git/index"));
|
||||
await fs.writeFile(path.join(root, "tracked"), "edited");
|
||||
await fs.writeFile(path.join(root, "new"), "new content");
|
||||
await fs.writeFile(path.join(root, "ignored"), "not source");
|
||||
const snapshot = await snapshotRepository(root, path.join(directory, "snapshot"));
|
||||
assert.equal(await fs.readFile(path.join(snapshot.directory, "tracked"), "utf8"), "edited");
|
||||
assert.equal(await fs.readFile(path.join(snapshot.directory, "new"), "utf8"), "new content");
|
||||
await assert.rejects(fs.access(path.join(snapshot.directory, "ignored")));
|
||||
assert.deepEqual(await fs.readFile(path.join(root, ".git/index")), index);
|
||||
await assert.rejects(git("rev-parse", "--verify", "HEAD"), "no commit was created");
|
||||
await fs.symlink("tracked", path.join(root, "link"));
|
||||
await assert.rejects(snapshotRepository(root, path.join(directory, "rejected")), /regular file/);
|
||||
});
|
||||
|
||||
test("candidate check produces explicitly non-activation evidence and never overwrites a report", async (context) => {
|
||||
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "qx-check-test-"));
|
||||
context.after(() => fs.rm(directory, { recursive: true, force: true }));
|
||||
const root = path.join(directory, "source"), output = path.join(directory, "check");
|
||||
await fs.mkdir(root);
|
||||
await execFile("git", ["-C", root, "init"]);
|
||||
await fs.writeFile(path.join(root, "quixos.lock"), `quixos-lock version 1 { quixos source { repository "https://example.test/quixos.git"; commit "${"a".repeat(40)}"; } }`);
|
||||
await fs.writeFile(path.join(root, "workspace.qx"), `workspace Test id "workspace:test" revision "workspace:test@1" commit "${"b".repeat(40)}" { atom Subject id "atom:subject"; }`);
|
||||
const result = await checkWorkspaceCandidate({root, output});
|
||||
assert.equal(result.candidateOnly, true);
|
||||
assert.equal(result.activationEvidence, false);
|
||||
assert.deepEqual(result.blockers, []);
|
||||
const report = await fs.readFile(path.join(output, "report.json"));
|
||||
await assert.rejects(checkWorkspaceCandidate({root, output}), /EEXIST/);
|
||||
assert.deepEqual(await fs.readFile(path.join(output, "report.json")), report);
|
||||
});
|
||||
@@ -101,16 +101,16 @@ test("ANTLR parses and validates a complete capability workspace", () => {
|
||||
assert.equal("id" in result.workspace.conformances[0]!, false);
|
||||
});
|
||||
|
||||
test("conformances do not accept authored IDs", () => {
|
||||
test("conformances preserve authored migration lineage IDs", () => {
|
||||
const result = compileCapabilityFixture({
|
||||
workspace: capabilityFixtureSource.replace(
|
||||
"conform Project as Named {",
|
||||
'conform Project as Named id "conformance:project:named" {',
|
||||
),
|
||||
});
|
||||
assert.equal(result.ok, false);
|
||||
if (result.ok) return;
|
||||
assert.ok(result.diagnostics.some((entry) => entry.phase === "syntax"));
|
||||
assert.equal(result.ok, true);
|
||||
if (!result.ok) return;
|
||||
assert.equal(result.workspace.conformances[0]!.id, "conformance:project:named");
|
||||
});
|
||||
|
||||
test("the v1 language has no implicit relationship materialization rule", () => {
|
||||
|
||||
@@ -14,6 +14,14 @@ import {
|
||||
makeValidCapabilityWorkspace,
|
||||
} from "./fixtures/capability-model.js";
|
||||
|
||||
test("ordinary state rejects managed references even under list/optional wrappers", () => {
|
||||
const workspace = makeValidCapabilityWorkspace();
|
||||
const state = [...workspace.sharedAttachments, ...workspace.conformances.flatMap((entry) => entry.privateAttachments)].find((entry) => entry.kind === "state")!;
|
||||
if (state.kind !== "state") throw new Error("fixture missing state");
|
||||
state.valueType = {kind: "list", value: {kind: "optional", value: {kind: "object-ref", expectation: {kind: "atom", atomId: state.attachedTo}}}};
|
||||
assert.ok(validateWorkspaceRevision(workspace).some((entry) => entry.message.includes("graph relationships")));
|
||||
});
|
||||
|
||||
const expectIssue = (
|
||||
workspace: WorkspaceRevision,
|
||||
code: CapabilityValidationIssueCode,
|
||||
@@ -193,6 +201,11 @@ test("related-object dependency views cannot traverse another conformance's priv
|
||||
projectionId: fixtureId.projectOwnerProjection,
|
||||
};
|
||||
expectIssue(workspace, "private-attachment-access");
|
||||
const owner = conformance(workspace, fixtureId.projectOwnedConformance);
|
||||
const edge = owner.privateAttachments.find((entry) => entry.kind === "edge" && entry.id === fixtureId.projectOwner);
|
||||
assert.ok(edge?.kind === "edge");
|
||||
edge.endpoints.find((endpoint) => endpoint.projectionId === fixtureId.projectOwnerProjection)!.publicTraversal = true;
|
||||
assert.equal(validateWorkspaceRevision(workspace).some((entry) => entry.code === "private-attachment-access"), false, "Only an explicitly exported read-only traversal crosses ownership");
|
||||
});
|
||||
|
||||
test("native state and edge providers must match operation shape", () => {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { capabilityId as id, valueType, validateWorkspaceRevision } from "../src/capability-model/index.js";
|
||||
import { contentDigest, planEvolution, runtimeContracts, storageContracts } from "../src/capability-model/evolution.js";
|
||||
import { capabilityFixtureSource, capabilityResourceSources, compileCapabilityFixture, makeValidCapabilityWorkspace } from "./fixtures/capability-model.js";
|
||||
|
||||
test("QX carries stable conformance IDs and implementation semantic majors", () => {
|
||||
const result = compileCapabilityFixture({
|
||||
workspace: capabilityFixtureSource.replace("conform Project as Named {", 'conform Project as Named id "conformance:project:named" semantic-major 3 {'),
|
||||
todo: capabilityResourceSources.todo.replace('revision "package:todo-runtime@1" {', 'revision "package:todo-runtime@1" semantic-major 2 {'),
|
||||
});
|
||||
assert.ok(result.ok, JSON.stringify(result));
|
||||
assert.equal(result.workspace.conformances[0]!.id, "conformance:project:named");
|
||||
assert.equal(result.workspace.conformances[0]!.semanticMajor, 3);
|
||||
assert.equal(result.workspace.packageImports[0]!.semanticMajor, 2);
|
||||
});
|
||||
|
||||
test("invalid majors and duplicate owner identities are rejected", () => {
|
||||
const workspace = makeValidCapabilityWorkspace();
|
||||
workspace.packageImports[0]!.semanticMajor = 0;
|
||||
workspace.conformances[0]!.semanticMajor = 1.5;
|
||||
workspace.conformances[0]!.id = id.conformance("same");
|
||||
workspace.conformances[1]!.id = id.conformance("same");
|
||||
const issues = validateWorkspaceRevision(workspace);
|
||||
assert.equal(issues.filter((entry) => entry.code === "invalid-semantic-major").length, 2);
|
||||
assert.ok(issues.some((entry) => entry.code === "duplicate-conformance-id"));
|
||||
});
|
||||
|
||||
test("hashing is canonical and rejects values outside the persisted JSON contract", () => {
|
||||
assert.equal(contentDigest({ z: 1, a: { y: 3, b: 2 } }), contentDigest({ a: { b: 2, y: 3 }, z: 1 }));
|
||||
assert.notEqual(contentDigest([1, 2]), contentDigest([2, 1]));
|
||||
assert.throws(() => contentDigest(NaN));
|
||||
assert.throws(() => contentDigest(new Date()));
|
||||
});
|
||||
|
||||
test("a workspace root change and display names do not restart package runtimes", () => {
|
||||
const before = makeValidCapabilityWorkspace();
|
||||
const after = structuredClone(before);
|
||||
after.id = id.workspaceRevision("next");
|
||||
after.sourceRootCommit = "f".repeat(40);
|
||||
after.atoms[0]!.displayName = "Renamed";
|
||||
after.sharedAttachments[0]!.displayName = "Renamed storage";
|
||||
after.conformances.reverse();
|
||||
after.interfaceImports.reverse();
|
||||
const report = planEvolution(before, after, { allowLegacy: true });
|
||||
assert.deepEqual(report.runtimeActions.map((entry) => entry.action), ["keep"]);
|
||||
assert.deepEqual(report.storageChanges, []);
|
||||
assert.deepEqual(report.packageChecks, []);
|
||||
});
|
||||
|
||||
test("consumer changes preserve unrelated resource owners", () => {
|
||||
const before = makeValidCapabilityWorkspace();
|
||||
before.packageImports.push({ packageId: id.package("package:resource-owner"), revisionId: id.packageRevision("package:resource-owner@1"),
|
||||
displayName: "ResourceOwner", source: { repository: "https://example.org/owner.git", commit: "a".repeat(40) },
|
||||
exports: [{ kind: "function", id: id.packageExport("export:owner:ping"), displayName: "ping", inputType: valueType.unit, outputType: valueType.unit, dependencyPorts: [] }] });
|
||||
const after = structuredClone(before);
|
||||
after.packageImports[0]!.source.commit = "e".repeat(40);
|
||||
const actions = planEvolution(before, after, { allowLegacy: true }).runtimeActions;
|
||||
assert.equal(actions.find((entry) => entry.groupId === "package:resource-owner")!.action, "keep");
|
||||
assert.equal(actions.find((entry) => entry.groupId === "package:todo-runtime")!.action, "replace");
|
||||
});
|
||||
|
||||
test("storage defaults and ownership changes invalidate consumers without requiring a major", () => {
|
||||
const before = makeValidCapabilityWorkspace();
|
||||
const after = structuredClone(before);
|
||||
const slot = after.sharedAttachments[0]!;
|
||||
assert.equal(slot.kind, "state");
|
||||
if (slot.kind === "state") slot.defaultValue = "Different default";
|
||||
const report = planEvolution(before, after, { allowLegacy: true });
|
||||
assert.equal(report.storageChanges.length, 1);
|
||||
assert.equal(report.runtimeActions[0]!.action, "replace");
|
||||
assert.deepEqual(report.reviews, []);
|
||||
assert.notDeepEqual(storageContracts(before), storageContracts(after));
|
||||
});
|
||||
|
||||
test("semantic review receipts cover exact consumer/provider contracts", () => {
|
||||
const before = makeValidCapabilityWorkspace();
|
||||
before.conformances[0]!.id = id.conformance("conformance:project:named");
|
||||
const after = structuredClone(before);
|
||||
after.conformances[0]!.semanticMajor = 2;
|
||||
const report = planEvolution(before, after, { allowLegacy: true });
|
||||
assert.equal(report.reviews.length, 1);
|
||||
assert.equal(report.reviews[0]!.accepted, false);
|
||||
const receipt = { requirementDigest: report.reviews[0]!.requirementDigest, decision: "accepted-unchanged" as const,
|
||||
rationale: "Reviewed the semantic change against summary behavior", agentId: "workspace-agent" };
|
||||
assert.equal(planEvolution(before, after, { allowLegacy: true, reviews: [receipt] }).reviews[0]!.accepted, true);
|
||||
after.packageImports[0]!.source.commit = "f".repeat(40);
|
||||
assert.equal(planEvolution(before, after, { allowLegacy: true, reviews: [receipt] }).reviews[0]!.accepted, false);
|
||||
});
|
||||
|
||||
test("evolution enrollment is explicit and never erases legacy ownership", () => {
|
||||
const workspace = makeValidCapabilityWorkspace();
|
||||
const report = planEvolution(workspace, workspace);
|
||||
assert.ok(report.blockers.some((entry) => entry.includes("workspace-shared")));
|
||||
assert.ok(report.blockers.some((entry) => entry.includes("authored ID")));
|
||||
assert.equal(runtimeContracts(workspace).length, 1);
|
||||
assert.throws(() => planEvolution(workspace, { ...workspace, workspaceId: id.workspace("other") }), /different workspace/);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { contentDigest, validateMigrationCatalog, selectMigrationPath, type MigrationCatalog } from "../src/capability-model/index.js";
|
||||
const before = { fields: ["name"] }, after = { fields: ["first", "last"] };
|
||||
const from = contentDigest(before), to = contentDigest(after);
|
||||
const catalog = (): MigrationCatalog => ({ schemaVersion: 1, contracts: { [from]: before, [to]: after }, migrations: [{
|
||||
id: "split-name", scopeId: "person-name", from, to,
|
||||
implementation: { exportId: "migrate-name", file: "src/migrate-name.ts", digest: contentDigest("implementation") }, predecessors: [],
|
||||
ports: [{ name: "source", view: "old", access: ["read"], contractDigest: from }, { name: "target", view: "new", access: ["write"], contractDigest: to }],
|
||||
}] });
|
||||
test("published migrations retain exact old contracts and explicit local bindings", () => {
|
||||
const value = validateMigrationCatalog(catalog(), new Set(["migrate-name"]));
|
||||
const selection = { scopeId: "person-name", from, to, path: ["split-name"], bindings: { source: "old-slot", target: "new-slot" } };
|
||||
const result = selectMigrationPath(value, selection);
|
||||
assert.equal(result[0].alreadyApplied, false);
|
||||
assert.equal(selectMigrationPath(value, selection, new Map([["split-name", result[0].digest]]))[0].alreadyApplied, true);
|
||||
const changed = catalog(); changed.migrations[0].implementation.digest = contentDigest("new code");
|
||||
assert.throws(() => selectMigrationPath(changed, selection, new Map([["split-name", result[0].digest]])), /different code/);
|
||||
assert.throws(() => selectMigrationPath(value, { ...selection, path: [] }), /does not cover/);
|
||||
assert.throws(() => selectMigrationPath(value, { ...selection, bindings: {} }), /Missing local/);
|
||||
});
|
||||
test("old migration views cannot be writable and contract hashes are verified", () => {
|
||||
const value = catalog(); value.migrations[0].ports[0].access = ["write"];
|
||||
assert.throws(() => validateMigrationCatalog(value), /read-only/);
|
||||
const corrupt = catalog(); corrupt.contracts[from] = {};
|
||||
assert.throws(() => validateMigrationCatalog(corrupt), /digest mismatch/);
|
||||
});
|
||||
|
||||
test("migration history rejects cycles and non-boolean compatibility promises", () => {
|
||||
const cyclic = catalog();
|
||||
cyclic.migrations[0].predecessors = ["split-name"];
|
||||
assert.throws(() => validateMigrationCatalog(cyclic), /Cyclic/);
|
||||
const misleading = catalog();
|
||||
(misleading.migrations[0] as unknown as {preservesOldReaders: string}).preservesOldReaders = "false";
|
||||
assert.throws(() => validateMigrationCatalog(misleading), /must be booleans/);
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import {promisify} from "node:util";
|
||||
import {execFile as callback} from "node:child_process";
|
||||
import {planPinUpgrades, applyPinUpgrades, type UpgradeEffects} from "../src/capability-language/pin-upgrades.js";
|
||||
const execFile = promisify(callback);
|
||||
|
||||
test("pin upgrades publish children before parent locks and resume without republishing completed nodes", async (context) => {
|
||||
const workbench = await fs.mkdtemp(path.join(os.tmpdir(), "qx-upgrade-test-"));
|
||||
context.after(() => fs.rm(workbench, {recursive: true, force: true}));
|
||||
const from = "a".repeat(40), to = "b".repeat(40), framework = "c".repeat(40);
|
||||
const sources = [{kind: "workspace" as const, directory: "root", source: {repository: "https://example.test/workspace.git", commit: from}},
|
||||
{kind: "interface" as const, directory: "resources/Named", source: {repository: "https://example.test/named.git", commit: from}}];
|
||||
const lock = `quixos-lock version 1 { quixos source { repository "https://example.test/quixos.git"; commit "${framework}"; }`;
|
||||
for (const node of sources) {
|
||||
const directory = path.join(workbench, node.directory);
|
||||
await fs.mkdir(directory, {recursive: true});
|
||||
await execFile("git", ["-C", directory, "init"]);
|
||||
await execFile("git", ["-C", directory, "remote", "add", "origin", node.source.repository]);
|
||||
await fs.writeFile(path.join(directory, ".gitignore"), ".quixos/\n");
|
||||
await fs.writeFile(path.join(directory, "quixos.lock"), lock + (node.kind === "workspace" ? ` interface Named source { repository "${sources[1].source.repository}"; commit "${from}"; }` : "") + " }");
|
||||
}
|
||||
await fs.writeFile(path.join(workbench, "resources/Named/interface.qx"), 'interface Named id "interface:named" revision "interface:named@1" { value name id "member:name" : string { get id "op:get"; } }');
|
||||
await fs.writeFile(path.join(workbench, "root/workspace.qx"), `workspace W id "workspace:w" revision "workspace:w@1" commit "${from}" { import interface Named; atom A id "atom:a"; }`);
|
||||
const snapshotMap = path.join(workbench, "snapshots.json");
|
||||
await fs.writeFile(snapshotMap, JSON.stringify({resources: [{kind: "interface", repository: sources[1].source.repository, commit: to, directory: path.join(workbench, "resources/Named")}]}));
|
||||
const oldMap = process.env.QUIXOS_SNAPSHOT_MAP;
|
||||
process.env.QUIXOS_SNAPSHOT_MAP = snapshotMap;
|
||||
context.after(() => {if (oldMap === undefined) delete process.env.QUIXOS_SNAPSHOT_MAP; else process.env.QUIXOS_SNAPSHOT_MAP = oldMap;});
|
||||
const plan = await planPinUpgrades(workbench, {nodes: sources});
|
||||
await fs.mkdir(path.join(workbench, ".quixos"), {recursive: true});
|
||||
await fs.writeFile(path.join(workbench, ".quixos/resource-graph.json"), JSON.stringify({resources: [{...sources[1], source: {resolver: "git", ...sources[1].source}}]}));
|
||||
assert.deepEqual(plan.nodes.map((node) => node.directory), ["resources/Named", "root"]);
|
||||
let fail = true;
|
||||
const published: string[] = [];
|
||||
const effects: UpgradeEffects = {
|
||||
check: async (node) => {if (node.kind === "workspace" && fail) throw new Error("refactor required");},
|
||||
snapshot: async () => to,
|
||||
publish: async (root) => {published.push(path.relative(workbench, root));},
|
||||
};
|
||||
await assert.rejects(() => applyPinUpgrades(plan, undefined, effects), /refactor required/);
|
||||
assert.deepEqual(published, ["resources/Named"]);
|
||||
assert.match(await fs.readFile(path.join(workbench, "root/quixos.lock"), "utf8"), new RegExp(to));
|
||||
const id = (await fs.readdir(path.join(workbench, ".quixos/upgrades"))).find((name) => name.endsWith(".json"))!.slice(0, -5);
|
||||
fail = false;
|
||||
await fs.appendFile(path.join(workbench, "root/workspace.qx"), "\n// explicit refactor\n");
|
||||
await assert.rejects(() => applyPinUpgrades(plan, id, effects), /accept-edits/);
|
||||
const result = await applyPinUpgrades(plan, id, effects, {acceptEdits: true});
|
||||
assert.equal(result.activated, false);
|
||||
assert.deepEqual(published, ["resources/Named", "root"]);
|
||||
const graph = JSON.parse(await fs.readFile(path.join(workbench, ".quixos/resource-graph.json"), "utf8"));
|
||||
assert.equal(graph.resources.length, 1);
|
||||
assert.equal(graph.resources[0].source.commit, to);
|
||||
const next = await planPinUpgrades(workbench, {nodes: [sources[0], {...sources[1], source: graph.resources[0].source}]});
|
||||
assert.deepEqual(next.nodes.find((node) => node.kind === "workspace")!.dependencies, ["resources/Named"]);
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import {execFile as callback} from "node:child_process";
|
||||
import {promisify} from "node:util";
|
||||
import {scaffoldRecipe} from "../src/capability-language/scaffold-recipes.js";
|
||||
import {planStructure, applyStructure} from "../src/capability-language/structural-plan.js";
|
||||
import {contentDigest} from "../src/capability-model/evolution.js";
|
||||
const execFile = promisify(callback);
|
||||
|
||||
test("package/function/migration scaffolds register implementations and refresh code digests without overwriting code", async (context) => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "qx-recipes-"));
|
||||
context.after(() => fs.rm(root, {recursive: true, force: true}));
|
||||
await execFile("git", ["-C", root, "init"]);
|
||||
await fs.writeFile(path.join(root, ".gitignore"), ".quixos/\n");
|
||||
const source = {repository: "https://example.test/chess.git", commit: "a".repeat(40)};
|
||||
const base = {source, directory: "packages/Chess"};
|
||||
const apply = async (command: Parameters<typeof scaffoldRecipe>[1], input: Parameters<typeof scaffoldRecipe>[2]) => applyStructure(await planStructure(root, await scaffoldRecipe(root, command, input)));
|
||||
await apply("package", {...base, name: "Chess", id: "package:chess", revision: "package:chess@1", tools: {quixos: source, protocol: source, helpers: source, sdk: source}});
|
||||
await apply("function", {...base, name: "play", id: "export:play"});
|
||||
const filename = path.join(root, base.directory, "src/impl/play.ts");
|
||||
const edited = 'import type {Implementation} from "../generated-bindings.js";\nexport const handler: Implementation["play"] = async () => null;\n';
|
||||
await fs.writeFile(filename, edited);
|
||||
const old = {version: 1}, next = {version: 2}, from = contentDigest(old), to = contentDigest(next);
|
||||
await apply("migration", {...base, name: "upgrade", id: "export:upgrade", migration: {id: "upgrade-v2", scopeId: "board", from, to, predecessors: [], ports: [], contracts: {[from]: old, [to]: next}}});
|
||||
const migrationFile = path.join(root, base.directory, "src/migrations/upgrade.ts");
|
||||
await fs.appendFile(migrationFile, "\n// authored migration change\n");
|
||||
await apply("refresh", base);
|
||||
assert.equal(await fs.readFile(filename, "utf8"), edited);
|
||||
const catalog = JSON.parse(await fs.readFile(path.join(root, base.directory, "quixos.migrations.json"), "utf8"));
|
||||
assert.equal(catalog.migrations[0].implementation.digest, contentDigest(await fs.readFile(migrationFile, "utf8")));
|
||||
const bindings = await fs.readFile(path.join(root, base.directory, "src/generated-bindings.ts"), "utf8");
|
||||
assert.match(bindings, /export:play/);
|
||||
assert.match(await fs.readFile(path.join(root, base.directory, "src/migrate.ts"), "utf8"), /export:upgrade/);
|
||||
if (process.env.QX_SCAFFOLD_TEST_SDK) {
|
||||
const sdk = await fs.realpath(process.env.QX_SCAFFOLD_TEST_SDK);
|
||||
const packageRoot = path.join(root, base.directory);
|
||||
await fs.mkdir(path.join(packageRoot, "node_modules/@quixos"), {recursive: true});
|
||||
await fs.symlink(sdk, path.join(packageRoot, "node_modules/@quixos/camino-package-runtime"));
|
||||
await fs.symlink(path.join(sdk, "node_modules/@types"), path.join(packageRoot, "node_modules/@types"));
|
||||
await execFile(path.join(sdk, "node_modules/.bin/tsc"), ["--noEmit"], {cwd: packageRoot});
|
||||
await execFile("nix-instantiate", ["--parse", path.join(packageRoot, "flake.nix")]);
|
||||
}
|
||||
await assert.rejects(() => apply("function", {...base, name: "play", id: "export:play"}), /unique/);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { editStructure, scaffoldResourceSource } from "../src/capability-language/structural-edits.js";
|
||||
|
||||
test("package scaffolding and function edits preserve surrounding source and use exact selectors", () => {
|
||||
const source = `// 🧭 resource comment\n${scaffoldResourceSource("package", "Chess", "package:chess", "package:chess@1")}`;
|
||||
const functionSource = 'function evaluate id "export:evaluate" : string -> string;';
|
||||
const appended = editStructure(source, {operation: "append", parent: {kind: "packageResourceDecl", id: "package:chess"}, source: functionSource});
|
||||
assert.ok(appended.startsWith("// 🧭 resource comment\n"));
|
||||
assert.ok(appended.includes(functionSource));
|
||||
const replaced = editStructure(appended, {operation: "replace", target: {kind: "packageFunctionExport", id: "export:evaluate"}, source: 'function evaluate id "export:evaluate" : unit -> string;'});
|
||||
assert.ok(replaced.includes(": unit -> string;"));
|
||||
assert.ok(!editStructure(replaced, {operation: "remove", target: {kind: "packageFunctionExport", id: "export:evaluate"}}).includes("evaluate"));
|
||||
assert.throws(() => editStructure(source, {operation: "remove", target: {kind: "packageResourceDecl", id: "package:chess@1"}}), /exactly once/);
|
||||
assert.throws(() => editStructure(source, {operation: "append", parent: {kind: "packageResourceDecl"}, source: "not valid QX"}), /Invalid structural/);
|
||||
});
|
||||
|
||||
test("dependency scaffolding validates exact sources and preserves unrelated lock comments", () => {
|
||||
const source = `// 🧭 lock\nquixos-lock version 1 {\n quixos source { repository "https://example.test/quixos.git"; commit "${"a".repeat(40)}"; }\n // retained comment\n}\n`;
|
||||
const dependency = {operation: "dependency" as const, kind: "package" as const, name: "Chess", source: {repository: "https://example.test/chess.git", commit: "b".repeat(40)}};
|
||||
const appended = editStructure(source, dependency);
|
||||
assert.ok(appended.includes("// retained comment"));
|
||||
assert.ok(appended.startsWith("// 🧭 lock\n"));
|
||||
assert.throws(() => editStructure(source, {...dependency, source: {...dependency.source, commit: "main"}}), /Invalid dependency/);
|
||||
const changed = editStructure(appended, {...dependency, source: {...dependency.source, commit: "c".repeat(40)}});
|
||||
assert.ok(!changed.includes("b".repeat(40)));
|
||||
assert.ok(!editStructure(changed, {...dependency, source: null}).includes("package Chess"));
|
||||
});
|
||||
|
||||
test("conformance enrollment, major edits, imports, and private attachment removal preserve valid structure", () => {
|
||||
const source = `fragment { conform Game as Playable { private state Board id "slot:board" on Game : string policy optimistic-register; } }`;
|
||||
const selector = {kind: "conformanceDecl", names: ["Game", "Playable"]};
|
||||
const enrolled = editStructure(source, {operation: "conformance-id", target: selector, id: "conformance:playable"});
|
||||
assert.ok(enrolled.includes('as Playable id "conformance:playable"'));
|
||||
const major = editStructure(enrolled, {operation: "semantic-major", target: {kind: "conformanceDecl", id: "conformance:playable"}, major: 2});
|
||||
assert.ok(major.includes("semantic-major 2"));
|
||||
assert.throws(() => editStructure(major, {operation: "conformance-id", target: selector, id: "different"}), /Cannot change/);
|
||||
const removed = editStructure(major, {operation: "remove", target: {kind: "stateDecl", id: "slot:board"}});
|
||||
assert.ok(!removed.includes("private"));
|
||||
const imported = editStructure(removed, {operation: "import", kind: "interface", name: "Playable"});
|
||||
assert.equal(editStructure(imported, {operation: "import", kind: "interface", name: "Playable"}), imported);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { execFile as callback } from "node:child_process";
|
||||
import { planStructure, applyStructure, resumeStructure, type StructuralRequest } from "../src/capability-language/structural-plan.js";
|
||||
const execFile = promisify(callback);
|
||||
|
||||
test("structural plans validate the graph, journal originals, and reject stale edits", async (context) => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "qx-structural-test-"));
|
||||
context.after(() => fs.rm(root, {recursive: true, force: true}));
|
||||
await execFile("git", ["-C", root, "init"]);
|
||||
await fs.writeFile(path.join(root, ".gitignore"), ".quixos/\n");
|
||||
await fs.writeFile(path.join(root, "quixos.lock"), `quixos-lock version 1 { quixos source { repository "https://example.test/quixos.git"; commit "${"a".repeat(40)}"; } }`);
|
||||
const before = `workspace Test id "workspace:test" revision "workspace:test@1" commit "${"b".repeat(40)}" { atom Subject id "atom:subject"; }`;
|
||||
await fs.writeFile(path.join(root, "workspace.qx"), before);
|
||||
const request: StructuralRequest = {kind: "workspace", files: [{file: "workspace.qx", edits: [{operation: "append", parent: {kind: "workspaceDecl"}, source: 'atom Game id "atom:game";'}]}]};
|
||||
const plan = await planStructure(root, request);
|
||||
assert.equal(await fs.readFile(path.join(root, "workspace.qx"), "utf8"), before);
|
||||
await fs.writeFile(path.join(root, "workspace.qx"), `${before}\n// newer edit`);
|
||||
await assert.rejects(() => applyStructure(plan), /Stale scaffold/);
|
||||
await fs.writeFile(path.join(root, "workspace.qx"), before);
|
||||
const applied = await applyStructure(plan);
|
||||
assert.equal(applied.phase, "complete");
|
||||
assert.ok((await fs.readFile(path.join(root, "workspace.qx"), "utf8")).includes("atom Game"));
|
||||
const journal = JSON.parse(await fs.readFile(applied.journalPath, "utf8"));
|
||||
assert.equal(journal.changes[0].before, before);
|
||||
assert.equal((await resumeStructure(root, applied.id)).phase, "complete");
|
||||
// Simulate a process interrupted after one file was written, before recording
|
||||
// completion. Replay accepts the already-written exact after image.
|
||||
journal.phase = "prepared";
|
||||
await fs.writeFile(applied.journalPath, JSON.stringify(journal));
|
||||
assert.equal((await resumeStructure(root, applied.id)).phase, "complete");
|
||||
await assert.rejects(() => planStructure(root, request), /Duplicate|duplicate/);
|
||||
});
|
||||
Reference in New Issue
Block a user