Add factory creation ports and owner initialization contracts

This commit is contained in:
Timothy J. Aveni
2026-09-19 22:20:55 -07:00
parent 03ac7f8557
commit 0555c929b1
25 changed files with 3899 additions and 3012 deletions
+3 -3
View File
@@ -148,10 +148,10 @@ test("interfaces can declare ordinary call operations", () => {
test("state defaults accept recursive JSON values", () => {
const source = capabilityFixtureSource.replace(
/policy optimistic-register default "Untitled project";/,
` policy optimistic-register default "Untitled project";
/policy register default "Untitled project";/,
` policy register default "Untitled project";
shared state ProjectMetadata id "slot:project:metadata" on Project : message "example.Metadata"
policy optimistic-register default {"labels":["compiler","runtime"],"score":1.5,"enabled":true,"extra":null};`,
policy register default {"labels":["compiler","runtime"],"score":1.5,"enabled":true,"extra":null};`,
);
const result = compileCapabilityFixture({ workspace: source });
assert.equal(result.ok, true);
+197
View File
@@ -0,0 +1,197 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import {
compileCapabilityResourceSource,
compileCapabilitySource,
formatQx,
} from "../src/capability-language/index.js";
import type { InterfaceRevision } from "../src/capability-model/types.js";
const source = { repository: "https://example.test/factories.git", commit: "a".repeat(40) };
const seed = "record { data: record { title: string; }; tags: record { tags: list<string>; }; }";
const iface = (text: string): InterfaceRevision => {
const result = compileCapabilityResourceSource(text, { source });
assert.ok(result.ok && result.resource.kind === "interface", JSON.stringify(result.diagnostics));
return result.resource.revision;
};
const data = iface(`interface Data id "data" revision "data@1" {
value title id "title" : string { get id "title:get" execution snapshot targets [browser, server]; }
}`);
const tagged = iface(`interface Tagged id "tagged" revision "tagged@1" {
value tags id "tags" : list<string> { get id "tags:get" execution snapshot targets [browser, server]; }
}`);
const factory = iface(`external atom Note id "note";
interface Factory id "factory" revision "factory@1" {
static operation create id "create" : ${seed} -> atom-ref<Note> { call id "create:call" execution transaction targets [browser, server]; }
static operation importNote id "import" : ${seed} -> atom-ref<Note> { call id "import:call" execution transaction targets [browser, server]; }
}`);
const runtime = compileCapabilityResourceSource(
`external atom Note id "note";
package Runtime id "runtime" revision "runtime@1" {
function createNote id "create-note" : ${seed} -> atom-ref<Note> execution transaction targets [browser, server] requires {
creation note id "new-note" : Note input ${seed};
};
function importNote id "import-note" : ${seed} -> atom-ref<Note> execution transaction targets [browser, server] requires {
creation note id "new-note" : Note input ${seed};
};
}`,
{ source },
);
assert.ok(runtime.ok && runtime.resource.kind === "package", JSON.stringify(runtime.diagnostics));
const packageRevision = runtime.resource.revision;
const text = `workspace Notes id "notes" revision "notes@1" commit "${"a".repeat(40)}" {
import interface Data; import interface Tagged; import interface Factory; import package Runtime;
atom Note id "note";
conform Note as Data id "owner:data" {
private state Title id "title-state" on Note : string policy register;
initialize { title to state Title; };
bind title.get to state Title.read;
}
conform Note as Tagged id "owner:tags" {
private state Tags id "tags-state" on Note : list<string> policy register;
initialize { tags to state Tags; };
bind tags.get to state Tags.read;
}
conform Note as Factory id "owner:factory" {
bind create.call to package Runtime.createNote with {
note to creation Note with { Data from input.data; Tagged from input.tags; };
};
bind importNote.call to package Runtime.importNote with {
note to creation Note with { Data from input.data; Tagged from input.tags; };
};
}
}`;
const compile = (textOverride = text) =>
compileCapabilitySource(formatQx(textOverride), "notes.qx", {
interfaces: new Map([
["Data", data],
["Tagged", tagged],
["Factory", factory],
]),
interfaceClosure: [data, tagged, factory],
packages: new Map([["Runtime", packageRevision]]),
packageClosure: [packageRevision],
});
test("two factories initialize two independent state owners without constructors", () => {
const result = compile();
assert.ok(result.ok, JSON.stringify(result.diagnostics));
assert.deepEqual(result.workspace.constructors, []);
assert.equal(result.workspace.conformances.filter((c) => c.initialization).length, 2);
const owners = result.workspace.conformances[2]!.operationBindings.map((b) =>
b.binding.kind === "package" ? b.binding.dependencies[0]!.binding : undefined,
);
for (const binding of owners) {
assert.ok(binding?.kind === "creation");
assert.deepEqual(binding.owners, [
{ interfaceRevisionId: "data@1", inputPath: ["data"] },
{ interfaceRevisionId: "tagged@1", inputPath: ["tags"] },
]);
}
});
test("creation rejects missing seeds, wrong input shapes, and private initialization laundering", () => {
for (const [edit, message] of [
[text.replaceAll("Tagged from input.tags;", ""), "Required state tags-state"],
[text.replaceAll("Data from input.data;", "Data from input.tags;"), "does not match"],
[text.replace("title to state Title;", "title to state Tags;"), "owned by this conformance"],
[
text.replaceAll("Data from input.data;", "Data from input.data; Data from input.data;"),
"Duplicate initialization owner",
],
]) {
const result = compile(edit!);
assert.equal(result.ok, false);
assert.match(JSON.stringify(result.diagnostics), new RegExp(message!));
}
});
test("defaults supply unmapped state and seeds cannot invoke an undeclared owner", () => {
const withDefault = text
.replace("on Note : list<string> policy register;", "on Note : list<string> policy register default [];")
.replaceAll("Tagged from input.tags;", "");
const result = compile(withDefault);
assert.ok(result.ok, JSON.stringify(result.diagnostics));
const missing = compile(text.replace("initialize { tags to state Tags; };", ""));
assert.equal(missing.ok, false);
assert.match(JSON.stringify(missing.diagnostics), /no declared initialization mapping/);
});
test("creation ports cannot be used in snapshot execution", () => {
const result = compileCapabilityResourceSource(
`external atom Note id "note";
package P id "p" revision "p@1" {
function createNote id "create" : unit -> atom-ref<Note> execution snapshot targets [browser, server] requires {
creation note id "note" : Note input record { title:string; };
};
}`,
{ source },
);
assert.equal(result.ok, false);
assert.match(JSON.stringify(result.diagnostics), /creation requires transaction/);
});
test("the authored storage policy is register, without an old spelling alias", () => {
const result = compileCapabilitySource(text.replaceAll("policy register", "policy optimistic-register"), "notes.qx");
assert.equal(result.ok, false);
assert.ok(result.diagnostics.some((d) => d.phase === "syntax"));
});
test("initialization contracts participate in executable source identity", async () => {
const { runtimeContracts } = await import("../src/capability-model/index.js");
const result = compile();
assert.ok(result.ok, JSON.stringify(result.diagnostics));
const before = runtimeContracts(result.workspace);
const changed = structuredClone(result.workspace);
changed.conformances[0]!.initialization![0]!.input = "renamed";
assert.notDeepEqual(runtimeContracts(changed), before);
});
test("to-many initialization requires stable entry keys and typed targets", async () => {
const { validateInitialization } = await import("../src/capability-model/initialization.js");
const { capabilityId } = await import("../src/capability-model/index.js");
const result = compile();
assert.ok(result.ok, JSON.stringify(result.diagnostics));
const workspace = result.workspace;
const owner = workspace.conformances[1]!;
const state = owner.privateAttachments[0]!;
assert.equal(state.kind, "state");
if (state.kind !== "state") return;
state.defaultValue = [];
const edgeId = capabilityId.edgeType("children"),
projectionId = capabilityId.edgeProjection("children:parent");
owner.privateAttachments.push({
kind: "edge",
id: edgeId,
displayName: "Children",
endpoints: [
{
projectionId,
displayName: "children",
constraint: { kind: "atom", atomId: owner.atomId },
cardinality: "many-unique",
ordered: false,
},
{
projectionId: capabilityId.edgeProjection("children:child"),
displayName: "parent",
constraint: { kind: "atom", atomId: owner.atomId },
cardinality: "optional-one",
ordered: false,
},
],
});
owner.initialization = [{ input: "children", binding: { kind: "edge", edgeTypeId: edgeId, projectionId } }];
const entryType = {
kind: "record" as const,
fields: {
key: { kind: "scalar" as const, name: "string" as const },
target: { kind: "object-ref" as const, expectation: { kind: "atom" as const, atomId: owner.atomId } },
},
};
for (const entry of workspace.packageImports[0]!.exports) {
const port = entry.dependencyPorts[0]!.requirement;
assert.ok(port.kind === "creation" && port.inputType.kind === "record");
port.inputType.fields.tags = { kind: "record", fields: { children: { kind: "list", value: entryType } } };
}
assert.deepEqual(validateInitialization(workspace), []);
Reflect.deleteProperty(entryType.fields, "key");
assert.ok(validateInitialization(workspace).some((i) => i.message.includes("does not match")));
});
+3 -3
View File
@@ -98,8 +98,8 @@ export async function queryWorkspaceFixture(options: { live?: boolean } = {}) {
);
const implementation = (atom: string) => `conform ${atom} as TaskFacts id "${atom}-facts" {
private state Title${atom} id "${atom}:title" on ${atom} : string policy crdt(string) default "Untitled";
private state Done${atom} id "${atom}:done" on ${atom} : bool policy optimistic-register default false;
private state Rank${atom} id "${atom}:rank" on ${atom} : int64 policy optimistic-register default 0;
private state Done${atom} id "${atom}:done" on ${atom} : bool policy register default false;
private state Rank${atom} id "${atom}:rank" on ${atom} : int64 policy register default 0;
private edge Assignee${atom} id "${atom}:assignee" {
atom ${atom} projection assignee id "${atom}:assignee:forward" optional-one;
interface PersonFacts projection tasks id "${atom}:assignee:inverse" many;
@@ -114,7 +114,7 @@ export async function queryWorkspaceFixture(options: { live?: boolean } = {}) {
import interface PersonFacts; import interface TaskFacts; import interface Collection; import package Queries;
atom Task id "Task"; atom Reminder id "Reminder"; atom Person id "Person"; atom Tasks id "Tasks";
conform Person as PersonFacts id "person-facts" {
private state Name id "person:name" on Person : string policy optimistic-register default "Nobody";
private state Name id "person:name" on Person : string policy register default "Nobody";
bind name to state Name;
}
${implementation("Task")} ${implementation("Reminder")}
+2 -2
View File
@@ -8,7 +8,7 @@ workspace Todo id "workspace:todo" revision "workspace:todo@1" commit "111111111
import package TodoRuntime;
shared state ProjectTitle id "slot:project:title" on Project : string
policy optimistic-register default "Untitled project";
policy register default "Untitled project";
conform Project as Named {
bind name.get to state ProjectTitle.read;
@@ -19,7 +19,7 @@ workspace Todo id "workspace:todo" revision "workspace:todo@1" commit "111111111
conform Person as Named {
private state PersonName id "slot:person:name" on Person : string
policy optimistic-register default "Anonymous";
policy register default "Anonymous";
bind name.get to state PersonName.read;
bind name.set to state PersonName.write;
bind name.watch-start to state PersonName.watch-start;
+1 -1
View File
@@ -8,7 +8,7 @@ workspace WebStudioFixture id "workspace:web-studio-fixture" revision "workspace
import package ComponentRuntime;
shared state ProjectName id "slot:project:name" on Project : string
policy optimistic-register default "Untitled project";
policy register default "Untitled project";
shared edge ProjectComponentEdge id "edge:project:component" {
atom ProjectComponent projection subject id "projection:component:subject" exactly-one;
atom Project projection component id "projection:project:component" optional-one;
+1 -1
View File
@@ -36,7 +36,7 @@ function fixture(transform = (s: string) => s, generic = false) {
${forward("Relay", "Alias")}
${forward("Alias", generic ? "Owner<string>" : "Owner")}
conform Item as Owner${generic ? "<string>" : ""} id "owner-conformance" {
private state Title id "title" on Item : string policy optimistic-register default "";
private state Title id "title" on Item : string policy register default "";
bind title to state Title;
}
}`;
+2 -2
View File
@@ -272,7 +272,7 @@ test("generic conformances bind state against specialized signatures", () => {
atom Document id "document";
import interface Reader;
conform Document as Reader<string> id "reader-conformance" {
private state Values id "values-slot" on Document : list<optional<string>> policy optimistic-register;
private state Values id "values-slot" on Document : list<optional<string>> policy register;
bind values.get to state Values.read;
bind values.watch-start to state Values.watch-start;
bind values.watch-stop to state Values.watch-stop;
@@ -328,7 +328,7 @@ test("package receivers and injected dependencies select exact applications", ()
import interface Reader; import interface Summary; import package P;
atom Note id "note";
conform Note as Reader<string> id "reader-conformance" {
private state Values id "values" on Note : list<optional<string>> policy optimistic-register;
private state Values id "values" on Note : list<optional<string>> policy register;
bind values.get to state Values.read;
bind values.watch-start to state Values.watch-start;
bind values.watch-stop to state Values.watch-stop;
+1 -1
View File
@@ -82,7 +82,7 @@ test("dependency scaffolding validates exact sources and preserves unrelated loc
});
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 source = `fragment { conform Game as Playable { private state Board id "slot:board" on Game : string policy 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"'));