Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat: add dynamic module and interface checker (#543)

Myriad-Dreamindddf9be932ab
diff --git a/.gitignore b/.gitignore
index aa6dfb7c..1a6a22fe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -41,3 +41,8 @@ packages/landing/.blog-assets/
/design
/AGENTS.md
/CLAUDE.md
+
+# generated by scripts/gen-ifaces.mjs (pnpm gen:ifaces); typecheck, build and test regenerate it
+packages/server/src/ifaces.json
+# rendered by scripts/iface-page.mjs (pnpm ifaces:page); CI publishes it
+dist-ifaces/
diff --git a/package.json b/package.json
index 150a28e1..5f2600cd 100644
--- a/package.json
+++ b/package.json
@@ -11,7 +11,9 @@
"format": "prettier --write .",
"format:check": "prettier --check .",
"lint": "oxlint",
- "typecheck": "pnpm -r typecheck",
+ "gen:ifaces": "node scripts/gen-ifaces.mjs --project packages/server/tsconfig.json --out packages/server/src/ifaces.json",
+ "ifaces:page": "pnpm gen:ifaces && node scripts/iface-page.mjs --in packages/server/src/ifaces.json --out dist-ifaces",
+ "typecheck": "pnpm gen:ifaces && pnpm -r typecheck",
"test": "pnpm -r test",
"test:e2e": "pnpm --filter @prismshadow/penguin-core test:e2e",
"build": "pnpm -r build && pnpm link:cli",
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index 3fa4dd10..4cb96637 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -151,6 +151,32 @@ export interface CreateAgentOptions {
* Sessions. Absent = commands spawn unconfined.
*/
confineSpawn?: () => SpawnConfiner | null;
+ /**
+ * What a host adds to every Session this Agent assembles — see {@link AgentAssembly}.
+ * Host policy like
+ * `proxyEnv`: inherited by subagents' Agents, re-read at every Session creation so a
+ * hot push that changes the set reaches the next Session without a restart.
+ */
+ assembly?: AgentAssembly;
+}
+
+/**
+ * The host's contributions to Session assembly. Everything an Agent's own folder
+ * decides (system prompt, tool selection, MCP servers, model, compaction, memory) stays
+ * in its config; this is what the HOSTING PROCESS adds on top, for every Agent.
+ */
+export interface AgentAssembly {
+ /**
+ * Sections appended to the assembled system prompt, in order, each as `# <title>` +
+ * text. Empty = the prompt is exactly the Agent's own.
+ */
+ promptSections?(): readonly PromptSection[];
+}
+
+export interface PromptSection {
+ /** The `# ` heading the section is appended under. */
+ title: string;
+ text: string;
}
/** The Session coordinates a {@link CreateAgentOptions.controlEnv} policy is evaluated with. */
@@ -321,6 +347,12 @@ export function metaMaxTokens(budget: number, modelCap: number | undefined): num
return modelCap !== undefined && modelCap > 0 ? Math.min(budget, modelCap) : budget;
}
+/** The assembled prompt plus the host's sections, each under its own heading. */
+function withPromptSections(prompt: string, sections: readonly PromptSection[]): string {
+ if (sections.length === 0) return prompt;
+ return [prompt, ...sections.map((s) => `# ${s.title}\n${s.text}`)].join("\n\n");
+}
+
/** Create or load an Agent (the one init-enabled use of `loadAgentState`). */
export async function createAgent(opts: CreateAgentOptions = {}): Promise<Agent> {
const state = await loadAgentState({
@@ -337,6 +369,7 @@ export async function createAgent(opts: CreateAgentOptions = {}): Promise<Agent>
opts.controlEnv,
opts.pathPrepend,
opts.confineSpawn,
+ opts.assembly,
);
}
@@ -352,6 +385,8 @@ export class Agent {
private readonly pathPrepend?: () => string[],
/** See {@link CreateAgentOptions.confineSpawn}; forwarded into every Session's Environment. */
private readonly confineSpawn?: () => SpawnConfiner | null,
+ /** See {@link CreateAgentOptions.assembly}; read at every Session creation. */
+ private readonly assembly?: AgentAssembly,
) {}
/**
@@ -427,18 +462,21 @@ export class Agent {
workspaceDir: spec.workspaceDir,
enabled: state.systemConfig.memory?.enabled !== false,
});
- systemPrompt = assembleSystemPrompt(
- state,
- sessionEnvironment(spec.workspaceDir, spec.sessionId, {
- agentId,
- projectDir: projectDir(root, projectId),
- provider: spec.modelEntry.provider,
- modelId: spec.modelEntry.model_id,
- }),
- Object.keys(vault),
- installedSkills,
- memory,
- scheduleNames,
+ systemPrompt = withPromptSections(
+ assembleSystemPrompt(
+ state,
+ sessionEnvironment(spec.workspaceDir, spec.sessionId, {
+ agentId,
+ projectDir: projectDir(root, projectId),
+ provider: spec.modelEntry.provider,
+ modelId: spec.modelEntry.model_id,
+ }),
+ Object.keys(vault),
+ installedSkills,
+ memory,
+ scheduleNames,
+ ),
+ this.assembly?.promptSections?.() ?? [],
);
}
@@ -927,6 +965,7 @@ export class Agent {
...(parentAgent.controlEnv ? { controlEnv: parentAgent.controlEnv } : {}),
...(parentAgent.pathPrepend ? { pathPrepend: parentAgent.pathPrepend } : {}),
...(parentAgent.confineSpawn ? { confineSpawn: parentAgent.confineSpawn } : {}),
+ ...(parentAgent.assembly ? { assembly: parentAgent.assembly } : {}),
})
: parentAgent;
// The child Session follows the PARENT Session, never the Project default: with the
@@ -976,6 +1015,7 @@ export class Agent {
...(parentAgent.controlEnv ? { controlEnv: parentAgent.controlEnv } : {}),
...(parentAgent.pathPrepend ? { pathPrepend: parentAgent.pathPrepend } : {}),
...(parentAgent.confineSpawn ? { confineSpawn: parentAgent.confineSpawn } : {}),
+ ...(parentAgent.assembly ? { assembly: parentAgent.assembly } : {}),
});
const childSession = await childAgent.resumeSession({ sessionId });
return subagentHandleFor(childSession);
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 7a54be07..16a03d5a 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -50,6 +50,7 @@ export type {
} from "./engine/context-engine.js";
export { Session } from "./session.js";
export type { SessionConfig } from "./session.js";
+export type { AgentAssembly, PromptSection } from "./agent.js";
// Session-title generation lives in internal/ (an assembly detail of Session.generateTitle);
// only its narrow public surface is re-exported: the result type (part of
// Session.generateTitle's signature) and the two cleaners, sanitizeTitle and truncateTitle,
diff --git a/packages/core/src/kernel/check.ts b/packages/core/src/kernel/check.ts
new file mode 100644
index 00000000..89f40002
--- /dev/null
+++ b/packages/core/src/kernel/check.ts
@@ -0,0 +1,286 @@
+/**
+ * The module-tree check: manifests + interface table in, problems out. Nothing here
+ * executes module code, so it runs on the sending side of a push (against the target's
+ * published table), at boot (before any create), and in CI.
+ *
+ * Three questions, per module:
+ * 1. every `requires` resolves to a visible module whose provided interface
+ * structurally satisfies the required one ({@link satisfies});
+ * 2. every contribution names an existing `<module>.<slot>` and parses under that
+ * slot's data schema;
+ * 3. every `provides` names an interface the table actually carries.
+ *
+ * Visibility is lexical: a module sees its siblings, its ancestors and their siblings —
+ * not another subtree's internals, and not itself. Anything the host publishes (the
+ * runtime's capabilities) is visible everywhere, as a virtual root-level sibling.
+ *
+ * Ancestors are visible to CONTRIBUTE to (a child fills its parent's slots), not to
+ * REQUIRE from: a parent is created after its children, so its api does not exist when
+ * a child is created. The booter orders it so; the check refuses the requirement here,
+ * before any code runs, rather than letting it surface as a dependency cycle at boot.
+ */
+import { type } from "arktype";
+import type { Json } from "./json.js";
+import type { IfaceDecl, TableLike } from "./sig.js";
+import { satisfies, tableOf } from "./sig.js";
+import type { Manifest } from "./manifest.js";
+import { ifaceKey, splitSlotKey } from "./manifest.js";
+
+/** A manifest and its children, as the tree is declared. */
+export interface ManifestNode {
+ manifest: Manifest;
+ children: ManifestNode[];
+}
+
+/** What the host publishes: modules with provided interfaces, no manifests of their own. */
+export type Published = Record<string /* module name */, Record<string /* alias */, IfaceDecl>>;
+
+export type Problem =
+ | { path: string; kind: "unresolved"; alias: string; from: string; why: string }
+ | { path: string; kind: "mismatch"; alias: string; from: string; method: string; why: string }
+ | { path: string; kind: "unknown-iface"; alias: string; ref: string }
+ | { path: string; kind: "no-such-slot"; slotKey: string }
+ | { path: string; kind: "bad-contribution"; slotKey: string; id: string; why: string }
+ | { path: string; kind: "duplicate-id"; id: string; other: string }
+ | { path: string; kind: "duplicate-module"; name: string; other: string };
+
+interface Located {
+ path: string;
+ manifest: Manifest;
+ /** Module names this module may wire to or contribute to. */
+ visible: Set<string>;
+ /** The subset of `visible` that is an ancestor — contributable, not requirable. */
+ ancestors: Set<string>;
+}
+
+/** Provided interfaces of a module, by alias, resolved through the table. */
+function provided(
+ manifest: Manifest,
+ table: TableLike,
+): { byAlias: Record<string, IfaceDecl>; unknown: Array<{ alias: string; ref: string }> } {
+ const byAlias: Record<string, IfaceDecl> = {};
+ const unknown: Array<{ alias: string; ref: string }> = [];
+ for (const [alias, ref] of Object.entries(manifest.provides)) {
+ const decl = tableOf(table).ifaces[ifaceKey(manifest.name, ref)];
+ if (decl === undefined) unknown.push({ alias, ref });
+ else byAlias[alias] = decl;
+ }
+ return { byAlias, unknown };
+}
+
+function locate(root: ManifestNode): Located[] {
+ const out: Located[] = [];
+ const walk = (node: ManifestNode, path: string, inherited: string[], ancestors: string[]) => {
+ const names = node.children.map((c) => c.manifest.name);
+ const above = [...ancestors, node.manifest.name];
+ for (const child of node.children) {
+ const childPath = `${path}/${child.manifest.name}`;
+ const siblings = names.filter((n) => n !== child.manifest.name);
+ out.push({
+ path: childPath,
+ manifest: child.manifest,
+ visible: new Set([...inherited, node.manifest.name, ...siblings]),
+ ancestors: new Set(above),
+ });
+ walk(child, childPath, [...inherited, node.manifest.name, ...names], above);
+ }
+ };
+ out.push({
+ path: `/${root.manifest.name}`,
+ manifest: root.manifest,
+ visible: new Set(),
+ ancestors: new Set(),
+ });
+ walk(root, `/${root.manifest.name}`, [], []);
+ return out;
+}
+
+export interface CheckResult {
+ problems: Problem[];
+ /** Module name → its provided interfaces by alias (the tree's own plus the published). */
+ provides: Record<string, Record<string, IfaceDecl>>;
+}
+
+export function checkTree(
+ root: ManifestNode,
+ table: TableLike,
+ published: Published = {},
+): CheckResult {
+ const problems: Problem[] = [];
+ const located = locate(root);
+ const byName = new Map<string, Located>();
+ for (const m of located) {
+ const other = byName.get(m.manifest.name);
+ if (other !== undefined) {
+ problems.push({
+ path: m.path,
+ kind: "duplicate-module",
+ name: m.manifest.name,
+ other: other.path,
+ });
+ continue;
+ }
+ byName.set(m.manifest.name, m);
+ }
+ const provides: Record<string, Record<string, IfaceDecl>> = { ...published };
+ for (const m of byName.values()) {
+ const { byAlias, unknown } = provided(m.manifest, table);
+ for (const u of unknown) problems.push({ path: m.path, kind: "unknown-iface", ...u });
+ provides[m.manifest.name] = byAlias;
+ }
+ const ids = new Map<string, string>();
+ for (const m of byName.values()) {
+ const mf = m.manifest;
+ for (const [alias, need] of Object.entries(mf.requires)) {
+ const required = tableOf(table).ifaces[ifaceKey(mf.name, need.iface)];
+ if (required === undefined) {
+ problems.push({ path: m.path, kind: "unknown-iface", alias, ref: need.iface });
+ continue;
+ }
+ const requirable = (from: string) =>
+ (m.visible.has(from) && !m.ancestors.has(from)) || from in published;
+ const candidates =
+ need.from !== undefined
+ ? [need.from]
+ : [...m.visible, ...Object.keys(published)].filter(
+ (name) => name !== mf.name && requirable(name),
+ );
+ const matches: string[] = [];
+ let lastMismatch: { from: string; method: string; why: string } | null = null;
+ for (const from of candidates) {
+ if (!requirable(from)) continue;
+ const offered = provides[from];
+ if (offered === undefined) continue;
+ for (const decl of Object.values(offered)) {
+ const gaps = satisfies(decl, required, table);
+ if (gaps.length === 0) {
+ matches.push(from);
+ break;
+ }
+ lastMismatch = { from, method: gaps[0]!.method, why: gaps[0]!.why };
+ }
+ }
+ if (matches.length === 1) continue;
+ if (need.from !== undefined) {
+ const from = need.from;
+ if (!requirable(from) || provides[from] === undefined) {
+ problems.push({
+ path: m.path,
+ kind: "unresolved",
+ alias,
+ from,
+ why: m.ancestors.has(from)
+ ? "an ancestor — created after its children, so its api is not there yet"
+ : from === mf.name
+ ? "itself"
+ : byName.has(from)
+ ? "not visible from here"
+ : "no such module",
+ });
+ } else if (lastMismatch !== null) {
+ problems.push({ path: m.path, kind: "mismatch", alias, ...lastMismatch });
+ } else {
+ problems.push({ path: m.path, kind: "unresolved", alias, from, why: "provides nothing" });
+ }
+ } else {
+ problems.push({
+ path: m.path,
+ kind: "unresolved",
+ alias,
+ from: "",
+ why:
+ matches.length === 0
+ ? "no visible module provides an interface satisfying it"
+ : `ambiguous: ${matches.join(", ")} all satisfy it — name one with 'from'`,
+ });
+ }
+ }
+ for (const [slotKey, entries] of Object.entries(mf.contributes)) {
+ const split = splitSlotKey(slotKey);
+ const reachable =
+ split !== null &&
+ (split.module === mf.name || m.visible.has(split.module) || split.module in published);
+ const target = reachable ? provides[split.module] : undefined;
+ const slot =
+ split === null || target === undefined
+ ? undefined
+ : Object.values(target)
+ .map((decl) => decl.slots[split.slot])
+ .find((s) => s !== undefined);
+ if (slot === undefined) {
+ problems.push({ path: m.path, kind: "no-such-slot", slotKey });
+ continue;
+ }
+ let schema: ((v: unknown) => unknown) | null = null;
+ try {
+ schema = type.raw(inlineRefs(slot.data, tableOf(table).types)).onUndeclaredKey("reject");
+ } catch (err) {
+ problems.push({
+ path: m.path,
+ kind: "bad-contribution",
+ slotKey,
+ id: "*",
+ why: `slot schema is not an arktype definition: ${err instanceof Error ? err.message : String(err)}`,
+ });
+ continue;
+ }
+ for (const entry of entries) {
+ const other = ids.get(entry.id);
+ if (other !== undefined) {
+ problems.push({ path: m.path, kind: "duplicate-id", id: entry.id, other });
+ } else {
+ ids.set(entry.id, m.path);
+ }
+ const { id: _id, ...data } = entry;
+ const out = schema(data);
+ if (out instanceof type.errors) {
+ problems.push({
+ path: m.path,
+ kind: "bad-contribution",
+ slotKey,
+ id: entry.id,
+ why: out.summary,
+ });
+ }
+ }
+ }
+ }
+ return { problems, provides };
+}
+
+/** A definition with its `$ref`s substituted, for arktype (which knows no references); a cycle stays a reference and parses as `unknown`. */
+export function inlineRefs(def: Json, types: Record<string, Json>, stack: string[] = []): Json {
+ if (Array.isArray(def)) return def.map((d) => inlineRefs(d, types, stack));
+ if (def !== null && typeof def === "object") {
+ const keys = Object.keys(def);
+ if (keys.length === 1 && keys[0] === "$ref" && typeof def.$ref === "string") {
+ const name = def.$ref;
+ const target = types[name];
+ if (target === undefined || stack.includes(name)) return "unknown";
+ return inlineRefs(target, types, [...stack, name]);
+ }
+ return Object.fromEntries(
+ Object.entries(def).map(([k, v]) => [k, inlineRefs(v, types, stack)]),
+ );
+ }
+ return def;
+}
+
+export function describeProblem(p: Problem): string {
+ switch (p.kind) {
+ case "unresolved":
+ return `${p.path}: requires.${p.alias}${p.from ? ` from '${p.from}'` : ""}: ${p.why}`;
+ case "mismatch":
+ return `${p.path}: requires.${p.alias} from '${p.from}': ${p.method}: ${p.why}`;
+ case "unknown-iface":
+ return `${p.path}: '${p.alias}' names interface '${p.ref}', which the table does not carry`;
+ case "no-such-slot":
+ return `${p.path}: contributes to '${p.slotKey}', which no visible module declares`;
+ case "bad-contribution":
+ return `${p.path}: contribution '${p.id}' to '${p.slotKey}': ${p.why}`;
+ case "duplicate-id":
+ return `${p.path}: contribution id '${p.id}' is already used by ${p.other}`;
+ case "duplicate-module":
+ return `${p.path}: module name '${p.name}' is already used by ${p.other}`;
+ }
+}
diff --git a/packages/core/src/kernel/data.ts b/packages/core/src/kernel/data.ts
new file mode 100644
index 00000000..46fcc1eb
--- /dev/null
+++ b/packages/core/src/kernel/data.ts
@@ -0,0 +1,201 @@
+/**
+ * Assignability over data definitions — the `{ data }` half of a signature.
+ *
+ * A definition is an arktype DEFINITION: a string expression (`"string"`, `"'a'|'b'"`,
+ * `"number[]"`), an object (`{ a: "string", "b?": "number", "[string]": "unknown" }`) or
+ * a tuple expression (`[def, "[]"]`, `[def, "|", def]`, `[def, "&", def]`, or a plain
+ * tuple of definitions). The generator emits exactly these forms.
+ *
+ * Why not arktype's own `extends`: it is intersection identity (`A & B ≡ A`), which
+ * rejects `{ a: string }` ⊆ `{ a: string; meta?: X }` — but that is the assignability
+ * every TS caller relies on, and the one Go's rule means. So the structural forms are
+ * compared here with TS rules (extra keys allowed, optional keys may be absent, arrays
+ * and tuples elementwise, unions member-wise), and only LEAF string expressions —
+ * primitives, literals, literal unions — go to arktype.
+ */
+import { type } from "arktype";
+import type { Json } from "./json.js";
+import { isJsonObject } from "./json.js";
+
+type Def = Json;
+
+/** Named data definitions a definition may reference as `{ "$ref": "<name>" }`. */
+export type TypeTable = Record<string, Json>;
+
+const refOf = (d: Def): string | null =>
+ isJsonObject(d) && typeof d.$ref === "string" && Object.keys(d).length === 1 ? d.$ref : null;
+
+const isOp = (d: Def, op: string): d is [Def, string, Def] =>
+ Array.isArray(d) && d.length === 3 && d[1] === op;
+const isArrayForm = (d: Def): d is [Def, "[]"] =>
+ Array.isArray(d) && d.length === 2 && d[1] === "[]";
+const isTuple = (d: Def): d is Def[] =>
+ Array.isArray(d) && !isArrayForm(d) && !isOp(d, "|") && !isOp(d, "&");
+
+/** Top-level `|` split of a string expression that has no grouping; null when it has. */
+function splitUnion(s: string): string[] | null {
+ if (/[()[\]{}<>]/.test(s.replace(/'[^']*'/g, ""))) return null;
+ const parts = s.split("|").map((p) => p.trim());
+ return parts.length > 1 ? parts : null;
+}
+
+/** `T[]` on a string expression, when unambiguous. */
+function arrayElem(s: string): string | null {
+ const m = /^(.*)\[\]$/.exec(s.trim());
+ if (m === null) return null;
+ const inner = m[1]!;
+ return splitUnion(inner) === null ? inner : null;
+}
+
+function leafExtends(a: string, b: string): boolean {
+ try {
+ return type.raw(a).extends(type.raw(b));
+ } catch {
+ return a === b;
+ }
+}
+
+/**
+ * a ⊆ b. `types` resolves `$ref`s; a pair of references met again while it is being
+ * decided is assumed to hold (coinduction — the rule that makes recursive types finite).
+ */
+export function dataExtends(
+ a: Def,
+ b: Def,
+ types: TypeTable = {},
+ seen: Set<string> = new Set(),
+): boolean {
+ if (typeof b === "string" && b.trim() === "unknown") return true;
+ const ra = refOf(a);
+ const rb = refOf(b);
+ if (ra !== null || rb !== null) {
+ if (ra !== null && rb !== null) {
+ if (ra === rb) return true;
+ const key = `${ra}<:${rb}`;
+ if (seen.has(key)) return true;
+ seen = new Set(seen).add(key);
+ }
+ const da = ra === null ? a : types[ra];
+ const db = rb === null ? b : types[rb];
+ if (da === undefined || db === undefined) return false; // a dangling reference fits nothing
+ return dataExtends(da, db, types, seen);
+ }
+ if (typeof b === "string" && b.trim() === "unknown") return true;
+ if (typeof a === "string" && a.trim() === "never") return true;
+ // Unions: every member of a must fit b; a fits a union b when it fits any member.
+ if (isOp(a, "|")) return dataExtends(a[0], b, types, seen) && dataExtends(a[2], b, types, seen);
+ if (typeof a === "string") {
+ const members = splitUnion(a);
+ if (members !== null && typeof b !== "string")
+ return members.every((m) => dataExtends(m, b, types, seen));
+ }
+ if (isOp(b, "|")) return dataExtends(a, b[0], types, seen) || dataExtends(a, b[2], types, seen);
+ if (typeof b === "string" && typeof a !== "string") {
+ const members = splitUnion(b);
+ if (members !== null) return members.some((m) => dataExtends(a, m, types, seen));
+ }
+ // Intersections. On the right, both halves must hold. On the left, the halves only
+ // mean something together — `{ a } & { b }` is `{ a; b }` — so object members are
+ // merged into one shape first; only when a half is not an object does either half
+ // alone have to fit.
+ if (isOp(b, "&")) return dataExtends(a, b[0], types, seen) && dataExtends(a, b[2], types, seen);
+ if (isOp(a, "&")) {
+ const merged = mergeIntersection(a, types);
+ if (merged !== null) return dataExtends(merged, b, types, seen);
+ return dataExtends(a[0], b, types, seen) || dataExtends(a[2], b, types, seen);
+ }
+ // Arrays, in either spelling.
+ const aElem = isArrayForm(a) ? a[0] : typeof a === "string" ? arrayElem(a) : null;
+ const bElem = isArrayForm(b) ? b[0] : typeof b === "string" ? arrayElem(b) : null;
+ if (aElem !== null && bElem !== null) return dataExtends(aElem, bElem, types, seen);
+ if (isTuple(a) && bElem !== null) return a.every((e) => dataExtends(e, bElem, types, seen));
+ if (isTuple(a) && isTuple(b))
+ return a.length === b.length && a.every((e, i) => dataExtends(e, b[i]!, types, seen));
+ // Objects.
+ if (isJsonObject(a) && isJsonObject(b)) return objectExtends(a, b, types, seen);
+ // Leaves (and anything mixed the forms above did not settle).
+ if (typeof a === "string" && typeof b === "string") return leafExtends(a, b);
+ return false;
+}
+
+function objectExtends(
+ a: { [k: string]: Def },
+ b: { [k: string]: Def },
+ types: TypeTable,
+ seen: Set<string>,
+): boolean {
+ const aIndex = a["[string]"];
+ const bIndex = b["[string]"];
+ const aKeys = new Map<string, { def: Def; optional: boolean }>();
+ for (const [k, def] of Object.entries(a)) {
+ if (k === "[string]") continue;
+ const optional = k.endsWith("?");
+ aKeys.set(optional ? k.slice(0, -1) : k, { def: def!, optional });
+ }
+ for (const [k, def] of Object.entries(b)) {
+ if (k === "[string]") continue;
+ const optional = k.endsWith("?");
+ const name = optional ? k.slice(0, -1) : k;
+ const have = aKeys.get(name);
+ if (have === undefined) {
+ if (optional) continue;
+ // A required key can still be met by a's index signature.
+ if (aIndex !== undefined && dataExtends(aIndex, def!, types, seen)) continue;
+ return false;
+ }
+ if (have.optional && !optional) return false;
+ if (!dataExtends(have.def, def!, types, seen)) return false;
+ }
+ if (bIndex !== undefined) {
+ for (const [name, have] of aKeys) {
+ if (name in b || `${name}?` in b) continue;
+ if (!dataExtends(have.def, bIndex, types, seen)) return false;
+ }
+ if (aIndex !== undefined && !dataExtends(aIndex, bIndex, types, seen)) return false;
+ }
+ return true;
+}
+
+/**
+ * `A & B & …` as one object definition, when every member (references followed) is a
+ * plain object; null otherwise. A key both sides carry keeps both constraints, as an
+ * intersection of its own; a key required by any member is required.
+ */
+function mergeIntersection(d: Def, types: TypeTable): { [k: string]: Def } | null {
+ const members: Array<{ [k: string]: Def }> = [];
+ const collect = (x: Def): boolean => {
+ if (isOp(x, "&")) return collect(x[0]) && collect(x[2]);
+ const ref = refOf(x);
+ const resolved = ref === null ? x : types[ref];
+ if (resolved === undefined || !isJsonObject(resolved) || refOf(resolved) !== null) return false;
+ members.push(resolved);
+ return true;
+ };
+ if (!collect(d)) return null;
+ const out: { [k: string]: Def } = {};
+ const seenKeys = new Map<string, { def: Def; optional: boolean }>();
+ for (const m of members) {
+ for (const [k, def] of Object.entries(m)) {
+ if (k === "[string]") {
+ out["[string]"] = "[string]" in out ? [out["[string]"]!, "&", def!] : def!;
+ continue;
+ }
+ const optional = k.endsWith("?");
+ const name = optional ? k.slice(0, -1) : k;
+ const have = seenKeys.get(name);
+ seenKeys.set(
+ name,
+ have === undefined
+ ? { def: def!, optional }
+ : { def: [have.def, "&", def!], optional: have.optional && optional },
+ );
+ }
+ }
+ for (const [name, { def, optional }] of seenKeys) out[optional ? `${name}?` : name] = def;
+ return out;
+}
+
+/** Whether `undefined` fits the definition — an optional parameter's test. */
+export function acceptsUndefined(def: Def, types: TypeTable = {}): boolean {
+ return dataExtends("undefined", def, types);
+}
diff --git a/packages/core/src/kernel/index.ts b/packages/core/src/kernel/index.ts
index 912c2b68..31b35c37 100644
--- a/packages/core/src/kernel/index.ts
+++ b/packages/core/src/kernel/index.ts
@@ -23,3 +23,47 @@ export type {
export { boot, BootError, initialDoc } from "./boot.js";
export type { UpgradeBlocked, UpgradeFailed, UpgradeResult } from "./upgrade.js";
export { upgrade } from "./upgrade.js";
+export type { IfaceDecl, IfaceTable, Mismatch, Sig, SlotDecl, TableLike, TypeExpr } from "./sig.js";
+export { assignable, extendsExpr, satisfies, show, tableOf } from "./sig.js";
+export type { ChildRef, ContextDecl, Manifest, Requirement } from "./manifest.js";
+export { ifaceKey, parseManifest, splitSlotKey } from "./manifest.js";
+export type { CheckResult, ManifestNode, Problem, Published } from "./check.js";
+export { checkTree, describeProblem, inlineRefs } from "./check.js";
+export type {
+ BootModulesOptions,
+ Contributed,
+ ModuleCtx,
+ ModuleDef,
+ ModuleInstance,
+ ModuleTree,
+ UseOf,
+ ApiOf,
+ IfaceRegistry,
+ ModuleImplOf,
+} from "./module.js";
+export {
+ Bind,
+ Component,
+ bootModules,
+ defineModule,
+ Module,
+ moduleDefiner,
+ moduleDefOf,
+ moduleMetaOf,
+ ModuleBootError,
+ Provide,
+ Use,
+ wire,
+} from "./module.js";
+export type {
+ ClassCtx,
+ ComponentMeta,
+ IfaceClass,
+ ManifestTable,
+ ModuleClass,
+ ModuleMeta,
+} from "./module.js";
+export type { Opaque, Slot } from "./markers.js";
+export { Interface } from "./markers.js";
+export { dataExtends } from "./data.js";
+export type { TypeTable } from "./data.js";
diff --git a/packages/core/src/kernel/manifest.ts b/packages/core/src/kernel/manifest.ts
new file mode 100644
index 00000000..20dd400c
--- /dev/null
+++ b/packages/core/src/kernel/manifest.ts
@@ -0,0 +1,78 @@
+/**
+ * A module's manifest: its static description, as a JSON file that is read and checked
+ * WITHOUT executing the module — the same split VS Code makes between package.json's
+ * `contributes` and the plugin's code.
+ *
+ * {
+ * "name": "agents",
+ * "requires": { "projects": { "iface": "ProjectsNeeded", "from": "projects" } },
+ * "provides": { "agents": "Agents" },
+ * "contributes": { "http.routes": [{ "id": "agents.routes", "prefix": "/api/…", "auth": "user" }] },
+ * "context": { "version": 1, "schema": "{ collapsed?: string[] }" },
+ * "children": ["vault", { "keyed": "workflows" }]
+ * }
+ *
+ * - `provides`: alias → an interface class this module declares, keyed
+ * `<name>#<Export>` in the bundle's iface table.
+ * - `requires`: alias → the SHAPE needed (an interface class the consumer declares —
+ * the Go habit of declaring the interface where it is consumed — or `<pkg>#<Export>`,
+ * copied into this bundle's table at build) and `from`, the module WIRED to provide
+ * it. Satisfaction is structural; `from` only says whose implementation.
+ * - `contributes`: `<module>.<slot>` → entries, each with a unique `id`. Pure data.
+ * - `context`: the parked state's version and schema; migrations are code and live on
+ * the module implementation.
+ */
+import { type } from "arktype";
+import type { Json, JsonObject } from "./json.js";
+
+export interface Requirement {
+ readonly iface: string;
+ readonly from?: string;
+}
+
+export interface ContextDecl {
+ readonly version: number;
+ /** An arktype definition; absent = opaque (anything parks). */
+ readonly schema?: Json;
+}
+
+export type ChildRef = string | { readonly keyed: string };
+
+export interface Manifest {
+ readonly name: string;
+ readonly requires: Readonly<Record<string, Requirement>>;
+ readonly provides: Readonly<Record<string, string>>;
+ readonly contributes: Readonly<
+ Record<string, ReadonlyArray<{ readonly id: string } & JsonObject>>
+ >;
+ readonly context?: ContextDecl;
+ readonly children: ReadonlyArray<ChildRef>;
+}
+
+const ManifestType = type({
+ name: "string > 0",
+ requires: { "[string]": { iface: "string > 0", "from?": "string > 0" } },
+ provides: { "[string]": "string > 0" },
+ contributes: { "[string]": type({ id: "string > 0", "[string]": "unknown" }).array() },
+ "context?": { version: "number.integer >= 1", "schema?": "unknown" },
+ children: type("string").or({ keyed: "string" }).array(),
+});
+
+/** Strict parse of a manifest document; throws with the arktype summary on failure. */
+export function parseManifest(doc: unknown, where = "manifest"): Manifest {
+ const out = ManifestType(doc);
+ if (out instanceof type.errors) throw new Error(`${where}: ${out.summary}`);
+ return out as unknown as Manifest;
+}
+
+/** The iface-table key a manifest reference resolves to. */
+export function ifaceKey(moduleName: string, ref: string): string {
+ return ref.includes("#") ? ref : `${moduleName}#${ref}`;
+}
+
+/** `<module>.<slot>` → its two halves. */
+export function splitSlotKey(key: string): { module: string; slot: string } | null {
+ const at = key.lastIndexOf(".");
+ if (at <= 0 || at === key.length - 1) return null;
+ return { module: key.slice(0, at), slot: key.slice(at + 1) };
+}
diff --git a/packages/core/src/kernel/markers.ts b/packages/core/src/kernel/markers.ts
new file mode 100644
index 00000000..b249c290
--- /dev/null
+++ b/packages/core/src/kernel/markers.ts
@@ -0,0 +1,72 @@
+/**
+ * Type-level markers the interface generator (scripts/gen-ifaces.mjs) recognizes in a
+ * package. They exist only to be projected; at runtime they are the types
+ * they wrap.
+ */
+
+/**
+ * A host object compared by NAME across the push boundary: `Opaque<"AbortSignal">`
+ * projects to `{ opaque: "AbortSignal" }`. The generator refuses an unmarked class type
+ * — writing this out is how a declaration says "structure not checked here".
+ */
+export type Opaque<Name extends string, T = unknown> = T & { readonly __opaque?: Name };
+
+/**
+ * The value `Interface()` returns: a handle that is both a base class and a class
+ * decorator, so one call site serves both spellings below. It is a plain function rather
+ * than a class because a class cannot be invoked as a decorator without `new`.
+ */
+export type IfaceHandle<T> = (abstract new () => T) &
+ (<C>(target: C, context: ClassDecoratorContext) => C);
+
+/**
+ * An interface as a CLASS. It is also a runtime value, so a manifest names it by
+ * reference (`requires: { db: [Db, RuntimeModule] }`) instead of by string. Nothing is
+ * ever constructed from it and nothing is checked by `instanceof`: the check is
+ * structural (kernel/sig.ts); the class is only the handle. The generator projects the
+ * instance type like any other interface.
+ *
+ * Two spellings, for two different things.
+ *
+ * **The interface declares its own members** — `@Interface()`, and the members are the
+ * class's, which is where their doc comments belong:
+ *
+ * ```ts
+ * @Interface()
+ * export abstract class Db {
+ * abstract prepare(sql: string): Opaque<"StatementSync", StatementSync>;
+ * abstract close(): void;
+ * }
+ * ```
+ *
+ * A decorated class must be exactly a declaration: no heritage, no constructor, no
+ * concrete or private member. The generator rejects the rest rather than deciding what
+ * belongs in the contract.
+ *
+ * **The interface IS an existing type** — the base-class form, which the decorator
+ * cannot express: TypeScript has no way to carry a decorator's type argument into the
+ * instance type, so the members would be invisible to every consumer.
+ *
+ * ```ts
+ * export abstract class Config extends Interface<ServerConfig>() {}
+ * ```
+ */
+export function Interface<T = unknown>(): IfaceHandle<T> {
+ // Applied as a decorator it is called with the class and hands it back untouched;
+ // named in a heritage clause it is the (never constructed) base. One function does both
+ // — a `class {}` would throw "cannot be invoked without 'new'" in the first position.
+ function handle(target?: unknown, _context?: unknown): unknown {
+ return target;
+ }
+ return handle as unknown as IfaceHandle<T>;
+}
+
+/**
+ * A contribution slot with a CODE half: the data one contribution carries in the manifest,
+ * and the implementation the contributor binds by id. A slot written as a plain object type
+ * is data-only.
+ */
+export interface Slot<Data, Code = never> {
+ data: Data;
+ code: Code;
+}
diff --git a/packages/core/src/kernel/module.ts b/packages/core/src/kernel/module.ts
new file mode 100644
index 00000000..7d983836
--- /dev/null
+++ b/packages/core/src/kernel/module.ts
@@ -0,0 +1,693 @@
+/**
+ * Module tree boot: manifests decide the wiring, code only provides implementations.
+ *
+ * A module is a manifest ({@link Manifest}) plus one `create`. Boot runs {@link checkTree}
+ * over the manifests first — nothing is created while a problem stands — then creates
+ * modules in dependency order: a module boots after everything it `requires` and after
+ * every module that CONTRIBUTES to one of its slots (the code half of a contribution is
+ * the contributor's `bind[id]`, which exists only once the contributor is created).
+ *
+ * The tree shape is scope, not order: siblings are created in whatever order their
+ * edges allow, and a cycle is a boot error naming the modules in it.
+ *
+ * Parked state: each module's `park()` result is stored under its name; `bootModules`
+ * takes that map back and hands each module its own document after running the
+ * module's migrations. This is the platform node's `modules` field.
+ */
+import { type } from "arktype";
+import type { Json, JsonObject } from "./json.js";
+import { isJsonObject } from "./json.js";
+import type { Resources } from "./boot.js";
+import type { IfaceDecl, TableLike } from "./sig.js";
+import { satisfies, tableOf } from "./sig.js";
+import type { ContextDecl, Manifest, Requirement } from "./manifest.js";
+import { splitSlotKey } from "./manifest.js";
+import type { ManifestNode, Problem, Published } from "./check.js";
+import { checkTree, describeProblem } from "./check.js";
+
+/** One contribution as the consuming module receives it. */
+export interface Contributed<D = JsonObject, C = unknown> {
+ id: string;
+ /** The contributor module's name. */
+ from: string;
+ data: D;
+ /** The contributor's `bind[id]`, when the slot declares a code half. */
+ code?: C;
+}
+
+export interface ModuleCtx<Use = Record<string, unknown>> {
+ /** Resolved requirements, by the manifest's alias. */
+ use: Use;
+ /** Contributions to this module's slots, by slot name. */
+ contributions: Record<string, Contributed[]>;
+ resources: Resources;
+ /** Self-cleaning registration; drained at dispose in reverse order, children first. */
+ effect(dispose: () => void): void;
+}
+
+export interface ModuleInstance<Api = Record<string, unknown>> {
+ /** Provided implementations, by the manifest's provides alias. */
+ api: Api;
+ /** Implementations of this module's own contributions, by contribution id. */
+ bind?: Record<string, unknown>;
+ park?(): Json;
+}
+
+export interface ModuleDef<
+ M extends Manifest = Manifest,
+ Use = Record<string, unknown>,
+ Api = Record<string, unknown>,
+> {
+ manifest: M;
+ /** Context migrations by from-version, chained (1→2→3). */
+ migrations?: Record<number, (old: Json) => Json>;
+ create(ctx: ModuleCtx<Use>, context: Json): ModuleInstance<Api> | Promise<ModuleInstance<Api>>;
+ children?: ModuleDef[];
+}
+
+type RefKey<Ref, Mod extends string> = Ref extends `${string}#${string}`
+ ? Ref
+ : Ref extends string
+ ? `${Mod}#${Ref}`
+ : never;
+type Lookup<Reg, K> = K extends keyof Reg ? Reg[K] : unknown;
+
+/**
+ * Interface key (`<module>#<Export>`) → TypeScript type: a registry a package
+ * may declare over its interface classes, and `moduleDefiner<ThatRegistry>()` is how a manifest literal
+ * gets to type its own `use` and `api`.
+ */
+export type IfaceRegistry = object;
+
+/** The `use` a manifest's `requires` resolves to, by alias. */
+export type UseOf<M extends Manifest, Reg extends IfaceRegistry = IfaceRegistry> = {
+ [A in keyof M["requires"]]: Lookup<Reg, RefKey<M["requires"][A]["iface"], M["name"]>>;
+};
+/** The `api` a manifest's `provides` demands, by alias. */
+export type ApiOf<M extends Manifest, Reg extends IfaceRegistry = IfaceRegistry> = {
+ [A in keyof M["provides"]]: Lookup<Reg, RefKey<M["provides"][A], M["name"]>>;
+};
+
+export interface ModuleImplOf<M extends Manifest, Reg extends IfaceRegistry> {
+ migrations?: Record<number, (old: Json) => Json>;
+ create(
+ ctx: ModuleCtx<UseOf<M, Reg>>,
+ context: Json,
+ ): ModuleInstance<ApiOf<M, Reg>> | Promise<ModuleInstance<ApiOf<M, Reg>>>;
+ children?: ModuleDef[];
+}
+
+/**
+ * A `defineModule` bound to an interface registry. A module is its manifest as a literal
+ * (the static half — the generator extracts it without executing the file) and its
+ * create; `use` and `api` are typed FROM the manifest through the registry, so the two
+ * cannot drift: an alias renamed in `requires` is a type error at every `ctx.use.<alias>`,
+ * and an interface named in `provides` is what `api` must satisfy. A key the registry
+ * does not carry types as `unknown` (a plugin requiring a host interface it has no
+ * types for still boots; the host checks the signature).
+ */
+export function moduleDefiner<Reg extends IfaceRegistry>() {
+ return function defineModule<const M extends Manifest>(
+ manifest: M,
+ impl: ModuleImplOf<M, Reg>,
+ ): ModuleDef<M, UseOf<M, Reg>, ApiOf<M, Reg>> {
+ return { manifest, ...impl };
+ };
+}
+
+/** `defineModule` with no registry: every requirement is `unknown` at compile time. */
+export const defineModule = moduleDefiner<IfaceRegistry>();
+
+// ───────────────────────── class form: @Module / @Use / @Provide / @Bind ─────────────────────────
+
+/** An interface handle: an abstract class whose instance type is the interface (see markers.ts Interface). */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export type IfaceClass<T = any> = abstract new (...args: never[]) => T;
+/** A module class: decorated with @Module; instantiated once per App; `create` is the module's create. */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export type ModuleClass = abstract new (...args: any[]) => object;
+
+/** What a module class's `create` receives: everything in {@link ModuleCtx} except `use` — requirements are fields. */
+export type ClassCtx = Omit<ModuleCtx, "use">;
+
+/**
+ * The static half a module class declares in its decorator. Requirements and provisions
+ * are FIELDS (`@Use`, `@Provide`), where their types already are; what is left here is
+ * the name, the contributions (pure data), the parked context and the child classes.
+ */
+export interface ModuleMeta {
+ readonly contributes?: Readonly<
+ Record<string, ReadonlyArray<{ readonly id: string } & JsonObject>>
+ >;
+ readonly context?: ContextDecl;
+ readonly children?: ReadonlyArray<ModuleClass>;
+}
+
+/** What a @Component declares: a module's meta minus children — a component exports itself. */
+export type ComponentMeta = Omit<ModuleMeta, "children">;
+type Meta = ModuleMeta & { readonly name: string; readonly kind: "module" | "component" };
+
+interface ClassFields {
+ /** field → the module class wired to provide it (undefined = any visible provider). */
+ use: Map<string, ModuleClass | undefined>;
+ provide: Set<string>;
+ /** field → contribution id. */
+ bind: Map<string, string>;
+}
+
+const metas = new WeakMap<ModuleClass, Meta>();
+const fields = new WeakMap<ModuleClass, ClassFields>();
+const fieldsOf = (cls: ModuleClass): ClassFields => {
+ let f = fields.get(cls);
+ if (f === undefined) {
+ f = { use: new Map(), provide: new Set(), bind: new Map() };
+ fields.set(cls, f);
+ }
+ return f;
+};
+
+/**
+ * Registers a class as a module. `create(ctx, context)` runs once per App; the class's
+ * `@Use` fields are injected before it, its `@Provide` fields are read after it, its
+ * `@Bind` fields are the code halves of its contributions, and `park()` (optional)
+ * parks its state.
+ */
+export function Module(meta: ModuleMeta = {}) {
+ return (target: ModuleClass, context: ClassDecoratorContext): void => {
+ metas.set(target, { ...meta, name: nodeName(context), kind: "module" });
+ };
+}
+
+/**
+ * A node's name is the class's DECLARED name — the one the generator read off the source
+ * into the table — and it arrives here as the decorator context's `name`, which both
+ * lowerings emit as a string literal. `target.name` would be the same word until a
+ * minifier renamed the binding; a string literal it cannot touch. So the name the table
+ * carries and the name the class boots under cannot disagree, whatever the bundle went
+ * through.
+ */
+function nodeName(context: ClassDecoratorContext): string {
+ const name = context.name;
+ if (typeof name !== "string" || name === "") {
+ throw new ModuleBootError("a @Module / @Component class must be a named class declaration");
+ }
+ return name;
+}
+
+/**
+ * Registers a class as a COMPONENT: a module that exports itself. The instance is the
+ * provision, named in a consumer by its own class (`@Use() auth!: AuthService`), and its
+ * interface is its public surface as the generator projects it. `@Use` fields are injected
+ * before the optional `create(ctx, context)`; `@Bind` fields and `park()` work as on a
+ * module. A class whose inputs no interface provides (a computed closure, a path) is built
+ * by a @Module instead, which is what "exports others" means.
+ */
+export function Component(meta: ComponentMeta = {}) {
+ return (target: ModuleClass, context: ClassDecoratorContext): void => {
+ metas.set(target, { ...meta, name: nodeName(context), kind: "component" });
+ };
+}
+
+/**
+ * A requirement: `@Use(SessionsModule) readonly runner!: ScheduleTaskRunner;` — the field's
+ * type is the interface, the decorator's argument the module wired to provide it (absent =
+ * whichever visible module structurally satisfies it, if exactly one does). Injected before
+ * `create`. The interface key comes from the generated table, which reads the annotation.
+ */
+export function Use(from?: ModuleClass) {
+ return (_value: undefined, context: ClassFieldDecoratorContext): void => {
+ const name = String(context.name);
+ context.addInitializer(function (this: unknown) {
+ fieldsOf((this as object).constructor as ModuleClass).use.set(name, from);
+ });
+ };
+}
+
+/** A provision: `@Provide() settings!: Settings;` — assigned in `create`, read after it; unassigned = boot error. */
+export function Provide() {
+ return (_value: undefined, context: ClassFieldDecoratorContext): void => {
+ const name = String(context.name);
+ context.addInitializer(function (this: unknown) {
+ fieldsOf((this as object).constructor as ModuleClass).provide.add(name);
+ });
+ };
+}
+
+/** The code half of one contribution: `@Bind("agents.routes") routes!: Hono;` — assigned in `create`. */
+export function Bind(id: string) {
+ return (_value: undefined, context: ClassFieldDecoratorContext): void => {
+ const name = String(context.name);
+ context.addInitializer(function (this: unknown) {
+ fieldsOf((this as object).constructor as ModuleClass).bind.set(name, id);
+ });
+ };
+}
+
+/**
+ * Constructs a component OUTSIDE a tree — a script or a test that wants the class with
+ * its fields supplied by hand. The fields are assigned as the booter would inject them;
+ * nothing is checked, and `create()` is not called.
+ */
+export function wire<T extends object>(
+ cls: new () => T,
+ // `any`, so a callback supplied here is contextually typed rather than an implicit any.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ fields: Record<string, any>,
+): T {
+ return Object.assign(new cls(), fields);
+}
+
+/** The meta a class was decorated with; throws for an undecorated class. */
+export function moduleMetaOf(cls: ModuleClass): Meta {
+ const m = metas.get(cls);
+ if (m === undefined)
+ throw new ModuleBootError(`class '${cls.name}' is not a @Module or @Component`);
+ return m;
+}
+
+/** The manifests the generator extracted, by module name — the `modules` section of the table. */
+export type ManifestTable = Readonly<Record<string, Manifest>>;
+
+/**
+ * Turns a module class (and, recursively, its children) into the {@link ModuleDef} the
+ * booter runs. The string manifest is the generator's (`table.modules[name]` — it read the
+ * field annotations statically); the class is checked against it: every `@Use` field must
+ * be a requirement there with the same `from`, every `@Provide` field a provision, every
+ * child class a child. A mismatch means the table is stale, and says so. `instances`
+ * supplies pre-built instances for classes whose constructor takes arguments.
+ */
+export function moduleDefOf(
+ cls: ModuleClass,
+ opts: {
+ manifests: ManifestTable;
+ instances?: ReadonlyMap<ModuleClass, object>;
+ extra?: ModuleDef[];
+ },
+): ModuleDef {
+ const meta = moduleMetaOf(cls);
+ const manifest = opts.manifests[meta.name];
+ if (manifest === undefined) {
+ throw new ModuleBootError(`${meta.name}: not in the generated manifest table — run gen:ifaces`);
+ }
+ const instance = (opts.instances?.get(cls) ??
+ new (cls as unknown as new () => object)()) as Record<string, unknown> & {
+ setup?: (ctx: ClassCtx, context: Json) => void | Promise<void>;
+ park?: () => Json;
+ migrations?: Record<number, (old: Json) => Json>;
+ };
+ const f = fieldsOf(cls);
+ const stale = (what: string) =>
+ new ModuleBootError(
+ `${meta.name}: ${what} — the generated manifest table is stale; run gen:ifaces`,
+ );
+ for (const [field, from] of f.use) {
+ const r = manifest.requires[field];
+ if (r === undefined) throw stale(`@Use field '${field}' is not a requirement in the table`);
+ // `@Use()` with no argument leaves the wiring to the table (the generator wires a field
+ // typed by a component class to that component); an explicit argument must agree.
+ const fromName = from === undefined ? undefined : moduleMetaOf(from).name;
+ if (fromName !== undefined && r.from !== fromName)
+ throw stale(
+ `@Use field '${field}' is wired to '${fromName}' in code, '${r.from}' in the table`,
+ );
+ }
+ for (const field of Object.keys(manifest.requires)) {
+ if (!f.use.has(field)) throw stale(`requirement '${field}' in the table has no @Use field`);
+ }
+ const selfAlias = meta.kind === "component" ? meta.name : null;
+ if (selfAlias !== null && manifest.provides[selfAlias] === undefined)
+ throw stale(`component '${meta.name}' does not provide itself in the table`);
+ for (const field of f.provide) {
+ if (manifest.provides[field] === undefined)
+ throw stale(`@Provide field '${field}' is not a provision in the table`);
+ }
+ for (const field of Object.keys(manifest.provides)) {
+ if (field === selfAlias) continue;
+ if (!f.provide.has(field))
+ throw stale(`provision '${field}' in the table has no @Provide field`);
+ }
+ const childNames = (meta.children ?? []).map((c) => moduleMetaOf(c).name);
+ const declared = manifest.children
+ .map((c) => (typeof c === "string" ? c : c.keyed))
+ .filter((c) => c !== "*");
+ if (childNames.join(",") !== declared.join(",")) {
+ throw stale(
+ `children are [${childNames.join(", ")}] in code, [${declared.join(", ")}] in the table`,
+ );
+ }
+ const extra = opts.extra ?? [];
+ const def: ModuleDef = {
+ manifest: {
+ ...manifest,
+ children: [...manifest.children.filter((c) => c !== "*"), ...(extra.length > 0 ? ["*"] : [])],
+ },
+ async create(ctx, context) {
+ for (const field of f.use.keys())
+ instance[field] = (ctx.use as Record<string, unknown>)[field];
+ if (typeof instance.setup === "function") await instance.setup(ctx, context);
+ const api: Record<string, unknown> = {};
+ if (selfAlias !== null) api[selfAlias] = instance;
+ for (const field of f.provide) {
+ if (instance[field] === undefined) {
+ throw new ModuleBootError(
+ `${meta.name}: setup() left @Provide field '${field}' unassigned`,
+ );
+ }
+ api[field] = instance[field];
+ }
+ const bind: Record<string, unknown> = {};
+ for (const [field, id] of f.bind) {
+ if (instance[field] === undefined) {
+ throw new ModuleBootError(
+ `${meta.name}: create() left @Bind field '${field}' ('${id}') unassigned`,
+ );
+ }
+ bind[id] = instance[field];
+ }
+ const out: ModuleInstance = { api, bind };
+ if (typeof instance.park === "function") out.park = () => instance.park!();
+ return out;
+ },
+ children: [
+ ...(meta.children ?? []).map((child) => moduleDefOf(child, { ...opts, extra: undefined })),
+ ...extra,
+ ],
+ };
+ if (instance.migrations !== undefined) def.migrations = instance.migrations;
+ return def;
+}
+
+export class ModuleBootError extends Error {
+ constructor(
+ message: string,
+ readonly problems: Problem[] = [],
+ ) {
+ super(message);
+ this.name = "ModuleBootError";
+ }
+}
+
+/** A booted tree. */
+export interface ModuleTree {
+ /** A module's provided api by module name and alias. */
+ api<T = unknown>(module: string, alias: string): T;
+ has(module: string): boolean;
+ /** Every module's parked document, by name — the platform node stores this. */
+ park(): Record<string, Json>;
+ /** Reverse creation order. */
+ dispose(): void;
+}
+
+export interface BootModulesOptions {
+ ifaces: TableLike;
+ /** What the host publishes: interface declarations AND the live values behind them. */
+ published?: { ifaces: Published; values: Record<string, Record<string, unknown>> };
+ resources: Resources;
+ /** Parked documents from the previous generation, by module name. */
+ parked?: Record<string, Json>;
+}
+
+interface Flat {
+ def: ModuleDef;
+ parent: Flat | null;
+ childrenDefs: ModuleDef[];
+}
+
+function flatten(root: ModuleDef): { nodes: Flat[]; tree: ManifestNode } {
+ const nodes: Flat[] = [];
+ const walk = (def: ModuleDef, parent: Flat | null): ManifestNode => {
+ const flat: Flat = { def, parent, childrenDefs: def.children ?? [] };
+ nodes.push(flat);
+ return { manifest: def.manifest, children: flat.childrenDefs.map((c) => walk(c, flat)) };
+ };
+ const tree = walk(root, null);
+ return { nodes, tree };
+}
+
+/** The module each `requires` alias wires to, after the check has proven it unique. */
+function wiring(
+ manifest: Manifest,
+ provides: Record<string, Record<string, IfaceDecl>>,
+ ifaces: TableLike,
+): Record<string, { from: string; alias: string }> {
+ const out: Record<string, { from: string; alias: string }> = {};
+ for (const [alias, need] of Object.entries(manifest.requires)) {
+ const required =
+ tableOf(ifaces).ifaces[
+ need.iface.includes("#") ? need.iface : `${manifest.name}#${need.iface}`
+ ]!;
+ const candidates = need.from !== undefined ? [need.from] : Object.keys(provides);
+ for (const from of candidates) {
+ if (from === manifest.name) continue;
+ for (const [pAlias, decl] of Object.entries(provides[from] ?? {})) {
+ // checkTree already established satisfaction; pick the first satisfying alias.
+ if (satisfiesQuick(decl, required, ifaces)) {
+ out[alias] = { from, alias: pAlias };
+ break;
+ }
+ }
+ if (out[alias] !== undefined) break;
+ }
+ }
+ return out;
+}
+
+function satisfiesQuick(offered: IfaceDecl, required: IfaceDecl, table: TableLike): boolean {
+ return satisfies(offered, required, table).length === 0;
+}
+
+function migrateContext(def: ModuleDef, doc: Json | undefined): Json {
+ const decl = def.manifest.context;
+ if (decl === undefined || doc === undefined) return null; // No context, or a fresh boot: nothing to migrate.
+ let version = 1;
+ let self: Json = null;
+ if (isJsonObject(doc) && typeof doc.v === "number" && "self" in doc) {
+ version = doc.v;
+ self = doc.self;
+ } else if (doc !== undefined) {
+ self = doc;
+ }
+ if (version > decl.version) {
+ throw new ModuleBootError(
+ `${def.manifest.name}: parked under context v${version}, newer than this module's v${decl.version}`,
+ );
+ }
+ while (version < decl.version) {
+ const migrate = def.migrations?.[version];
+ if (migrate === undefined) {
+ throw new ModuleBootError(
+ `${def.manifest.name}: no context migration from v${version} to v${decl.version}`,
+ );
+ }
+ self = migrate(self);
+ version += 1;
+ }
+ if (decl.schema !== undefined && self !== null) {
+ const out = type.raw(decl.schema).onUndeclaredKey("reject")(self);
+ if (out instanceof type.errors) {
+ throw new ModuleBootError(
+ `${def.manifest.name}: parked context does not fit: ${out.summary}`,
+ );
+ }
+ }
+ return self;
+}
+
+export async function bootModules(root: ModuleDef, opts: BootModulesOptions): Promise<ModuleTree> {
+ const { nodes, tree } = flatten(root);
+ // The manifest's `children` is the declared shape; the defs are what boots. They must
+ // agree — except that a manifest listing "*" accepts modules supplied at runtime
+ // beyond the ones it names (plugin modules under the platform root).
+ for (const n of nodes) {
+ const declared = n.def.manifest.children.map((c) => (typeof c === "string" ? c : c.keyed));
+ const open = declared.includes("*");
+ const named = declared.filter((c) => c !== "*").sort();
+ const actual = n.childrenDefs.map((c) => c.manifest.name).sort();
+ const missing = named.filter((c) => !actual.includes(c));
+ const extra = actual.filter((c) => !named.includes(c));
+ if (missing.length > 0 || (!open && extra.length > 0)) {
+ throw new ModuleBootError(
+ `${n.def.manifest.name}: manifest declares children [${declared.join(", ")}] but the code supplies [${actual.join(", ")}]`,
+ );
+ }
+ }
+ const publishedIfaces = opts.published?.ifaces ?? {};
+ const { problems, provides } = checkTree(tree, opts.ifaces, publishedIfaces);
+ if (problems.length > 0) {
+ throw new ModuleBootError(
+ `module tree rejected:\n${problems.map((p) => ` - ${describeProblem(p)}`).join("\n")}`,
+ problems,
+ );
+ }
+ const byName = new Map(nodes.map((n) => [n.def.manifest.name, n]));
+ const wires = new Map<string, Record<string, { from: string; alias: string }>>();
+ for (const n of nodes)
+ wires.set(n.def.manifest.name, wiring(n.def.manifest, provides, opts.ifaces));
+
+ // Edges: a module comes after what it requires, after what contributes to it, and
+ // after its children (a parent reaches its children's apis).
+ const after = new Map<string, Set<string>>();
+ for (const n of nodes) after.set(n.def.manifest.name, new Set());
+ for (const n of nodes) {
+ const name = n.def.manifest.name;
+ for (const w of Object.values(wires.get(name)!)) {
+ if (byName.has(w.from)) after.get(name)!.add(w.from);
+ }
+ for (const slotKey of Object.keys(n.def.manifest.contributes)) {
+ const target = splitSlotKey(slotKey)!.module;
+ if (byName.has(target)) after.get(target)!.add(name);
+ }
+ for (const child of n.childrenDefs) after.get(name)!.add(child.manifest.name);
+ }
+ const order: Flat[] = [];
+ const state = new Map<string, "visiting" | "done">();
+ const visit = (name: string, stack: string[]) => {
+ const s = state.get(name);
+ if (s === "done") return;
+ if (s === "visiting") {
+ throw new ModuleBootError(`module dependency cycle: ${[...stack, name].join(" → ")}`);
+ }
+ state.set(name, "visiting");
+ for (const dep of after.get(name)!) visit(dep, [...stack, name]);
+ state.set(name, "done");
+ order.push(byName.get(name)!);
+ };
+ for (const n of nodes) visit(n.def.manifest.name, []);
+
+ const instances = new Map<string, { inst: ModuleInstance; disposers: Array<() => void> }>();
+ const created: string[] = [];
+ const apiOf = (module: string, alias: string): unknown => {
+ const inst = instances.get(module);
+ if (inst !== undefined) return inst.inst.api[alias];
+ const value = opts.published?.values[module]?.[alias];
+ if (value === undefined) throw new ModuleBootError(`no api '${alias}' on module '${module}'`);
+ return value;
+ };
+ /** Runs every disposer, newest first, through failures; the failures come back together. */
+ const drain = (disposers: Array<() => void>): unknown[] => {
+ const failures: unknown[] = [];
+ for (const dispose of disposers.reverse()) {
+ try {
+ dispose();
+ } catch (err) {
+ failures.push(err);
+ }
+ }
+ disposers.length = 0;
+ return failures;
+ };
+ const disposeAll = () => {
+ const failures: unknown[] = [];
+ try {
+ for (const name of [...created].reverse())
+ failures.push(...drain(instances.get(name)!.disposers));
+ } finally {
+ created.length = 0;
+ instances.clear();
+ }
+ if (failures.length === 1) throw failures[0];
+ if (failures.length > 1)
+ throw new AggregateError(failures, `${failures.length} disposers failed`);
+ };
+ try {
+ for (const n of order) {
+ const mf = n.def.manifest;
+ const use: Record<string, unknown> = {};
+ for (const [alias, w] of Object.entries(wires.get(mf.name)!))
+ use[alias] = apiOf(w.from, w.alias);
+ const contributions: Record<string, Contributed[]> = {};
+ for (const other of nodes) {
+ for (const [slotKey, entries] of Object.entries(other.def.manifest.contributes)) {
+ const split = splitSlotKey(slotKey)!;
+ if (split.module !== mf.name) continue;
+ const slotDecl = Object.values(provides[mf.name] ?? {})
+ .map((d) => d.slots[split.slot])
+ .find((s) => s !== undefined);
+ const list = (contributions[split.slot] ??= []);
+ const contributor = instances.get(other.def.manifest.name);
+ for (const entry of entries) {
+ const { id, ...data } = entry;
+ const item: Contributed = { id, from: other.def.manifest.name, data };
+ if (slotDecl?.code !== undefined) {
+ const code = contributor?.inst.bind?.[id];
+ if (code === undefined) {
+ throw new ModuleBootError(
+ `${other.def.manifest.name}: contribution '${id}' to '${slotKey}' declared but not bound`,
+ );
+ }
+ item.code = code;
+ }
+ list.push(item);
+ }
+ }
+ }
+ const disposers: Array<() => void> = [];
+ const ctx: ModuleCtx = {
+ use,
+ contributions,
+ resources: opts.resources,
+ effect: (dispose) => disposers.push(dispose),
+ };
+ const context = migrateContext(n.def, opts.parked?.[mf.name]);
+ // Effects registered while this module is being created are its own to release when
+ // it fails — the outer cleanup only knows the modules that made it into `instances`.
+ let inst: ModuleInstance;
+ try {
+ inst = await n.def.create(ctx, context);
+ } catch (err) {
+ drain(disposers);
+ throw err;
+ }
+ const validate = () => {
+ for (const alias of Object.keys(mf.provides)) {
+ const value = inst.api[alias];
+ if (value === null || (typeof value !== "object" && typeof value !== "function")) {
+ throw new ModuleBootError(`${mf.name}: create() returned no api for provides.${alias}`);
+ }
+ const decl = provides[mf.name]![alias]!;
+ const missing = Object.keys(decl.methods).filter(
+ (m) => typeof (value as Record<string, unknown>)[m] !== "function",
+ );
+ const absent = Object.entries(decl.fields ?? {})
+ .filter(([, expr]) => !("maybe" in expr))
+ .filter(([f]) => (value as Record<string, unknown>)[f] === undefined)
+ .map(([f]) => f);
+ if (missing.length > 0 || absent.length > 0) {
+ throw new ModuleBootError(
+ `${mf.name}: api '${alias}' does not satisfy '${decl.name}': missing [${[...missing, ...absent].join(", ")}]`,
+ );
+ }
+ }
+ };
+ try {
+ validate();
+ } catch (err) {
+ drain(disposers);
+ throw err;
+ }
+ instances.set(mf.name, { inst, disposers });
+ created.push(mf.name);
+ }
+ } catch (err) {
+ try {
+ disposeAll();
+ } catch {
+ // The original failure is what the caller needs.
+ }
+ throw err;
+ }
+ return {
+ api: <T>(module: string, alias: string) => apiOf(module, alias) as T,
+ has: (module) => instances.has(module),
+ park() {
+ const out: Record<string, Json> = {};
+ for (const [name, entry] of instances) {
+ const decl = byName.get(name)!.def.manifest.context;
+ if (decl === undefined || entry.inst.park === undefined) continue;
+ out[name] = { v: decl.version, self: entry.inst.park() };
+ }
+ return out;
+ },
+ dispose: disposeAll,
+ };
+}
diff --git a/packages/core/src/kernel/sig.ts b/packages/core/src/kernel/sig.ts
new file mode 100644
index 00000000..d8bef3b7
--- /dev/null
+++ b/packages/core/src/kernel/sig.ts
@@ -0,0 +1,243 @@
+/**
+ * Interfaces as data, at SIGNATURE level.
+ *
+ * Go's rule is the whole contract: a value satisfies an interface when every method the
+ * interface names exists on it with the same signature. Across a hot-push boundary the
+ * two sides are separate compilations, so a signature has to be something that can be
+ * serialized and compared — this module is that form, and {@link satisfies} is the
+ * comparison. The TS `interface` a module author writes is the source; a build step
+ * projects it into this shape (see scripts/gen-ifaces.mjs), so the two cannot drift.
+ *
+ * Data types are arktype definitions, compared with TS assignability rules (./data.ts);
+ * the non-data shapes (functions, promises,
+ * streams, live objects satisfying another interface, host objects compared by name)
+ * are the six other cases below.
+ */
+import type { Json } from "./json.js";
+import type { TypeTable } from "./data.js";
+import { acceptsUndefined, dataExtends } from "./data.js";
+
+/** A type, as data. */
+export type TypeExpr =
+ /** An arktype DEFINITION (string expression or object form): primitives, literals, unions, arrays, tuples, plain objects. */
+ | { data: Json }
+ /** A live object satisfying another interface — a key into the {@link IfaceTable}. */
+ | { iface: string }
+ /** A callback. */
+ | { fn: Sig }
+ | { promise: TypeExpr }
+ /** AsyncIterable<T>; an AsyncGenerator's return value rides in `returns`. */
+ | { stream: TypeExpr; returns?: TypeExpr }
+ | { void: true }
+ /** An array whose element is not data (promises, callbacks, live objects). */
+ | { array: TypeExpr }
+ /** A plain object shape with at least one non-data member, compared member by member. */
+ | { object: Record<string, TypeExpr>; optional?: readonly string[] }
+ /** `T | null | undefined` around a non-data T. */
+ | { maybe: TypeExpr }
+ /** A union with more than one non-data member (a provider, or a promise of one). */
+ | { oneOf: readonly TypeExpr[] }
+ /**
+ * A host object compared by NAME only (AbortSignal, Request…): platform types the
+ * generator meets in a .d.ts, or a package's own class written as `Opaque<"Name">`.
+ */
+ | { opaque: string };
+
+/** A method signature: positional parameters and a return type. */
+export interface Sig {
+ params: readonly TypeExpr[];
+ returns: TypeExpr;
+}
+
+/**
+ * A contribution slot: the data shape one contribution carries (an arktype expression,
+ * `id` excluded — the framework adds it) and, when the slot needs an implementation
+ * bound by id, the shape of that implementation.
+ */
+export interface SlotDecl {
+ data: Json;
+ code?: TypeExpr;
+}
+
+/**
+ * One interface. `name` is for messages and lookup; identity is the member set. `fields`
+ * are the non-method members (Go has none; TS interfaces do, and a published config
+ * object is nothing but fields) — compared by presence and type, never by value.
+ */
+export interface IfaceDecl {
+ name: string;
+ methods: Record<string, Sig>;
+ fields?: Record<string, TypeExpr>;
+ slots: Record<string, SlotDecl>;
+}
+
+/**
+ * Every interface a bundle knows, keyed `<module>#<Export>`, plus the named data types its
+ * signatures reference by `$ref` (keyed the same way). Self-contained: a reference into it
+ * never leaves the bundle. A bare interface map is accepted everywhere a table is.
+ */
+export interface IfaceTable {
+ ifaces: Record<string, IfaceDecl>;
+ types: TypeTable;
+}
+
+/** The table as functions take it: the full form, or just the interface map. */
+export type TableLike = IfaceTable | Record<string, IfaceDecl>;
+
+export function tableOf(t: TableLike | undefined): IfaceTable {
+ if (t === undefined) return { ifaces: {}, types: {} };
+ if ("ifaces" in t && "types" in t && typeof t.ifaces === "object" && !("methods" in t.ifaces)) {
+ return t as IfaceTable;
+ }
+ return { ifaces: t as Record<string, IfaceDecl>, types: {} };
+}
+
+export interface Mismatch {
+ /** The method or field. */
+ method: string;
+ kind: "missing" | "signature" | "field";
+ why: string;
+}
+
+/** offered satisfies required ⇔ every required method exists on offered with an assignable signature. */
+export function satisfies(
+ offered: IfaceDecl,
+ required: IfaceDecl,
+ table: TableLike = {},
+ seen: Set<string> = new Set(),
+): Mismatch[] {
+ const out: Mismatch[] = [];
+ for (const [method, want] of Object.entries(required.methods)) {
+ const have = offered.methods[method];
+ if (have === undefined) {
+ out.push({ method, kind: "missing", why: `'${offered.name}' has no method '${method}'` });
+ continue;
+ }
+ for (const why of assignable(have, want, table, seen)) {
+ out.push({ method, kind: "signature", why });
+ }
+ }
+ for (const [field, want] of Object.entries(required.fields ?? {})) {
+ const have = offered.fields?.[field];
+ if (have === undefined) {
+ if ("maybe" in want) continue; // an optional field the offer does not declare at all
+ out.push({
+ method: field,
+ kind: "missing",
+ why: `'${offered.name}' has no field '${field}'`,
+ });
+ continue;
+ }
+ if (!extendsExpr(have, want, table, seen)) {
+ out.push({
+ method: field,
+ kind: "field",
+ why: `field is ${show(have)}, caller expects ${show(want)}`,
+ });
+ }
+ }
+ return out;
+}
+
+/**
+ * Function subtyping: `have` can stand in for `want` when it takes no more parameters
+ * than a caller of `want` passes, each of its parameters accepts what the caller passes
+ * (contravariant), and what it returns is what the caller expects (covariant).
+ */
+export function assignable(
+ have: Sig,
+ want: Sig,
+ table: TableLike = {},
+ seen: Set<string> = new Set(),
+): string[] {
+ const why: string[] = [];
+ if (have.params.length > want.params.length) {
+ // Extra parameters are fine only when optional — encoded as `T | undefined`.
+ for (let i = want.params.length; i < have.params.length; i += 1) {
+ const p = have.params[i]!;
+ if (!("maybe" in p) && (!("data" in p) || !acceptsUndefined(p.data, tableOf(table).types))) {
+ why.push(`takes ${have.params.length} params, caller passes ${want.params.length}`);
+ break;
+ }
+ }
+ }
+ have.params.forEach((p, i) => {
+ const passed = want.params[i];
+ if (passed === undefined) return;
+ if (!extendsExpr(passed, p, table, seen)) {
+ why.push(`param ${i}: caller passes ${show(passed)}, impl wants ${show(p)}`);
+ }
+ });
+ if (!extendsExpr(have.returns, want.returns, table, seen)) {
+ why.push(`returns ${show(have.returns)}, caller expects ${show(want.returns)}`);
+ }
+ return why;
+}
+
+/** a ⊆ b over the seven shapes; data goes to arktype, interfaces recurse through the table. */
+export function extendsExpr(
+ a: TypeExpr,
+ b: TypeExpr,
+ table: TableLike = {},
+ seen: Set<string> = new Set(),
+): boolean {
+ if ("void" in b) return true;
+ if ("data" in a && "data" in b) return dataExtends(a.data, b.data, tableOf(table).types);
+ if ("opaque" in a && "opaque" in b) return a.opaque === b.opaque;
+ if ("iface" in a && "iface" in b) {
+ if (a.iface === b.iface) return true;
+ const key = `${a.iface}<:${b.iface}`;
+ if (seen.has(key)) return true; // Coinductive: assume the pair while checking it.
+ const offered = tableOf(table).ifaces[a.iface];
+ const required = tableOf(table).ifaces[b.iface];
+ if (offered === undefined || required === undefined) return false;
+ // The assumption lives only inside this comparison (a copy, as data.ts does): a pair
+ // that turns out not to hold must not be taken as holding by a later branch — another
+ // union member, another parameter — that meets it again.
+ return satisfies(offered, required, table, new Set(seen).add(key)).length === 0;
+ }
+ if ("maybe" in b) return extendsExpr("maybe" in a ? a.maybe : a, b.maybe, table, seen);
+ if ("maybe" in a) return false;
+ if ("oneOf" in a) return a.oneOf.every((m) => extendsExpr(m, b, table, seen));
+ if ("oneOf" in b) return b.oneOf.some((m) => extendsExpr(a, m, table, seen));
+ if ("array" in a && "array" in b) return extendsExpr(a.array, b.array, table, seen);
+ if ("object" in a && "object" in b) {
+ for (const [key, want] of Object.entries(b.object)) {
+ const have = a.object[key];
+ const optionalInB = b.optional?.includes(key) ?? false;
+ if (have === undefined) {
+ if (optionalInB) continue;
+ return false;
+ }
+ if ((a.optional?.includes(key) ?? false) && !optionalInB) return false;
+ if (!extendsExpr(have, want, table, seen)) return false;
+ }
+ return true;
+ }
+ if ("fn" in a && "fn" in b) return assignable(a.fn, b.fn, table, seen).length === 0;
+ if ("promise" in a && "promise" in b) return extendsExpr(a.promise, b.promise, table, seen);
+ if ("stream" in a && "stream" in b) {
+ if (!extendsExpr(a.stream, b.stream, table, seen)) return false;
+ if (b.returns === undefined) return true;
+ return a.returns !== undefined && extendsExpr(a.returns, b.returns, table, seen);
+ }
+ return false;
+}
+
+/** A short rendering for messages. */
+export function show(expr: TypeExpr): string {
+ if ("data" in expr) return typeof expr.data === "string" ? expr.data : JSON.stringify(expr.data);
+ if ("iface" in expr) return expr.iface;
+ if ("opaque" in expr) return `opaque<${expr.opaque}>`;
+ if ("void" in expr) return "void";
+ if ("promise" in expr) return `Promise<${show(expr.promise)}>`;
+ if ("array" in expr) return `${show(expr.array)}[]`;
+ if ("object" in expr)
+ return `{ ${Object.entries(expr.object)
+ .map(([k, v]) => `${k}${expr.optional?.includes(k) ? "?" : ""}: ${show(v)}`)
+ .join(", ")} }`;
+ if ("maybe" in expr) return `${show(expr.maybe)} | null`;
+ if ("oneOf" in expr) return expr.oneOf.map(show).join(" | ");
+ if ("stream" in expr) return `AsyncIterable<${show(expr.stream)}>`;
+ return `(${expr.fn.params.map(show).join(", ")}) => ${show(expr.fn.returns)}`;
+}
diff --git a/packages/core/test/agent-assembly.test.ts b/packages/core/test/agent-assembly.test.ts
new file mode 100644
index 00000000..31903ba8
--- /dev/null
+++ b/packages/core/test/agent-assembly.test.ts
@@ -0,0 +1,34 @@
+/**
+ * AgentAssembly: what the hosting process adds to every Session — prompt sections
+ * appended under their own headings.
+ */
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { createAgent } from "../src/agent.js";
+
+const roots: string[] = [];
+afterEach(async () => {
+ await Promise.all(roots.splice(0).map((r) => fs.rm(r, { recursive: true, force: true })));
+});
+
+describe("AgentAssembly", () => {
+ it("appends prompt sections under their headings, after the Agent's own prompt", async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-assembly-"));
+ roots.push(root);
+ const agent = await createAgent({
+ root,
+ assembly: { promptSections: () => [{ title: "Host", text: "You run inside a test." }] },
+ });
+ const session = await agent.createSession({
+ modelId: agent.projectConfig.default_model!.model_id,
+ provider: agent.projectConfig.default_model!.provider,
+ apiKey: "test-key",
+ });
+ const prompt = (session.metaMessage.payload as { system_prompt: string }).system_prompt;
+ expect(prompt.endsWith("# Host\nYou run inside a test.")).toBe(true);
+ expect(prompt.startsWith(agent.state.systemConfig.system_prompt.slice(0, 20))).toBe(true);
+ session.dispose();
+ });
+});
diff --git a/packages/core/test/kernel-data.test.ts b/packages/core/test/kernel-data.test.ts
new file mode 100644
index 00000000..827f0ed8
--- /dev/null
+++ b/packages/core/test/kernel-data.test.ts
@@ -0,0 +1,123 @@
+/** TS assignability over data definitions — the rules arktype's intersection-based `extends` does not give. */
+import { describe, expect, it } from "vitest";
+import { dataExtends } from "../src/kernel/index.js";
+import type { TypeTable } from "../src/kernel/index.js";
+
+describe("dataExtends", () => {
+ it("leaves go to arktype: literals fit their primitive, not the reverse", () => {
+ expect(dataExtends("'a'", "string")).toBe(true);
+ expect(dataExtends("string", "'a'")).toBe(false);
+ expect(dataExtends("'a'|'b'", "string")).toBe(true);
+ expect(dataExtends("'a'", "'a'|'b'")).toBe(true);
+ expect(dataExtends("'c'", "'a'|'b'")).toBe(false);
+ });
+
+ it("objects: extra keys are fine, optional keys may be absent, required keys may not", () => {
+ expect(dataExtends({ a: "string" }, { a: "string", "meta?": { "[string]": "unknown" } })).toBe(
+ true,
+ );
+ expect(dataExtends({ a: "string", b: "number" }, { a: "string" })).toBe(true);
+ expect(dataExtends({ a: "string" }, { a: "string", b: "number" })).toBe(false);
+ expect(dataExtends({ "a?": "string" }, { a: "string" })).toBe(false);
+ expect(dataExtends({ a: "'x'" }, { a: "string" })).toBe(true);
+ expect(dataExtends({ a: "string" }, { a: "'x'" })).toBe(false);
+ });
+
+ it("index signatures bound the keys the other side does not name", () => {
+ expect(dataExtends({ a: "number" }, { "[string]": "number" })).toBe(true);
+ expect(dataExtends({ a: "string" }, { "[string]": "number" })).toBe(false);
+ expect(dataExtends({ "[string]": "number" }, { a: "number" })).toBe(true);
+ });
+
+ it("an intersection on the left is one shape — its halves fit together, not alone", () => {
+ expect(dataExtends([{ a: "string" }, "&", { b: "string" }], { a: "string", b: "string" })).toBe(
+ true,
+ );
+ expect(dataExtends([{ a: "string" }, "&", { b: "string" }], { a: "string", c: "string" })).toBe(
+ false,
+ );
+ // A key both halves carry keeps both constraints.
+ expect(dataExtends([{ a: "string" }, "&", { a: "'x'" }], { a: "'x'" })).toBe(true);
+ // Through references too.
+ const types: TypeTable = { "m#Role": { role: "'admin'|'member'" } };
+ expect(
+ dataExtends(
+ [{ id: "string" }, "&", { $ref: "m#Role" }],
+ { id: "string", role: "string" },
+ types,
+ ),
+ ).toBe(true);
+ // On the right, both halves must hold.
+ expect(dataExtends({ a: "string", b: "string" }, [{ a: "string" }, "&", { b: "string" }])).toBe(
+ true,
+ );
+ expect(dataExtends({ a: "string" }, [{ a: "string" }, "&", { b: "string" }])).toBe(false);
+ });
+
+ it("arrays and tuples, in both spellings", () => {
+ expect(dataExtends("string[]", "unknown[]")).toBe(true);
+ expect(dataExtends([{ a: "'x'" }, "[]"], [{ a: "string" }, "[]"])).toBe(true);
+ expect(dataExtends([{ a: "string" }, "[]"], [{ a: "'x'" }, "[]"])).toBe(false);
+ expect(dataExtends(["string", "number"], ["string", "number"])).toBe(true);
+ expect(dataExtends(["string"], ["string", "number"])).toBe(false);
+ expect(dataExtends(["string", "'a'"], "string[]")).toBe(true);
+ });
+
+ it("unions: every member of the source, any member of the target", () => {
+ expect(
+ dataExtends({ type: "'text'", text: "string" }, [
+ { type: "'text'", text: "string" },
+ "|",
+ { type: "'image'", url: "string" },
+ ]),
+ ).toBe(true);
+ expect(
+ dataExtends(
+ [{ type: "'text'" }, "|", { type: "'audio'" }],
+ [{ type: "'text'" }, "|", { type: "'image'" }],
+ ),
+ ).toBe(false);
+ expect(dataExtends("undefined", [{ a: "string" }, "|", "undefined"])).toBe(true);
+ expect(dataExtends("string|undefined", "string")).toBe(false);
+ });
+
+ it("unknown takes anything; never fits anything", () => {
+ expect(dataExtends({ deep: [{ x: "string" }, "[]"] }, "unknown")).toBe(true);
+ expect(dataExtends("never", { a: "string" })).toBe(true);
+ });
+});
+
+describe("named types and $ref", () => {
+ const types: TypeTable = {
+ "core#OmniMessage": { role: "'user'|'assistant'", "parts?": [{ $ref: "core#Part" }, "[]"] },
+ "core#Part": [{ type: "'text'", text: "string" }, "|", { type: "'image'", url: "string" }],
+ "core#Json": [
+ "string|number|boolean|null",
+ "|",
+ [[{ $ref: "core#Json" }, "[]"], "|", { "[string]": { $ref: "core#Json" } }],
+ ],
+ };
+
+ it("resolves a reference on either side", () => {
+ expect(dataExtends({ $ref: "core#Part" }, "unknown", types)).toBe(true);
+ expect(dataExtends({ type: "'text'", text: "string" }, { $ref: "core#Part" }, types)).toBe(
+ true,
+ );
+ expect(dataExtends({ $ref: "core#Part" }, { type: "'text'", text: "string" }, types)).toBe(
+ false,
+ );
+ expect(dataExtends({ role: "'user'" }, { $ref: "core#OmniMessage" }, types)).toBe(true);
+ });
+
+ it("a recursive type compares finitely, by coinduction", () => {
+ expect(dataExtends({ $ref: "core#Json" }, { $ref: "core#Json" }, types)).toBe(true);
+ expect(dataExtends(["string", "[]"], { $ref: "core#Json" }, types)).toBe(true);
+ expect(dataExtends({ a: { b: ["number", "[]"] } }, { $ref: "core#Json" }, types)).toBe(true);
+ expect(dataExtends({ a: "Date" }, { $ref: "core#Json" }, types)).toBe(false);
+ });
+
+ it("a dangling reference fits nothing and takes nothing", () => {
+ expect(dataExtends({ $ref: "nope" }, "unknown", {})).toBe(true); // unknown takes anything
+ expect(dataExtends("string", { $ref: "nope" }, {})).toBe(false);
+ });
+});
diff --git a/packages/core/test/kernel-modules.test.ts b/packages/core/test/kernel-modules.test.ts
new file mode 100644
index 00000000..6cd6c6ee
--- /dev/null
+++ b/packages/core/test/kernel-modules.test.ts
@@ -0,0 +1,800 @@
+/**
+ * The module tree: signature-level interface satisfaction, the manifest check that runs
+ * before any code, and boot order from requires + contributions.
+ */
+import { describe, expect, it } from "vitest";
+import type { IfaceDecl, Manifest, Resources } from "../src/kernel/index.js";
+type IfaceTable = Record<string, IfaceDecl>;
+import {
+ assignable,
+ bootModules,
+ checkTree,
+ Component,
+ defineModule,
+ extendsExpr,
+ Interface,
+ Module,
+ ModuleBootError,
+ moduleDefOf,
+ parseManifest,
+ Provide,
+ satisfies,
+ Use,
+ wire,
+} from "../src/kernel/index.js";
+
+const resources: Resources = {
+ register: () => () => {},
+ claim: () => undefined,
+};
+
+const str = { data: "string" } as const;
+const num = { data: "number" } as const;
+
+const Sessions: IfaceDecl = {
+ name: "Sessions",
+ methods: {
+ startTask: {
+ params: [
+ str,
+ { data: "string[]" },
+ { data: [{ "queueIfBusy?": "boolean" }, "|", "undefined"] },
+ ],
+ returns: { promise: { data: { sessionId: "string", queued: "boolean" } } },
+ },
+ statusOf: { params: [str], returns: { data: "'idle'|'running'" } },
+ subscribe: {
+ params: [str, { fn: { params: [{ data: "string" }], returns: { void: true } } }],
+ returns: { fn: { params: [], returns: { void: true } } },
+ },
+ },
+ slots: {},
+};
+
+/** What the scheduler needs: two methods, narrower signatures. */
+const Runner: IfaceDecl = {
+ name: "ScheduleTaskRunner",
+ methods: {
+ statusOf: { params: [str], returns: { data: "string" } },
+ startTask: {
+ params: [str, { data: "string[]" }],
+ returns: { promise: { data: { sessionId: "string" } } },
+ },
+ },
+ slots: {},
+};
+
+describe("satisfies", () => {
+ it("a wider interface satisfies a narrower one it structurally covers", () => {
+ expect(satisfies(Sessions, Runner)).toEqual([]);
+ });
+
+ it("names the method and the reason when it does not", () => {
+ const wrong: IfaceDecl = {
+ ...Runner,
+ methods: { ...Runner.methods, statusOf: { params: [num], returns: { data: "string" } } },
+ };
+ const gaps = satisfies(Sessions, wrong);
+ expect(gaps).toHaveLength(1);
+ expect(gaps[0]).toMatchObject({ method: "statusOf", kind: "signature" });
+ expect(gaps[0]!.why).toContain("param 0");
+ });
+
+ it("a missing method is reported as missing, not as a signature mismatch", () => {
+ const more: IfaceDecl = {
+ ...Runner,
+ methods: { ...Runner.methods, abort: { params: [str], returns: { data: "boolean" } } },
+ };
+ expect(satisfies(Runner, more)).toEqual([
+ { method: "abort", kind: "missing", why: expect.stringContaining("no method 'abort'") },
+ ]);
+ });
+
+ it("parameters are contravariant and returns covariant", () => {
+ // impl accepts string|number where the caller passes string: fine.
+ expect(
+ assignable(
+ { params: [{ data: "string|number" }], returns: { data: "'a'" } },
+ { params: [str], returns: { data: "string" } },
+ ),
+ ).toEqual([]);
+ // impl returns string where the caller expects 'a': not fine.
+ expect(
+ assignable(
+ { params: [str], returns: { data: "string" } },
+ { params: [str], returns: { data: "'a'" } },
+ ),
+ ).toHaveLength(1);
+ });
+
+ it("an extra parameter is allowed only when optional", () => {
+ const base = { params: [str], returns: { void: true as const } };
+ expect(
+ assignable({ params: [str, { data: "number|undefined" }], returns: { void: true } }, base),
+ ).toEqual([]);
+ expect(assignable({ params: [str, num], returns: { void: true } }, base)).toHaveLength(1);
+ });
+
+ it("interface-typed parameters recurse through the table, coinductively", () => {
+ const table: IfaceTable = {
+ "a#Node": {
+ name: "Node",
+ methods: { next: { params: [], returns: { iface: "a#Node" } } },
+ slots: {},
+ },
+ "b#Node": {
+ name: "Node",
+ methods: { next: { params: [], returns: { iface: "b#Node" } } },
+ slots: {},
+ },
+ };
+ expect(satisfies(table["a#Node"]!, table["b#Node"]!, table)).toEqual([]);
+ });
+
+ it("opaque host objects compare by name only", () => {
+ const sig = (name: string) => ({
+ params: [{ opaque: name }],
+ returns: { void: true as const },
+ });
+ expect(assignable(sig("AbortSignal"), sig("AbortSignal"))).toEqual([]);
+ expect(assignable(sig("AbortSignal"), sig("Request"))).toHaveLength(1);
+ });
+});
+
+const table: IfaceTable = {
+ "sessions#Sessions": Sessions,
+ "scheduler#ScheduleTaskRunner": Runner,
+ "http#Http": {
+ name: "Http",
+ methods: {
+ handle: { params: [{ opaque: "Request" }], returns: { promise: { opaque: "Response" } } },
+ },
+ slots: {
+ routes: { data: { prefix: "string", auth: "'admin'|'user'" }, code: { opaque: "Handler" } },
+ },
+ },
+};
+
+const manifest = (m: Partial<Manifest> & { name: string }): Manifest =>
+ parseManifest({ requires: {}, provides: {}, contributes: {}, children: [], ...m });
+
+const platform = manifest({ name: "platform", children: ["http", "sessions", "scheduler"] });
+const http = manifest({ name: "http", provides: { http: "Http" } });
+const sessions = manifest({
+ name: "sessions",
+ provides: { sessions: "Sessions" },
+ contributes: {
+ "http.routes": [{ id: "sessions.routes", prefix: "/api/sessions", auth: "user" }],
+ },
+});
+const scheduler = manifest({
+ name: "scheduler",
+ requires: { runner: { iface: "ScheduleTaskRunner", from: "sessions" } },
+});
+
+const tree = (...children: Manifest[]) => ({
+ manifest: platform,
+ children: children.map((manifest) => ({ manifest, children: [] })),
+});
+
+describe("extendsExpr", () => {
+ it("a pair that fails is not remembered as holding by the next branch that meets it", () => {
+ const t: IfaceTable = {
+ "a#A": { name: "A", methods: { x: { params: [], returns: str } }, slots: {} },
+ "a#B": { name: "B", methods: { x: { params: [], returns: num } }, slots: {} },
+ };
+ const seen = new Set<string>();
+ expect(extendsExpr({ iface: "a#A" }, { iface: "a#B" }, t, seen)).toBe(false);
+ expect(seen.size).toBe(0);
+ // The first member fails; the second is the same pair and must fail the same way.
+ expect(extendsExpr({ iface: "a#A" }, { oneOf: [{ iface: "a#B" }, { iface: "a#B" }] }, t)).toBe(
+ false,
+ );
+ });
+});
+
+describe("checkTree", () => {
+ it("passes a consistent tree", () => {
+ expect(checkTree(tree(http, sessions, scheduler), table).problems).toEqual([]);
+ });
+
+ it("reports a requirement no visible module satisfies, by method", () => {
+ const wrong = {
+ ...table,
+ "scheduler#ScheduleTaskRunner": {
+ ...Runner,
+ methods: { ...Runner.methods, abort: Runner.methods.statusOf! },
+ },
+ };
+ const { problems } = checkTree(tree(http, sessions, scheduler), wrong);
+ expect(problems).toEqual([
+ expect.objectContaining({
+ kind: "mismatch",
+ alias: "runner",
+ from: "sessions",
+ method: "abort",
+ }),
+ ]);
+ });
+
+ it("resolves an unnamed `from` when exactly one visible provider satisfies", () => {
+ const loose = manifest({
+ name: "scheduler",
+ requires: { runner: { iface: "ScheduleTaskRunner" } },
+ });
+ expect(checkTree(tree(http, sessions, loose), table).problems).toEqual([]);
+ });
+
+ it("a contribution to a slot nobody declares, or one that fails the slot schema, is a problem", () => {
+ const bad = manifest({
+ name: "sessions",
+ provides: { sessions: "Sessions" },
+ contributes: {
+ "http.nope": [{ id: "x" }],
+ "http.routes": [{ id: "sessions.routes", prefix: "/api", auth: "root" }],
+ },
+ });
+ const { problems } = checkTree(tree(http, bad, scheduler), table);
+ expect(problems.map((p) => p.kind).sort()).toEqual(["bad-contribution", "no-such-slot"]);
+ });
+
+ it("visibility is lexical: a module cannot wire to another subtree's child", () => {
+ const inner = manifest({ name: "inner", provides: { sessions: "Sessions" } });
+ const outer = manifest({ name: "outer", children: ["inner"] });
+ const root = {
+ manifest: platform,
+ children: [
+ { manifest: outer, children: [{ manifest: inner, children: [] }] },
+ {
+ manifest: manifest({
+ name: "scheduler",
+ requires: { runner: { iface: "ScheduleTaskRunner", from: "inner" } },
+ }),
+ children: [],
+ },
+ ],
+ };
+ const t = { ...table, "inner#Sessions": Sessions };
+ expect(checkTree(root, t).problems).toEqual([
+ expect.objectContaining({ kind: "unresolved", why: "not visible from here" }),
+ ]);
+ });
+ it("a module cannot require itself, nor an ancestor — created after its children, its api is not there yet", () => {
+ const selfish = manifest({
+ name: "scheduler",
+ requires: { runner: { iface: "ScheduleTaskRunner", from: "scheduler" } },
+ });
+ expect(checkTree(tree(http, sessions, selfish), table).problems).toEqual([
+ expect.objectContaining({ kind: "unresolved", from: "scheduler", why: "itself" }),
+ ]);
+
+ const byName = manifest({
+ name: "inner",
+ requires: { sessions: { iface: "Sessions", from: "outer" } },
+ });
+ const unnamed = manifest({ name: "inner", requires: { sessions: { iface: "Sessions" } } });
+ const outerOf = (inner: Manifest) => ({
+ manifest: platform,
+ children: [
+ {
+ manifest: manifest({
+ name: "outer",
+ provides: { sessions: "Sessions" },
+ children: ["inner"],
+ }),
+ children: [{ manifest: inner, children: [] }],
+ },
+ ],
+ });
+ const t = { ...table, "outer#Sessions": Sessions, "inner#Sessions": Sessions };
+ expect(checkTree(outerOf(byName), t).problems).toEqual([
+ expect.objectContaining({
+ kind: "unresolved",
+ from: "outer",
+ why: expect.stringContaining("an ancestor"),
+ }),
+ ]);
+ expect(checkTree(outerOf(unnamed), t).problems).toEqual([
+ expect.objectContaining({ kind: "unresolved", from: "" }),
+ ]);
+ });
+
+ it("a contribution reaches a parent or a sibling, not another subtree's child", () => {
+ const parentSlot = {
+ manifest: platform,
+ children: [
+ {
+ manifest: manifest({ name: "http", provides: { http: "Http" }, children: ["sessions"] }),
+ children: [{ manifest: sessions, children: [] }],
+ },
+ ],
+ };
+ expect(checkTree(parentSlot, table).problems).toEqual([]);
+
+ const hidden = {
+ manifest: platform,
+ children: [
+ {
+ manifest: manifest({ name: "wrapper", children: ["http"] }),
+ children: [{ manifest: http, children: [] }],
+ },
+ { manifest: sessions, children: [] },
+ ],
+ };
+ expect(checkTree(hidden, table).problems).toEqual([
+ expect.objectContaining({ kind: "no-such-slot", slotKey: "http.routes" }),
+ ]);
+ });
+});
+
+describe("bootModules", () => {
+ const sessionsApi = {
+ startTask: async () => ({ sessionId: "s", queued: false }),
+ statusOf: () => "idle",
+ subscribe: () => () => {},
+ };
+
+ it("boots in dependency order and hands contributions with their code half", async () => {
+ const order: string[] = [];
+ const root = defineModule(platform, {
+ create: () => ({ api: {} }),
+ children: [
+ defineModule(scheduler, {
+ create(ctx) {
+ order.push("scheduler");
+ expect(typeof (ctx.use.runner as { statusOf: unknown }).statusOf).toBe("function");
+ return { api: {} };
+ },
+ }),
+ defineModule(http, {
+ create(ctx) {
+ order.push("http");
+ expect(ctx.contributions.routes).toEqual([
+ {
+ id: "sessions.routes",
+ from: "sessions",
+ data: { prefix: "/api/sessions", auth: "user" },
+ code: "HANDLER",
+ },
+ ]);
+ return { api: { http: { handle: async () => null } } };
+ },
+ }),
+ defineModule(sessions, {
+ create() {
+ order.push("sessions");
+ return { api: { sessions: sessionsApi }, bind: { "sessions.routes": "HANDLER" } };
+ },
+ }),
+ ],
+ });
+ const booted = await bootModules(root, { ifaces: table, resources });
+ expect(order).toEqual(["sessions", "scheduler", "http"]);
+ expect(booted.api("sessions", "sessions")).toBe(sessionsApi);
+ booted.dispose();
+ });
+
+ it("refuses a declared-but-unbound contribution", async () => {
+ const root = defineModule(platform, {
+ create: () => ({ api: {} }),
+ children: [
+ defineModule(http, { create: () => ({ api: { http: { handle: async () => null } } }) }),
+ defineModule(sessions, { create: () => ({ api: { sessions: sessionsApi } }) }),
+ defineModule(scheduler, { create: () => ({ api: {} }) }),
+ ],
+ });
+ await expect(bootModules(root, { ifaces: table, resources })).rejects.toThrow(
+ /declared but not bound/,
+ );
+ });
+
+ it("refuses an api that lacks a method the interface names", async () => {
+ const bare = manifest({ name: "sessions", provides: { sessions: "Sessions" } });
+ const root = defineModule(manifest({ name: "platform", children: ["sessions"] }), {
+ create: () => ({ api: {} }),
+ children: [
+ defineModule(bare, { create: () => ({ api: { sessions: { statusOf: () => "idle" } } }) }),
+ ],
+ });
+ const t = { ...table };
+ await expect(bootModules(root, { ifaces: t, resources })).rejects.toThrow(
+ /missing \[startTask, subscribe\]/,
+ );
+ });
+
+ it("names the modules in a dependency cycle", async () => {
+ const a = manifest({
+ name: "a",
+ provides: { s: "Sessions" },
+ requires: { r: { iface: "ScheduleTaskRunner", from: "b" } },
+ });
+ const b = manifest({
+ name: "b",
+ provides: { s: "Sessions" },
+ requires: { r: { iface: "ScheduleTaskRunner", from: "a" } },
+ });
+ const t: IfaceTable = {
+ "a#Sessions": Sessions,
+ "b#Sessions": Sessions,
+ "a#ScheduleTaskRunner": Runner,
+ "b#ScheduleTaskRunner": Runner,
+ };
+ const root = defineModule(manifest({ name: "platform", children: ["a", "b"] }), {
+ create: () => ({ api: {} }),
+ children: [
+ defineModule(a, { create: () => ({ api: { s: sessionsApi } }) }),
+ defineModule(b, { create: () => ({ api: { s: sessionsApi } }) }),
+ ],
+ });
+ await expect(bootModules(root, { ifaces: t, resources })).rejects.toThrow(
+ /cycle: .*a → b → a|cycle: .*b → a → b/,
+ );
+ });
+
+ it("parks per module, versioned, and migrates on the way back in", async () => {
+ const mf = manifest({ name: "counter", context: { version: 2, schema: { n: "number" } } });
+ const make = (seen: { context: unknown }) =>
+ defineModule(manifest({ name: "platform", children: ["counter"] }), {
+ create: () => ({ api: {} }),
+ children: [
+ defineModule(mf, {
+ migrations: { 1: (old) => ({ n: typeof old === "number" ? old : 0 }) },
+ create(_ctx, context) {
+ seen.context = context;
+ return { api: {}, park: () => ({ n: 7 }) };
+ },
+ }),
+ ],
+ });
+ const seen = { context: null as unknown };
+ const first = await bootModules(make(seen), { ifaces: {}, resources });
+ expect(seen.context).toBeNull();
+ const parked = first.park();
+ expect(parked).toEqual({ counter: { v: 2, self: { n: 7 } } });
+ const second = await bootModules(make(seen), { ifaces: {}, resources, parked });
+ expect(seen.context).toEqual({ n: 7 });
+ second.dispose();
+ // A v1 document (a bare number) goes through the migration.
+ await bootModules(make(seen), {
+ ifaces: {},
+ resources,
+ parked: { counter: { v: 1, self: 3 } },
+ });
+ expect(seen.context).toEqual({ n: 3 });
+ await expect(
+ bootModules(make(seen), {
+ ifaces: {},
+ resources,
+ parked: { counter: { v: 2, self: { n: "x" } } },
+ }),
+ ).rejects.toThrow(ModuleBootError);
+ });
+ it("dispose runs every effect even when one throws, and reports the failures together", async () => {
+ const released: string[] = [];
+ const root = defineModule(platform, {
+ create: () => ({ api: {} }),
+ children: [
+ defineModule(http, {
+ create(ctx) {
+ ctx.effect(() => {
+ released.push("http");
+ });
+ return { api: { http: { handle: async () => null } } };
+ },
+ }),
+ defineModule(sessions, {
+ create(ctx) {
+ ctx.effect(() => {
+ throw new Error("sessions boom");
+ });
+ ctx.effect(() => {
+ released.push("sessions");
+ });
+ return { api: { sessions: sessionsApi }, bind: { "sessions.routes": "HANDLER" } };
+ },
+ }),
+ defineModule(scheduler, {
+ create(ctx) {
+ ctx.effect(() => {
+ released.push("scheduler");
+ });
+ return { api: {} };
+ },
+ }),
+ ],
+ });
+ const booted = await bootModules(root, { ifaces: table, resources });
+ expect(() => booted.dispose()).toThrow("sessions boom");
+ expect(released.sort()).toEqual(["http", "scheduler", "sessions"]);
+ expect(booted.has("sessions")).toBe(false);
+ });
+
+ it("a module that fails to create, or creates an api that does not satisfy, releases its own effects", async () => {
+ const released: string[] = [];
+ const failing = (body: () => never | { api: Record<string, unknown> }) =>
+ defineModule(platform, {
+ create: () => ({ api: {} }),
+ children: [
+ defineModule(http, { create: () => ({ api: { http: { handle: async () => null } } }) }),
+ defineModule(sessions, {
+ create(ctx) {
+ ctx.effect(() => {
+ released.push("sessions");
+ });
+ return body();
+ },
+ }),
+ defineModule(scheduler, { create: () => ({ api: {} }) }),
+ ],
+ });
+ await expect(
+ bootModules(
+ failing(() => {
+ throw new Error("no sessions today");
+ }),
+ { ifaces: table, resources },
+ ),
+ ).rejects.toThrow("no sessions today");
+ expect(released).toEqual(["sessions"]);
+
+ released.length = 0;
+ await expect(
+ bootModules(
+ failing(() => ({ api: { sessions: {} } })),
+ { ifaces: table, resources },
+ ),
+ ).rejects.toThrow("does not satisfy");
+ expect(released).toEqual(["sessions"]);
+ });
+});
+
+describe("Interface, in both spellings", () => {
+ // The interface declares its own members.
+ @Interface()
+ abstract class Clock {
+ abstract now(): number;
+ }
+ // The interface IS an existing type.
+ type StoreShape = { get(key: string): string | undefined };
+ abstract class Store extends Interface<StoreShape>() {}
+
+ it("is a runtime handle either way, so a manifest can name it by reference", () => {
+ expect(typeof Clock).toBe("function");
+ expect(Clock.name).toBe("Clock");
+ expect(typeof Store).toBe("function");
+ });
+
+ it("types a consumer the same either way", () => {
+ class RealClock {
+ now() {
+ return 7;
+ }
+ }
+ const satisfiesClock: RealClock extends Clock ? true : never = true;
+ const store: Store = { get: (k) => (k === "a" ? "1" : undefined) };
+ expect(satisfiesClock).toBe(true);
+ expect(store.get("a")).toBe("1");
+ const clock: Clock = new RealClock();
+ expect(clock.now()).toBe(7);
+ });
+});
+
+describe("class form: @Module / @Use / @Provide / @Bind", () => {
+ abstract class Sessions extends Interface<{
+ startTask(id: string): Promise<{ sessionId: string }>;
+ statusOf(id: string): string;
+ }>() {}
+ abstract class Runner extends Interface<{ statusOf(id: string): string }>() {}
+ const t: IfaceTable = {
+ "SessionsModule#Sessions": {
+ name: "Sessions",
+ methods: {
+ startTask: { params: [str], returns: { promise: { data: { sessionId: "string" } } } },
+ statusOf: { params: [str], returns: { data: "string" } },
+ },
+ slots: {},
+ },
+ "SchedulerModule#Runner": {
+ name: "Runner",
+ methods: { statusOf: { params: [str], returns: { data: "string" } } },
+ slots: {},
+ },
+ };
+ /** What the generator would have extracted from the classes below. */
+ const manifests = {
+ SessionsModule: parseManifest({
+ name: "SessionsModule",
+ requires: {},
+ provides: { sessions: "Sessions" },
+ contributes: {},
+ children: [],
+ }),
+ SchedulerModule: parseManifest({
+ name: "SchedulerModule",
+ requires: { runner: { iface: "Runner", from: "SessionsModule" } },
+ provides: {},
+ contributes: {},
+ children: [],
+ }),
+ PlatformModule: parseManifest({
+ name: "PlatformModule",
+ requires: {},
+ provides: {},
+ contributes: {},
+ children: ["SessionsModule", "SchedulerModule"],
+ }),
+ };
+ @Module()
+ class SessionsModule {
+ @Provide() sessions!: Sessions;
+ setup() {
+ this.sessions = {
+ startTask: async (id: string) => ({ sessionId: id }),
+ statusOf: () => "idle",
+ };
+ }
+ }
+ const seen: string[] = [];
+ @Module()
+ class SchedulerModule {
+ @Use(SessionsModule) readonly runner!: Runner;
+ setup() {
+ seen.push(this.runner.statusOf("s")); // typed by the field: Runner
+ }
+ }
+ @Module({ children: [SessionsModule, SchedulerModule] })
+ class PlatformModule {
+ setup() {}
+ }
+
+ it("boots a class tree against the generated manifests, injecting @Use and reading @Provide", async () => {
+ const def = moduleDefOf(PlatformModule, { manifests });
+ expect(def.manifest.children).toEqual(["SessionsModule", "SchedulerModule"]);
+ const tree = await bootModules(def, { ifaces: t, resources });
+ expect(seen).toEqual(["idle"]);
+ expect(typeof tree.api<Sessions>("SessionsModule", "sessions").startTask).toBe("function");
+ tree.dispose();
+ });
+
+ it("a @Use field the table does not know is a stale-table error, named", () => {
+ @Module()
+ class Drifted {
+ @Use(SessionsModule) readonly runner!: Runner;
+ @Use(SessionsModule) readonly extra!: Sessions;
+ setup() {}
+ }
+ expect(() =>
+ moduleDefOf(Drifted, { manifests: { ...manifests, Drifted: manifests.SchedulerModule! } }),
+ ).toThrow(/@Use field 'extra' is not a requirement in the table/);
+ });
+
+ it("a @Provide field setup() leaves unassigned refuses the boot", async () => {
+ @Module()
+ class Forgetful {
+ @Provide() sessions!: Sessions;
+ setup() {}
+ }
+ const def = moduleDefOf(Forgetful, {
+ manifests: { ...manifests, Forgetful: manifests.SessionsModule! },
+ });
+ await expect(
+ def.create({ use: {}, contributions: {}, resources, effect: () => {} }, null),
+ ).rejects.toThrow(/left @Provide field 'sessions' unassigned/);
+ });
+
+ it("a @Component provides itself: its instance is the api, named by its class", async () => {
+ const withComponent = {
+ ...manifests,
+ // A component's key is `<name>#<Class>`; the class is its own interface.
+ SessionRunner: parseManifest({
+ name: "SessionRunner",
+ requires: {},
+ provides: { SessionRunner: "test#SessionRunner" },
+ contributes: {},
+ children: [],
+ }),
+ SchedulerModule: parseManifest({
+ name: "SchedulerModule",
+ // A bare @Use() typed by a component is wired to that component by the generator.
+ requires: { runner: { iface: "Runner", from: "SessionRunner" } },
+ provides: {},
+ contributes: {},
+ children: [],
+ }),
+ PlatformModule: parseManifest({
+ name: "PlatformModule",
+ requires: {},
+ provides: {},
+ contributes: {},
+ children: ["SessionRunner", "SchedulerModule"],
+ }),
+ };
+ const table = {
+ ...t,
+ "test#SessionRunner": {
+ name: "SessionRunner",
+ methods: { statusOf: { params: [str], returns: { data: "string" } } },
+ slots: {},
+ },
+ };
+ const calls: string[] = [];
+ @Component()
+ class SessionRunner {
+ statusOf(id: string): string {
+ calls.push(id);
+ return "idle";
+ }
+ // no setup(): a component may be a plain class
+ }
+ @Module()
+ class SchedulerModule {
+ @Use() readonly runner!: Runner;
+ setup() {
+ this.runner.statusOf("s");
+ }
+ }
+ @Module({ children: [SessionRunner, SchedulerModule] })
+ class PlatformModule {}
+ const def = moduleDefOf(PlatformModule, { manifests: withComponent });
+ const tree = await bootModules(def, { ifaces: table, resources });
+ expect(calls).toEqual(["s"]);
+ expect(tree.api<SessionRunner>("SessionRunner", "SessionRunner")).toBeInstanceOf(SessionRunner);
+ tree.dispose();
+ });
+
+ it("a @Component the table does not list as providing itself is a stale-table error", () => {
+ @Component()
+ class Sneaky {}
+ expect(() =>
+ moduleDefOf(Sneaky, { manifests: { ...manifests, Sneaky: manifests.SessionsModule! } }),
+ ).toThrow(/component 'Sneaky' does not provide itself in the table/);
+ });
+
+ it("an explicit @Use(From) that disagrees with the table is named", () => {
+ @Module()
+ class Miswired {
+ @Use(SchedulerModule) readonly runner!: Runner;
+ setup() {}
+ }
+ expect(() =>
+ moduleDefOf(Miswired, { manifests: { ...manifests, Miswired: manifests.SchedulerModule! } }),
+ ).toThrow(/wired to 'SchedulerModule' in code, 'SessionsModule' in the table/);
+ });
+
+ it("wire() builds a component outside a tree with its fields supplied by hand", () => {
+ @Component()
+ class Counter {
+ @Use() private readonly runner!: Runner;
+ status(): string {
+ return this.runner.statusOf("x");
+ }
+ }
+ const c = wire(Counter, { runner: { statusOf: () => "busy" } });
+ expect(c.status()).toBe("busy");
+ expect(c).toBeInstanceOf(Counter);
+ });
+
+ it("an undecorated class is refused by name", () => {
+ class Plain {
+ setup() {}
+ }
+ @Module({ children: [Plain] })
+ class X {
+ setup() {}
+ }
+ expect(() =>
+ moduleDefOf(X, {
+ manifests: {
+ ...manifests,
+ X: parseManifest({
+ name: "X",
+ requires: {},
+ provides: {},
+ contributes: {},
+ children: [],
+ }),
+ },
+ }),
+ ).toThrow(/'Plain' is not a @Module/);
+ });
+});
diff --git a/scripts/gen-ifaces.mjs b/scripts/gen-ifaces.mjs
new file mode 100644
index 00000000..f46c578d
--- /dev/null
+++ b/scripts/gen-ifaces.mjs
@@ -0,0 +1,980 @@
+#!/usr/bin/env node
+/**
+ * gen-ifaces: project every interface class (`@Interface()`, or `extends Interface<…>()`) and every @Component
+ * class of a package into the
+ * kernel's signature-level form (core kernel/sig.ts) and write ONE `ifaces.json` per
+ * package — the table the module-tree check (kernel/check.ts) runs over.
+ *
+ * node scripts/gen-ifaces.mjs --project packages/server/tsconfig.json --out packages/server/src/ifaces.json
+ * node scripts/gen-ifaces.mjs ... --check # CI: fail when the file on disk is stale
+ *
+ * The table also carries every module's manifest, read STATICALLY off its class — the
+ * `@Module({...})` / `@Component({...})` literal and the `@Use` / `@Provide` / `@Bind`
+ * fields, identifiers resolved to their declarations, never executed. A @Component is a
+ * class that exports itself: its key is `<name>#<Class>`, its interface is its public
+ * surface (members that do not project become opaque with a warning), and a bare
+ * `@Use()` field typed by a component is wired to that component.
+ *
+ * The TS interface is the source; this file is its projection, so the two cannot drift
+ (the table is generated,
+ * not committed: `pnpm typecheck`, the server's `build` and `test`, and deploy.mjs all
+ * regenerate it; `--check` remains for a CI that wants to assert a committed copy). Keys are `<module>#<Export>`, where the
+ * module is the package name for an interface class (its identity is its structure; the
+ * key only has to agree between provider and consumer) and a component's own name.
+ *
+ * Projection rules — the generator REFUSES what it does not recognize rather than guess:
+ * data types (primitives, literals, unions, arrays, tuples, plain objects, records)
+ * → arktype definitions; a NAMED data type (an interface without methods, a type
+ * alias) is emitted once into `types` and referenced as { "$ref": "<module>#<Name>" },
+ * which also makes a recursive type a reference to itself rather than a cut
+ * an interface WITH methods → { iface: "<module>#<Name>" }, emitted into the table;
+ * its non-method members become `fields` (a published config object is all fields)
+ * function types → { fn }
+ * Promise<T> / PromiseLike<T> → { promise }
+ * AsyncIterable<T> / AsyncGenerator<T> → { stream }
+ * void / undefined return → { void }
+ * Opaque<"Name"> (core kernel/markers) → { opaque: "Name" } — the only by-name comparison
+ * <Name>Slots companion interface → the slots of <Name>; a property typed Slot<D, C>
+ * declares a code half
+ * classes, Map/Set, generics, rest parameters, unions mixing data with non-data → error
+ * A type that recurses into itself is cut at the cycle and compared by name (a warning).
+ */
+import fs from "node:fs";
+import { createHash } from "node:crypto";
+import path from "node:path";
+import ts from "typescript";
+
+const args = process.argv.slice(2);
+const opt = (name) => {
+ const at = args.indexOf(name);
+ return at === -1 ? null : args[at + 1];
+};
+const projects = args.flatMap((a, i) => (a === "--project" ? [args[i + 1]] : []));
+const outPath = opt("--out");
+const checkOnly = args.includes("--check");
+if (projects.length === 0 || outPath === null) {
+ console.error(
+ "usage: gen-ifaces --project <tsconfig> [--project ...] --out <ifaces.json> [--check]",
+ );
+ process.exit(2);
+}
+
+const warnings = [];
+const errors = [];
+/** The last reason dataOf answered null, for the error that follows it. */
+let notData = "";
+
+/** module name for a source file: nearest module.json's name, else nearest package.json's name. */
+const moduleNameCache = new Map();
+function moduleNameOf(fileName) {
+ let dir = path.dirname(fileName);
+ if (moduleNameCache.has(dir)) return moduleNameCache.get(dir);
+ const start = dir;
+ for (;;) {
+ // A module's name is the `name` of the defineModule({...}) literal in its module.ts;
+ // a plugin package's is the one its package.json#penguin.modules entry names,
+ // which the package name stands in for here (one module per package is the common case).
+ const mts = path.join(dir, "module.ts");
+ if (fs.existsSync(mts)) {
+ const m =
+ /(?:defineModule|manifestOf|@Module|@Component)\(\s*\{\s*"?name"?:\s*"([^"]+)"/.exec(
+ fs.readFileSync(mts, "utf8"),
+ );
+ if (m) {
+ moduleNameCache.set(start, m[1]);
+ return m[1];
+ }
+ }
+ const pkg = path.join(dir, "package.json");
+ if (fs.existsSync(pkg)) {
+ const name = JSON.parse(fs.readFileSync(pkg, "utf8")).name;
+ moduleNameCache.set(start, name);
+ return name;
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) throw new Error(`no module.json or package.json above ${fileName}`);
+ dir = parent;
+ }
+}
+
+const table = {};
+/** Named data types, keyed like interfaces; signatures reference them as { "$ref": key }. */
+const types = {};
+/** Module manifests, extracted STATICALLY from each module.ts's defineModule({...}) literal. */
+const manifests = {};
+
+for (const project of projects) {
+ const configPath = path.resolve(project);
+ const parsed = ts.getParsedCommandLineOfConfigFile(
+ configPath,
+ {},
+ {
+ ...ts.sys,
+ onUnRecoverableConfigFileDiagnostic: (d) => {
+ throw new Error(ts.flattenDiagnosticMessageText(d.messageText, "\n"));
+ },
+ },
+ );
+ const program = ts.createProgram({ rootNames: parsed.fileNames, options: parsed.options });
+ const checker = program.getTypeChecker();
+
+ const sourceFiles = program
+ .getSourceFiles()
+ .filter((sf) => !sf.isDeclarationFile && !sf.fileName.includes("/node_modules/"));
+ /** An `@Interface()` decorator, like every other decorator here a factory call. */
+ const hasInterfaceDecorator = (d) =>
+ (ts.getDecorators?.(d) ?? []).some(
+ (dec) =>
+ ts.isCallExpression(dec.expression) &&
+ ts.isIdentifier(dec.expression.expression) &&
+ dec.expression.expression.text === "Interface",
+ );
+ /**
+ * An interface handle, wherever it is declared, in either spelling: `@Interface()`
+ * on a class that declares its own abstract members, or `extends Interface<…>()` for
+ * an interface that IS an existing type (see core kernel/markers.ts).
+ */
+ const isInterfaceClassDecl = (d) =>
+ ts.isClassDeclaration(d) &&
+ (hasInterfaceDecorator(d) ||
+ (d.heritageClauses ?? []).some((h) =>
+ h.types.some(
+ (t) =>
+ ts.isCallExpression(t.expression) &&
+ ts.isIdentifier(t.expression.expression) &&
+ t.expression.expression.text === "Interface",
+ ),
+ ));
+ /**
+ * A decorated interface class must be exactly a declaration. Anything else — a base to
+ * inherit members from, a constructor, a member with a body, a private one — would put
+ * implementation into the contract or hide part of it, and which of the two was meant
+ * is not something to guess at.
+ */
+ const checkDecoratedInterface = (d, file) => {
+ if (!ts.isClassDeclaration(d) || !hasInterfaceDecorator(d)) return;
+ const name = d.name?.text ?? "?";
+ const abstract = (d.modifiers ?? []).some((m) => m.kind === ts.SyntaxKind.AbstractKeyword);
+ if (!abstract) errors.push(`${file}: @Interface() ${name}: must be an abstract class`);
+ if ((d.heritageClauses ?? []).length > 0)
+ errors.push(
+ `${file}: @Interface() ${name}: must not extend or implement anything — an interface that IS an existing type uses \`extends Interface<T>()\``,
+ );
+ for (const m of d.members) {
+ const mods = m.modifiers ?? [];
+ const has = (k) => mods.some((x) => x.kind === k);
+ const label = m.name?.getText?.() ?? "member";
+ if (ts.isConstructorDeclaration(m)) {
+ errors.push(`${file}: @Interface() ${name}: must not declare a constructor`);
+ continue;
+ }
+ if (has(ts.SyntaxKind.PrivateKeyword) || has(ts.SyntaxKind.ProtectedKeyword))
+ errors.push(`${file}: @Interface() ${name}.${label}: every member is public`);
+ if (has(ts.SyntaxKind.StaticKeyword))
+ errors.push(`${file}: @Interface() ${name}.${label}: static members are not part of it`);
+ if (!has(ts.SyntaxKind.AbstractKeyword))
+ errors.push(
+ `${file}: @Interface() ${name}.${label}: must be abstract — a member with a body is implementation`,
+ );
+ }
+ };
+
+ // Module manifests: the first argument of every defineModule(...) call, which must be a
+ // pure literal — the static half that is checked before any module code runs.
+ const literal = (node, file) => {
+ if (ts.isObjectLiteralExpression(node)) {
+ const out = {};
+ for (const prop of node.properties) {
+ if (!ts.isPropertyAssignment(prop)) {
+ errors.push(
+ `${file}:${node.getStart()}: manifest literal: only plain properties are allowed`,
+ );
+ continue;
+ }
+ const key = ts.isIdentifier(prop.name)
+ ? prop.name.text
+ : ts.isStringLiteral(prop.name)
+ ? prop.name.text
+ : null;
+ if (key === null) {
+ errors.push(`${file}: manifest literal: computed property names are not allowed`);
+ continue;
+ }
+ out[key] = literal(prop.initializer, file);
+ }
+ return out;
+ }
+ if (ts.isArrayLiteralExpression(node)) return node.elements.map((e) => literal(e, file));
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
+ if (ts.isNumericLiteral(node)) return Number(node.text);
+ if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
+ if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
+ if (node.kind === ts.SyntaxKind.NullKeyword) return null;
+ if (
+ ts.isAsExpression(node) ||
+ ts.isSatisfiesExpression(node) ||
+ ts.isParenthesizedExpression(node)
+ )
+ return literal(node.expression, file);
+ errors.push(
+ `${file}:${node.getStart()}: manifest literal: '${node.getText().slice(0, 40)}' is not a literal — a manifest is data`,
+ );
+ return null;
+ };
+ // Module classes: the @Module({...}) meta literal (name, contributes, context, children) plus
+ // the @Use / @Provide fields, whose TYPE ANNOTATION names the interface class and whose
+ // decorator argument names the providing module class. Identifiers resolve to their
+ // declarations — never executed. Pass 1 collects names; pass 2 resolves references.
+ const moduleClasses = new Map(); // class symbol → { node, meta, file }
+ const refLiteral = (node, file) => {
+ if (ts.isIdentifier(node)) {
+ const sym = checker.getSymbolAtLocation(node);
+ return { $id: sym && sym.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(sym) : sym };
+ }
+ if (ts.isObjectLiteralExpression(node)) {
+ const out = {};
+ for (const prop of node.properties) {
+ if (!ts.isPropertyAssignment(prop)) {
+ errors.push(`${file}: @Module literal: only plain properties are allowed`);
+ continue;
+ }
+ const key = ts.isIdentifier(prop.name)
+ ? prop.name.text
+ : ts.isStringLiteral(prop.name)
+ ? prop.name.text
+ : null;
+ if (key === null) {
+ errors.push(`${file}: @Module literal: computed property names are not allowed`);
+ continue;
+ }
+ out[key] = refLiteral(prop.initializer, file);
+ }
+ return out;
+ }
+ if (ts.isArrayLiteralExpression(node)) return node.elements.map((e) => refLiteral(e, file));
+ return literal(node, file);
+ };
+ const decoratorCall = (node, name) => {
+ for (const dec of ts.getDecorators?.(node) ?? []) {
+ const call = dec.expression;
+ if (
+ ts.isCallExpression(call) &&
+ ts.isIdentifier(call.expression) &&
+ call.expression.text === name
+ )
+ return call;
+ }
+ return null;
+ };
+ for (const sf of program.getSourceFiles()) {
+ if (sf.isDeclarationFile || sf.fileName.includes("/node_modules/")) continue;
+ const file = path.relative(process.cwd(), sf.fileName);
+ const visit = (node) => {
+ if (ts.isClassDeclaration(node) && node.name) {
+ const asModule = decoratorCall(node, "Module");
+ const asComponent = decoratorCall(node, "Component");
+ const call = asModule ?? asComponent;
+ if (asModule && asComponent)
+ errors.push(`${file}: class '${node.name.text}' is both a @Module and a @Component`);
+ if (call && call.arguments.length <= 1) {
+ moduleClasses.set(checker.getSymbolAtLocation(node.name), {
+ node,
+ meta: call.arguments.length === 0 ? {} : refLiteral(call.arguments[0], file),
+ file,
+ kind: asModule ? "module" : "component",
+ className: node.name.text,
+ });
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sf);
+ }
+ const moduleNameBySymbol = new Map();
+ /** component class symbol → its interface key: a component's name is its own module. */
+ const componentKeyBySymbol = new Map();
+ for (const [sym, { node, meta, file, kind, className }] of moduleClasses) {
+ // A node is named by its class: `export class AuthService` is the node `AuthService`.
+ if ("name" in meta) {
+ errors.push(
+ `${file}: @${kind === "module" ? "Module" : "Component"} meta names the node — a node is named by its class ('${className}')`,
+ );
+ continue;
+ }
+ meta.name = className;
+ moduleNameBySymbol.set(sym, meta.name);
+ // `export default class X` names its symbol "default"; the class keeps its own name.
+ if (kind === "component")
+ componentKeyBySymbol.set(sym, `${moduleNameOf(node.getSourceFile().fileName)}#${className}`);
+ }
+ /** interfaces with methods, by symbol → key; filled as they are met so references resolve. */
+ const keys = new Map();
+ const pending = [];
+
+ // An exported interface class is keyed by the EXPORTING module (a re-export from elsewhere in
+ // the package keeps that module's name); a type only reached through a signature is
+ // keyed by where it is declared.
+ const keyOf = (symbol, decl, exportingFile = null) => {
+ if (keys.has(symbol)) return keys.get(symbol);
+ const owner = exportingFile ?? decl.getSourceFile();
+ const key =
+ componentKeyBySymbol.get(symbol) ?? `${moduleNameOf(owner.fileName)}#${symbol.getName()}`;
+ keys.set(symbol, key);
+ pending.push({ symbol, decl, key });
+ return key;
+ };
+
+ const where = (node) => {
+ const sf = node.getSourceFile();
+ const { line } = sf.getLineAndCharacterOfPosition(node.getStart());
+ return `${path.relative(process.cwd(), sf.fileName)}:${line + 1}`;
+ };
+
+ const fail = (node, message) => {
+ errors.push(`${where(node)}: ${message}`);
+ return { data: "unknown" };
+ };
+
+ const isMethodLike = (symbol, atNode) => {
+ const t = checker.getTypeOfSymbolAtLocation(symbol, atNode);
+ return t.getCallSignatures().length > 0 && t.getProperties().length === 0;
+ };
+
+ const hasMethods = (type, atNode) => type.getProperties().some((p) => isMethodLike(p, atNode));
+ const hasUndefined = (type) =>
+ type.isUnion() && type.types.some((t) => t.getFlags() & ts.TypeFlags.Undefined);
+
+ const hasNull = (type) =>
+ type.isUnion()
+ ? type.types.some((t) => (t.getFlags() & ts.TypeFlags.Null) !== 0)
+ : (type.getFlags() & ts.TypeFlags.Null) !== 0;
+ /**
+ * What an optional member or parameter adds is `undefined`; that is what comes off.
+ * `null` is a value the contract has to keep — `x?: string | null` and `x?: string` are
+ * different promises, and a provider handing back null where the consumer allows only
+ * undefined must not pass. The checker can only strip both at once, so null is noted
+ * here and put back on the projected definition by `orNull` / `exprOrNull`.
+ */
+ const sansUndefined = (type) => ({
+ type: checker.getNonNullableType(type),
+ nullable: type.isUnion() && hasNull(type),
+ });
+ const orNull = (def) =>
+ typeof def === "string"
+ ? def
+ .split("|")
+ .map((s) => s.trim())
+ .includes("null")
+ ? def
+ : `${def}|null`
+ : [def, "|", "null"];
+ const exprOrNull = (expr) =>
+ "data" in expr ? { ...expr, data: orNull(expr.data) } : { oneOf: [expr, { data: "null" }] };
+
+ /**
+ * A type declared by the platform (TypeScript's lib, @types/node, a dependency's .d.ts)
+ * rather than by this package: compared by NAME, as `Opaque<>` would spell it — the host
+ * object behind AbortSignal or Request is the same on both sides of a push, and its
+ * structure is not ours to check.
+ */
+ /** An interface class (core kernel/markers.ts Interface) or a component: a handle, never a host object. */
+ const isIfaceClass = (symbol) =>
+ symbol !== undefined &&
+ (componentKeyBySymbol.has(symbol) ||
+ (symbol.declarations ?? []).some((d) => isInterfaceClassDecl(d)));
+
+ const isHostDeclared = (symbol) =>
+ symbol !== undefined &&
+ (symbol.declarations ?? []).length > 0 &&
+ symbol.declarations.every((d) => {
+ const f = d.getSourceFile();
+ return (
+ f.isDeclarationFile &&
+ (f.fileName.includes("/node_modules/") || /\/lib\.[\w.]+\.d\.ts$/.test(f.fileName))
+ );
+ });
+
+ const quote = (s) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
+
+ /** The `types` key for a named data type, or null for an anonymous one. */
+ function namedKeyOf(type) {
+ const alias = type.aliasSymbol;
+ const symbol = alias ?? type.getSymbol();
+ if (!symbol) return null;
+ const name = symbol.getName();
+ if (name === "__type" || name === "__object" || name.startsWith("__")) return null;
+ // Instantiated generics (OmniMessage<OmniPayload>) are named by their instantiation.
+ const args = alias ? type.aliasTypeArguments : checker.getTypeArguments?.(type);
+ const decl = symbol.declarations?.[0];
+ if (!decl) return null;
+ if (!(symbol.flags & (ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias))) return null;
+ const suffix =
+ args && args.length > 0 ? `<${args.map((a) => checker.typeToString(a)).join(",")}>` : "";
+ return `${moduleNameOf(decl.getSourceFile().fileName)}#${name}${suffix}`;
+ }
+
+ /** arktype definition for a DATA type, or null when the type is not data. */
+ function dataOf(type, atNode, stack) {
+ // A named data type is emitted once and referenced — so a recursive one refers to
+ // itself and needs no cut. Anonymous shapes still guard on identity.
+ const key = namedKeyOf(type);
+ if (key !== null && !(type.getFlags() & (ts.TypeFlags.Primitive | ts.TypeFlags.Literal))) {
+ if (key in types || stack.includes(type)) return { $ref: key };
+ types[key] = null; // reserve: a self-reference met while projecting resolves to $ref
+ const projected = projectData(type, atNode, [...stack, type]);
+ if (projected === null) {
+ delete types[key];
+ return null;
+ }
+ types[key] = projected;
+ return { $ref: key };
+ }
+ if (stack.includes(type)) {
+ const label = type.aliasSymbol?.getName() ?? type.getSymbol()?.getName() ?? "type";
+ warnings.push(
+ `${where(atNode)}: '${label}' is recursive; compared as unknown past the cycle`,
+ );
+ return "unknown";
+ }
+ return projectData(type, atNode, stack);
+ }
+
+ /** dataOf without the naming step. */
+ function projectData(type, atNode, stack) {
+ if (stack.length > 12) {
+ warnings.push(
+ `${where(atNode)}: '${checker.typeToString(type)}' is deeper than 12 levels; compared as unknown past that`,
+ );
+ return "unknown";
+ }
+ stack = [...stack, type];
+ const f = type.getFlags();
+ if (f & ts.TypeFlags.String) return "string";
+ if (f & ts.TypeFlags.Number) return "number";
+ if (f & ts.TypeFlags.BigInt) return "bigint";
+ if (f & ts.TypeFlags.Boolean) return "boolean";
+ if (f & ts.TypeFlags.BooleanLiteral) return checker.typeToString(type);
+ if (f & ts.TypeFlags.Null) return "null";
+ if (f & ts.TypeFlags.Undefined) return "undefined";
+ if (f & (ts.TypeFlags.Unknown | ts.TypeFlags.Any)) return "unknown";
+ if (f & ts.TypeFlags.Never) return "never";
+ if (f & ts.TypeFlags.StringLiteral) return quote(type.value);
+ if (f & ts.TypeFlags.NumberLiteral) return String(type.value);
+ if (f & ts.TypeFlags.EnumLiteral && type.isUnion()) {
+ return type.types.map((t) => dataOf(t, atNode, stack)).join("|");
+ }
+ if (type.isUnion()) {
+ const parts = type.types.map((t) => dataOf(t, atNode, stack));
+ if (parts.some((p) => p === null)) {
+ notData = `member of '${checker.typeToString(type)}': ${notData || "not data"}`;
+ return null;
+ }
+ // Collapse `true | false` back to boolean and keep string-only unions readable.
+ if (parts.every((p) => typeof p === "string")) {
+ const set = new Set(parts);
+ if (set.has("true") && set.has("false")) {
+ set.delete("true");
+ set.delete("false");
+ set.add("boolean");
+ }
+ return [...set].join("|");
+ }
+ return parts.slice(1).reduce((acc, p) => [acc, "|", p], parts[0]);
+ }
+ if (type.isIntersection()) {
+ const opaque = type.types.find((t) => t.getProperty("__opaque"));
+ if (opaque) {
+ notData = `'${checker.typeToString(type)}' is opaque`;
+ return null; // handled as opaque by exprOf
+ }
+ const parts = type.types.map((t) => dataOf(t, atNode, stack));
+ if (parts.some((p) => p === null)) {
+ notData = `part of '${checker.typeToString(type)}': ${notData || "not data"}`;
+ return null;
+ }
+ return parts.slice(1).reduce((acc, p) => [acc, "&", p], parts[0]);
+ }
+ if (f & ts.TypeFlags.TypeParameter) {
+ // Erased: a type parameter has no wire form, so the contract says `unknown` here.
+ warnings.push(
+ `${where(atNode)}: type parameter '${checker.typeToString(type)}' erased to unknown`,
+ );
+ return "unknown";
+ }
+ if (f & ts.TypeFlags.Object) {
+ const symbol = type.getSymbol();
+ const name = symbol?.getName();
+ if (name === "Date") return "Date";
+ if (checker.isArrayType(type) || name === "ReadonlyArray") {
+ const elem = checker.getTypeArguments(type)[0];
+ const inner = dataOf(elem, atNode, stack);
+ if (inner === null) {
+ notData = `element of '${checker.typeToString(type)}': ${notData || "not data"}`;
+ return null;
+ }
+ return typeof inner === "string" && /^[\w'|]+$/.test(inner) ? `${inner}[]` : [inner, "[]"];
+ }
+ if (checker.isTupleType(type)) {
+ const elems = checker.getTypeArguments(type).map((t) => dataOf(t, atNode, stack));
+ if (elems.some((e) => e === null)) {
+ notData = `tuple element: ${notData || "not data"}`;
+ return null;
+ }
+ return elems;
+ }
+ if (name === "Map" || name === "Set" || name === "WeakMap") {
+ fail(atNode, `${name} has no wire form; use an array or a record`);
+ return "unknown";
+ }
+ if (type.getCallSignatures().length > 0) {
+ notData = `'${checker.typeToString(type)}' is a function`;
+ return null;
+ }
+ // A host-declared object with behavior is opaque (exprOf); a host-declared plain
+ // shape ({ x: number } from a .d.ts) is data like any other.
+ if (
+ isHostDeclared(symbol) &&
+ (symbol.flags & ts.SymbolFlags.Class || hasMethods(type, atNode))
+ ) {
+ notData = `'${name}' is a host object`;
+ return null;
+ }
+ if (symbol && symbol.flags & ts.SymbolFlags.Class) {
+ if (isIfaceClass(symbol)) {
+ notData = `'${name}' is an interface class`;
+ return null;
+ }
+ fail(atNode, `class '${name}' cannot be a data type; wrap it as Opaque<"${name}">`);
+ return "unknown";
+ }
+ if (hasMethods(type, atNode)) {
+ notData = `'${checker.typeToString(type)}' has methods`;
+ return null;
+ }
+ const next = stack;
+ const out = {};
+ const stringIndex = checker.getIndexInfoOfType(type, ts.IndexKind.String);
+ if (stringIndex) {
+ const v = dataOf(stringIndex.type, atNode, next);
+ if (v === null) {
+ notData = `${name ?? "object"}.[string]: ${notData || checker.typeToString(stringIndex.type)}`;
+ return null;
+ }
+ out["[string]"] = v;
+ }
+ for (const prop of type.getProperties()) {
+ const propType = checker.getTypeOfSymbolAtLocation(prop, atNode);
+ // `x?: T` reads as `T | undefined` under strictNullChecks; an instantiated property
+ // may carry the union without the Optional flag, so the union is the test.
+ const optional = (prop.flags & ts.SymbolFlags.Optional) !== 0 || hasUndefined(propType);
+ const { type: kept, nullable } = optional
+ ? sansUndefined(propType)
+ : { type: propType, nullable: false };
+ let v = dataOf(kept, atNode, next);
+ if (v === null) {
+ notData = `${name ?? "object"}.${prop.getName()}: ${notData || `'${checker.typeToString(propType)}' flags=${propType.getFlags()} sym=${propType.getSymbol()?.getName()}`}`;
+ return null;
+ }
+ if (nullable) v = orNull(v);
+ out[optional ? `${prop.getName()}?` : prop.getName()] = v;
+ }
+ return out;
+ }
+ notData = `'${checker.typeToString(type)}' (flags ${type.getFlags()}) has no data form`;
+ return null;
+ }
+
+ function opaqueName(type) {
+ const prop = type.getProperty("__opaque");
+ if (!prop) return null;
+ const t = checker.getNonNullableType(checker.getTypeOfSymbol(prop));
+ return t.isStringLiteral() ? t.value : null;
+ }
+
+ /** TypeExpr for any type in a signature position. */
+ function exprOf(type, atNode, stack = []) {
+ notData = "";
+ const f = type.getFlags();
+ if (f & ts.TypeFlags.Void) return { void: true };
+ const opaque = opaqueName(type);
+ if (opaque !== null) return { opaque };
+ const symbol = type.getSymbol();
+ const name = symbol?.getName();
+ if (name === "Promise" || name === "PromiseLike") {
+ return { promise: exprOf(checker.getTypeArguments(type)[0], atNode, stack) };
+ }
+ if (name === "AsyncIterable" || name === "AsyncIterableIterator" || name === "AsyncGenerator") {
+ const [t, r] = checker.getTypeArguments(type);
+ const out = { stream: exprOf(t, atNode, stack) };
+ if (
+ name === "AsyncGenerator" &&
+ r &&
+ !(r.getFlags() & (ts.TypeFlags.Void | ts.TypeFlags.Any | ts.TypeFlags.Unknown))
+ ) {
+ out.returns = exprOf(r, atNode, stack);
+ }
+ return out;
+ }
+ const data = dataOf(type, atNode, stack);
+ if (data !== null) return { data };
+ if (type.isUnion()) {
+ // T | null | undefined around a non-data T: `undefined` is absence (`maybe`), `null`
+ // is a value and stays a member.
+ const rest = type.types.filter(
+ (t) => !(t.getFlags() & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)),
+ );
+ const absent = type.types.some((t) => (t.getFlags() & ts.TypeFlags.Undefined) !== 0);
+ if (rest.length > 0) {
+ const members = rest.map((t) => exprOf(t, atNode, stack));
+ if (hasNull(type)) members.push({ data: "null" });
+ const inner = members.length === 1 ? members[0] : { oneOf: members };
+ return absent ? { maybe: inner } : inner;
+ }
+ return fail(
+ atNode,
+ `union '${checker.typeToString(type)}' mixes data with a function, promise or interface (${notData})`,
+ );
+ }
+ const sigs = type.getCallSignatures();
+ if (sigs.length === 1 && type.getProperties().length === 0) {
+ return { fn: sigOf(sigs[0], atNode, stack) };
+ }
+ if (f & ts.TypeFlags.Object) {
+ if (checker.isArrayType(type)) {
+ return { array: exprOf(checker.getTypeArguments(type)[0], atNode, stack) };
+ }
+ if (checker.isTupleType(type)) {
+ return fail(
+ atNode,
+ `tuple '${checker.typeToString(type)}' holds a non-data element (${notData})`,
+ );
+ }
+ if (isHostDeclared(symbol)) return { opaque: name };
+ // A plain object shape some member of which is not data (a Buffer field, a callback
+ // property): structured, compared member by member.
+ if (
+ !hasMethods(type, atNode) &&
+ !(symbol && symbol.flags & ts.SymbolFlags.Class) &&
+ !stack.includes(type)
+ ) {
+ const members = {};
+ const optional = [];
+ for (const prop of type.getProperties()) {
+ const t = checker.getTypeOfSymbolAtLocation(prop, atNode);
+ const opt = (prop.flags & ts.SymbolFlags.Optional) !== 0 || hasUndefined(t);
+ if (opt) optional.push(prop.getName());
+ const { type: kept, nullable } = opt ? sansUndefined(t) : { type: t, nullable: false };
+ const e = exprOf(kept, prop.valueDeclaration ?? atNode, [...stack, type]);
+ members[prop.getName()] = nullable ? exprOrNull(e) : e;
+ }
+ return optional.length > 0 ? { object: members, optional } : { object: members };
+ }
+ if (symbol && symbol.flags & ts.SymbolFlags.Class && !isIfaceClass(symbol)) {
+ return fail(atNode, `class '${name}' in a signature: wrap it as Opaque<"${name}">`);
+ }
+ if (hasMethods(type, atNode) || isIfaceClass(symbol)) {
+ const decl = symbol?.declarations?.find(
+ (d) =>
+ ts.isInterfaceDeclaration(d) ||
+ ts.isTypeAliasDeclaration(d) ||
+ ts.isClassDeclaration(d),
+ );
+ if (!decl)
+ return fail(atNode, `anonymous object with methods; declare it as an exported interface`);
+ return { iface: keyOf(symbol, decl) };
+ }
+ }
+ return fail(atNode, `unsupported type '${checker.typeToString(type)}' (${notData})`);
+ }
+
+ function sigOf(signature, atNode, stack) {
+ if (signature.getTypeParameters()?.length) {
+ warnings.push(
+ `${where(atNode)}: generic method — its type parameters are erased to unknown in the contract`,
+ );
+ }
+ const params = signature.getParameters().map((p) => {
+ const decl = p.valueDeclaration;
+ if (decl && ts.isParameter(decl) && decl.dotDotDotToken) {
+ fail(decl, "rest parameters are not allowed on an interface");
+ }
+ const t = checker.getTypeOfSymbolAtLocation(p, atNode);
+ const optional =
+ decl &&
+ ts.isParameter(decl) &&
+ (decl.questionToken !== undefined || decl.initializer !== undefined);
+ const { type: kept, nullable } = optional ? sansUndefined(t) : { type: t, nullable: false };
+ let expr = exprOf(kept, decl ?? atNode, stack);
+ if (nullable) expr = exprOrNull(expr);
+ if (optional) {
+ if (!("data" in expr)) return { maybe: expr };
+ expr.data =
+ typeof expr.data === "string" && !expr.data.includes("undefined")
+ ? `${expr.data}|undefined`
+ : [expr.data, "|", "undefined"];
+ }
+ return expr;
+ });
+ return { params, returns: exprOf(signature.getReturnType(), atNode, stack) };
+ }
+
+ const LIFECYCLE = new Set(["setup", "park", "migrations"]);
+ /** A member of a component class that is not part of its interface. */
+ const isHiddenMember = (prop) => {
+ const d = prop.valueDeclaration;
+ if (!d) return false;
+ const flags = ts.getCombinedModifierFlags(d);
+ if (flags & (ts.ModifierFlags.Private | ts.ModifierFlags.Protected | ts.ModifierFlags.Static))
+ return true;
+ if (ts.isPrivateIdentifier(d.name)) return true;
+ if (LIFECYCLE.has(prop.getName())) return true;
+ return ["Use", "Provide", "Bind"].some((n) => decoratorCall(d, n));
+ };
+ function ifaceOf(symbol, decl) {
+ const type = checker.getDeclaredTypeOfSymbol(symbol);
+ const key = componentKeyBySymbol.get(symbol);
+ const component = key !== undefined;
+ const methods = {};
+ const fields = {};
+ // A component's interface is whatever of its public surface projects; a member that
+ // does not is opaque (compared by name only) with a warning, since a consumer that
+ // never names it loses nothing and one that does will see the mismatch.
+ const tolerant = (prop, project) => {
+ if (!component) return project();
+ const mark = errors.length;
+ const out = project();
+ if (errors.length === mark) return out;
+ const why = errors.splice(mark).map((e) => e.slice(e.indexOf(": ") + 2));
+ warnings.push(
+ `${where(prop.valueDeclaration ?? decl)}: component member '${prop.getName()}' is opaque in the contract (${why.join("; ")})`,
+ );
+ return { opaque: `${symbol.getName()}.${prop.getName()}` };
+ };
+ for (const prop of type.getProperties()) {
+ if (component && isHiddenMember(prop)) continue;
+ if (!isMethodLike(prop, decl)) {
+ const t = checker.getTypeOfSymbolAtLocation(prop, decl);
+ const optional = (prop.flags & ts.SymbolFlags.Optional) !== 0 || hasUndefined(t);
+ const { type: kept, nullable } = optional ? sansUndefined(t) : { type: t, nullable: false };
+ const projected = tolerant(prop, () => exprOf(kept, prop.valueDeclaration ?? decl, [type]));
+ const expr = nullable ? exprOrNull(projected) : projected;
+ // An optional field may be absent on the instance; the consumer sees a `maybe`.
+ fields[prop.getName()] = optional && !("maybe" in expr) ? { maybe: expr } : expr;
+ continue;
+ }
+ const t = checker.getTypeOfSymbolAtLocation(prop, decl);
+ const sigs = t.getCallSignatures();
+ if (sigs.length !== 1) {
+ tolerant(prop, () =>
+ fail(
+ prop.valueDeclaration ?? decl,
+ `method '${prop.getName()}' has ${sigs.length} overloads; one signature per method`,
+ ),
+ );
+ continue;
+ }
+ const sig = tolerant(prop, () => sigOf(sigs[0], prop.valueDeclaration ?? decl, [type]));
+ if ("opaque" in sig) fields[prop.getName()] = sig;
+ else methods[prop.getName()] = sig;
+ }
+ const out = { name: component ? key.slice(key.indexOf("#") + 1) : symbol.getName(), methods };
+ if (Object.keys(fields).length > 0) out.fields = fields;
+ out.slots = {};
+ return out;
+ }
+
+ function slotsOf(symbol, decl) {
+ const type = checker.getDeclaredTypeOfSymbol(symbol);
+ const slots = {};
+ for (const prop of type.getProperties()) {
+ const t = checker.getTypeOfSymbolAtLocation(prop, decl);
+ const at = prop.valueDeclaration ?? decl;
+ const isSlot =
+ t.getSymbol()?.getName() === "Slot" && t.getProperty("data") && t.getProperty("code");
+ if (isSlot) {
+ const data = dataOf(checker.getTypeOfSymbol(t.getProperty("data")), at, []);
+ if (data === null) {
+ fail(at, `slot '${prop.getName()}': the data half must be a data type`);
+ continue;
+ }
+ const codeType = checker.getTypeOfSymbol(t.getProperty("code"));
+ const slot = { data };
+ if (!(codeType.getFlags() & ts.TypeFlags.Never)) slot.code = exprOf(codeType, at, []);
+ slots[prop.getName()] = slot;
+ } else {
+ const data = dataOf(t, at, []);
+ if (data === null) {
+ fail(
+ at,
+ `slot '${prop.getName()}' must be a data type, or Slot<Data, Code> for a code half`,
+ );
+ continue;
+ }
+ slots[prop.getName()] = { data };
+ }
+ }
+ return slots;
+ }
+
+ // Every exported interface class (either spelling) anywhere in the package is
+ // a table entry, and an exported `<Name>Slots` interface beside one names its slots;
+ // everything else is a data type, reached only through references.
+ const slotCompanions = [];
+ for (const sf of sourceFiles) {
+ const moduleSymbol = checker.getSymbolAtLocation(sf);
+ if (!moduleSymbol) continue;
+ for (const exp of checker.getExportsOfModule(moduleSymbol)) {
+ // A re-export (`export type { X } from "..."`) is an alias; follow it to the declaration.
+ const symbol = exp.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(exp) : exp;
+ const decl = symbol.declarations?.[0];
+ if (!decl) continue;
+ const name = symbol.getName();
+ if (ts.isInterfaceDeclaration(decl) && name.endsWith("Slots")) {
+ slotCompanions.push({ symbol, decl, owner: name.slice(0, -"Slots".length), sf });
+ continue;
+ }
+ if (!isInterfaceClassDecl(decl)) continue;
+ checkDecoratedInterface(decl, path.relative(process.cwd(), sf.fileName));
+ keyOf(symbol, decl, sf);
+ }
+ }
+ for (const [sym, { node }] of moduleClasses) if (componentKeyBySymbol.has(sym)) keyOf(sym, node);
+ while (pending.length > 0) {
+ const { symbol, decl, key } = pending.shift();
+ table[key] = ifaceOf(symbol, decl);
+ }
+ const ifaceKeyOfType = (typeNode, file) => {
+ const sym0 =
+ typeNode && ts.isTypeReferenceNode(typeNode)
+ ? checker.getSymbolAtLocation(typeNode.typeName)
+ : undefined;
+ const sym = sym0 && sym0.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(sym0) : sym0;
+ if (sym && componentKeyBySymbol.has(sym)) return componentKeyBySymbol.get(sym);
+ const decl = sym?.declarations?.find((d) => isInterfaceClassDecl(d));
+ if (!decl) {
+ errors.push(
+ `${file}: a @Use/@Provide field's type must be a @Component class or an interface class (@Interface(), or extends Interface<…>()) (got '${typeNode?.getText() ?? "?"}')`,
+ );
+ return "?";
+ }
+ return `${moduleNameOf(decl.getSourceFile().fileName)}#${sym.getName()}`;
+ };
+ /** The component a bare `@Use()` field is wired to: the one its type names, if any. */
+ const componentOfType = (typeNode) => {
+ const sym0 =
+ typeNode && ts.isTypeReferenceNode(typeNode)
+ ? checker.getSymbolAtLocation(typeNode.typeName)
+ : undefined;
+ const sym = sym0 && sym0.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(sym0) : sym0;
+ return sym && componentKeyBySymbol.has(sym) ? moduleNameBySymbol.get(sym) : undefined;
+ };
+ for (const [sym, { node, meta, file, kind, className }] of moduleClasses) {
+ const m = {
+ name: meta.name,
+ requires: {},
+ provides: {},
+ contributes: meta.contributes ?? {},
+ children: [],
+ };
+ if (meta.context !== undefined) m.context = meta.context;
+ if (kind === "component") {
+ m.provides[className] = componentKeyBySymbol.get(sym);
+ if (meta.children !== undefined)
+ errors.push(`${file}: a @Component has no children — it exports itself`);
+ }
+ for (const member of node.members) {
+ if (!ts.isPropertyDeclaration(member) || !member.name) continue;
+ const field = ts.isIdentifier(member.name)
+ ? member.name.text
+ : ts.isStringLiteral(member.name)
+ ? member.name.text
+ : null;
+ if (field === null) continue;
+ const use = decoratorCall(member, "Use");
+ if (use) {
+ const req = { iface: ifaceKeyOfType(member.type, file) };
+ if (use.arguments.length > 0) {
+ const ref = refLiteral(use.arguments[0], file);
+ const fromName = moduleNameBySymbol.get(ref?.$id);
+ if (fromName === undefined)
+ errors.push(
+ `${file}: @Use(${use.arguments[0].getText()}) on '${field}': not a @Module class`,
+ );
+ req.from = fromName ?? "?";
+ } else {
+ const from = componentOfType(member.type);
+ if (from !== undefined) req.from = from;
+ }
+ m.requires[field] = req;
+ }
+ if (decoratorCall(member, "Provide")) {
+ if (kind === "component")
+ errors.push(`${file}: @Provide on a @Component: a component exports only itself`);
+ m.provides[field] = ifaceKeyOfType(member.type, file);
+ }
+ }
+ for (const child of meta.children ?? []) {
+ const childName = moduleNameBySymbol.get(child?.$id);
+ if (childName === undefined)
+ errors.push(`${file}: children: an entry is not a @Module or @Component class`);
+ m.children.push(childName ?? "?");
+ }
+ if (manifests[m.name]) errors.push(`${file}: module '${m.name}' is defined twice`);
+ manifests[m.name] = m;
+ }
+ for (const { symbol, decl, owner, sf } of slotCompanions) {
+ const ownerExp = checker
+ .getExportsOfModule(checker.getSymbolAtLocation(sf))
+ .find((e) => e.getName() === owner);
+ const ownerSym =
+ ownerExp &&
+ (ownerExp.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(ownerExp) : ownerExp);
+ const key = ownerSym && keys.get(ownerSym);
+ if (!key || !table[key]) {
+ errors.push(
+ `${where(decl)}: '${symbol.getName()}' has no interface '${owner}' in the same module to attach to`,
+ );
+ continue;
+ }
+ table[key].slots = slotsOf(symbol, decl);
+ }
+}
+
+for (const w of warnings) console.warn(`gen-ifaces: warning: ${w}`);
+if (errors.length > 0) {
+ for (const e of errors) console.error(`gen-ifaces: error: ${e}`);
+ process.exit(1);
+}
+
+const sortKeys = (o) =>
+ Object.fromEntries(
+ Object.keys(o)
+ .sort()
+ .map((k) => [k, o[k]]),
+ );
+// The table's identity: a sha256 over its canonical content, so two builds can tell at
+// a glance whether they agree on every interface and manifest (the page CI publishes
+// carries it, and a pre-push check compares it). The hash is not part of what it hashes.
+const body = { ifaces: sortKeys(table), types: sortKeys(types), modules: sortKeys(manifests) };
+const hash = createHash("sha256").update(JSON.stringify(body)).digest("hex");
+const text = `${JSON.stringify({ hash, ...body }, null, 1)}\n`;
+const existing = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : null;
+if (checkOnly) {
+ if (existing !== text) {
+ console.error(`gen-ifaces: ${outPath} is stale — run \`pnpm gen:ifaces\``);
+ process.exit(1);
+ }
+ console.log(
+ `gen-ifaces: ${outPath} is up to date (${Object.keys(table).length} interfaces, ${Object.keys(types).length} types)`,
+ );
+} else if (existing !== text) {
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
+ fs.writeFileSync(outPath, text);
+ console.log(
+ `gen-ifaces: wrote ${outPath} (${Object.keys(table).length} interfaces, ${Object.keys(types).length} types)`,
+ );
+} else {
+ console.log(
+ `gen-ifaces: ${outPath} unchanged (${Object.keys(table).length} interfaces, ${Object.keys(types).length} types)`,
+ );
+}
diff --git a/scripts/iface-page.mjs b/scripts/iface-page.mjs
new file mode 100644
index 00000000..870f1949
--- /dev/null
+++ b/scripts/iface-page.mjs
@@ -0,0 +1,229 @@
+#!/usr/bin/env node
+/**
+ * iface-page: render a package's generated ifaces.json (scripts/gen-ifaces.mjs) as ONE
+ * self-contained HTML page — the module tree, every node's requires / provides /
+ * contributes, and every interface at signature level — beside a copy of the JSON.
+ *
+ * node scripts/iface-page.mjs --in packages/server/src/ifaces.json --out dist-ifaces
+ *
+ * The page's header carries the table's hash; `<out>/ifaces.json` is byte-for-byte the
+ * table the page was rendered from, so the URL of a page names one interface state.
+ */
+import fs from "node:fs";
+import path from "node:path";
+
+const args = process.argv.slice(2);
+const opt = (name, fallback) => {
+ const i = args.indexOf(name);
+ return i >= 0 ? args[i + 1] : fallback;
+};
+const inPath = opt("--in", "packages/server/src/ifaces.json");
+const outDir = opt("--out", "dist-ifaces");
+const meta = {
+ sha: opt("--sha", process.env.GITHUB_SHA ?? ""),
+ ref: opt("--ref", process.env.GITHUB_REF_NAME ?? ""),
+ repo: opt("--repo", process.env.GITHUB_REPOSITORY ?? ""),
+ builtAt: new Date().toISOString(),
+};
+
+const text = fs.readFileSync(inPath, "utf8");
+const table = JSON.parse(text);
+/** For anything from the command line that lands in the page: a ref name may carry `<`. */
+const esc = (s) =>
+ String(s).replace(
+ /[&<>"']/g,
+ (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c],
+ );
+if (typeof table.hash !== "string") {
+ console.error(`iface-page: ${inPath} carries no hash — regenerate it with gen-ifaces`);
+ process.exit(1);
+}
+
+// The whole renderer lives in the page: the data is embedded as JSON, nothing is fetched.
+const page = `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>module tree · ${table.hash.slice(0, 12)}</title>
+<style>
+:root { color-scheme: light dark; --ink: #1f2328; --muted: #6a737d; --line: #d0d7de; --bg: #fff; --panel: #f6f8fa; --accent: #0969da; --mod: #8250df; --comp: #1a7f37; }
+@media (prefers-color-scheme: dark) { :root { --ink: #e6edf3; --muted: #8b949e; --line: #30363d; --bg: #0d1117; --panel: #161b22; --accent: #58a6ff; --mod: #d2a8ff; --comp: #3fb950; } }
+* { box-sizing: border-box; }
+body { margin: 0; font: 14px/1.45 system-ui, sans-serif; color: var(--ink); background: var(--bg); }
+header { display: flex; flex-wrap: wrap; gap: 8px 20px; align-items: baseline; padding: 12px 20px; border-bottom: 1px solid var(--line); background: var(--panel); position: sticky; top: 0; z-index: 2; }
+header h1 { font-size: 16px; margin: 0; }
+header code, .hash { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
+.hash { color: var(--muted); }
+header a { color: var(--accent); text-decoration: none; }
+header input { margin-left: auto; padding: 4px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--ink); min-width: 220px; }
+main { display: grid; grid-template-columns: minmax(280px, 380px) 1fr; min-height: calc(100vh - 50px); }
+nav { border-right: 1px solid var(--line); padding: 12px 8px; overflow: auto; max-height: calc(100vh - 50px); position: sticky; top: 50px; }
+nav ul { list-style: none; margin: 0; padding-left: 16px; }
+nav > ul { padding-left: 4px; }
+nav li { margin: 1px 0; }
+nav button { all: unset; cursor: pointer; padding: 2px 6px; border-radius: 4px; display: inline-block; }
+nav button:hover, nav button.current { background: var(--panel); }
+nav button.current { outline: 1px solid var(--line); }
+.kind { font-size: 10px; text-transform: uppercase; letter-spacing: .04em; margin-right: 6px; padding: 0 4px; border-radius: 3px; border: 1px solid; }
+.kind.module { color: var(--mod); border-color: var(--mod); }
+.kind.component { color: var(--comp); border-color: var(--comp); }
+.kind.iface { color: var(--accent); border-color: var(--accent); }
+.kind.slot { color: var(--muted); border-color: var(--muted); }
+section { padding: 16px 24px; max-width: 1100px; }
+section h2 { margin: 0 0 4px; font-size: 20px; }
+section h3 { margin: 18px 0 6px; font-size: 13px; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); }
+.muted { color: var(--muted); }
+table { border-collapse: collapse; width: 100%; }
+td, th { text-align: left; vertical-align: top; padding: 4px 8px; border-bottom: 1px solid var(--line); font-size: 13px; }
+th { color: var(--muted); font-weight: 500; }
+pre, code.sig { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; white-space: pre-wrap; word-break: break-word; margin: 0; }
+pre { background: var(--panel); padding: 10px 12px; border-radius: 6px; overflow: auto; }
+a.ref { color: var(--accent); text-decoration: none; border-bottom: 1px dotted; }
+.opaque { color: var(--muted); font-style: italic; }
+.hidden { display: none; }
+details { margin: 4px 0; }
+summary { cursor: pointer; color: var(--muted); }
+</style>
+</head>
+<body>
+<header>
+ <h1>module tree</h1>
+ <span class="hash" title="sha256 of the interface table">${esc(table.hash)}</span>
+ <a href="ifaces.json">ifaces.json</a>
+ ${meta.repo ? `<a href="https://github.com/${esc(meta.repo)}/commit/${encodeURIComponent(meta.sha)}"><code>${esc(meta.sha.slice(0, 7))}</code> ${esc(meta.ref)}</a>` : ""}
+ <input id="q" type="search" placeholder="filter nodes and interfaces">
+</header>
+<main>
+ <nav id="tree"></nav>
+ <section id="detail"><p class="muted">Pick a node or an interface.</p></section>
+</main>
+<script id="data" type="application/json">${text.replace(/<\//g, "<\\/")}</script>
+<script>
+const T = JSON.parse(document.getElementById("data").textContent);
+const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
+const short = (key) => key.slice(key.indexOf("#") + 1);
+const ref = (key, kind) => '<a class="ref" href="#' + kind + ':' + encodeURIComponent(key) + '" title="' + esc(key) + '">' + esc(short(key)) + "</a>";
+const isComponent = (m) => Object.entries(m.provides).length === 1 && Object.entries(m.provides).every(([alias, key]) => key === m.name + "#" + alias);
+
+// --- TypeExpr → TypeScript-ish text (mirrors core kernel/sig.ts) ---
+function data(d) {
+ if (typeof d === "string") return esc(d);
+ if (Array.isArray(d)) return d.map((x) => (typeof x === "string" && /^(\\|\\s*|\\[\\]|\\?)$/.test(x) ? esc(x) : data(x))).join(" ");
+ if (d && typeof d === "object") {
+ if ("$ref" in d) return ref(d.$ref, "type");
+ const parts = Object.entries(d).map(([k, v]) => esc(k) + ": " + data(v));
+ return "{ " + parts.join("; ") + " }";
+ }
+ return esc(JSON.stringify(d));
+}
+function expr(e) {
+ if (!e || typeof e !== "object") return esc(String(e));
+ if ("data" in e) return data(e.data);
+ if ("$ref" in e) return ref(e.$ref, "type");
+ if ("iface" in e) return ref(e.iface, "iface");
+ if ("opaque" in e) return '<span class="opaque">' + esc(e.opaque) + "</span>";
+ if ("void" in e) return "void";
+ if ("promise" in e) return "Promise&lt;" + expr(e.promise) + "&gt;";
+ if ("stream" in e) return "AsyncIterable&lt;" + expr(e.stream) + "&gt;";
+ if ("array" in e) return "(" + expr(e.array) + ")[]";
+ if ("maybe" in e) return expr(e.maybe) + " | undefined";
+ if ("oneOf" in e) return e.oneOf.map(expr).join(" | ");
+ if ("fn" in e) return "(" + sigParams(e.fn) + ") =&gt; " + expr(e.fn.returns);
+ if ("object" in e) {
+ const opt = new Set(e.optional ?? []);
+ return "{ " + Object.entries(e.object).map(([k, v]) => esc(k) + (opt.has(k) ? "?" : "") + ": " + expr(v)).join("; ") + " }";
+ }
+ return esc(JSON.stringify(e));
+}
+const sigParams = (sig) => sig.params.map((p, i) => "p" + i + ("maybe" in p ? "?" : "") + ": " + expr("maybe" in p ? p.maybe : p)).join(", ");
+const method = (name, sig) => esc(name) + "(" + sigParams(sig) + "): " + expr(sig.returns);
+
+// --- tree ---
+const modules = T.modules;
+const childOf = new Set(Object.values(modules).flatMap((m) => m.children.filter((c) => c !== "*")));
+const roots = Object.keys(modules).filter((n) => !childOf.has(n));
+function node(name) {
+ const m = modules[name];
+ if (!m) return "<li><button disabled>" + esc(name) + " (not in this table)</button></li>";
+ const kind = isComponent(m) ? "component" : "module";
+ const kids = m.children.map((c) => (c === "*" ? '<li><span class="kind slot">slot</span><span class="muted">plugin modules</span></li>' : node(c))).join("");
+ return "<li data-name=\\"" + esc(name) + "\\"><button data-go=\\"node:" + encodeURIComponent(name) + "\\"><span class=\\"kind " + kind + "\\">" + kind[0] + "</span>" + esc(name) + "</button>" + (kids ? "<ul>" + kids + "</ul>" : "") + "</li>";
+}
+const ifaceKeys = Object.keys(T.ifaces).sort();
+document.getElementById("tree").innerHTML =
+ "<ul>" + roots.map(node).join("") + "</ul>" +
+ "<h3 class=\\"muted\\" style=\\"margin:14px 6px 4px;font-size:12px\\">interfaces (" + ifaceKeys.length + ")</h3><ul>" +
+ ifaceKeys.map((k) => "<li data-name=\\"" + esc(k) + "\\"><button data-go=\\"iface:" + encodeURIComponent(k) + "\\"><span class=\\"kind iface\\">i</span>" + esc(short(k)) + "</button></li>").join("") + "</ul>";
+
+// --- detail ---
+function showNode(name) {
+ const m = modules[name];
+ const kind = isComponent(m) ? "component" : "module";
+ const req = Object.entries(m.requires);
+ const prov = Object.entries(m.provides);
+ const contrib = Object.entries(m.contributes);
+ const providers = Object.entries(modules).filter(([, o]) => Object.values(o.requires).some((r) => r.from === name)).map(([n]) => n);
+ return "<h2><span class=\\"kind " + kind + "\\">" + kind + "</span>" + esc(name) + "</h2>" +
+ (m.context ? "<p class=\\"muted\\">parks context v" + esc(m.context.version) + "</p>" : "") +
+ "<h3>requires (" + req.length + ")</h3>" + (req.length ? "<table><tr><th>field</th><th>interface</th><th>from</th></tr>" +
+ req.map(([f, r]) => "<tr><td><code>" + esc(f) + "</code></td><td>" + ref(r.iface, "iface") + "</td><td>" + (r.from ? '<a class="ref" href="#node:' + encodeURIComponent(r.from) + '">' + esc(r.from) + "</a>" : "<span class=\\"muted\\">by structure</span>") + "</td></tr>").join("") + "</table>" : "<p class=\\"muted\\">nothing</p>") +
+ "<h3>provides (" + prov.length + ")</h3>" + (prov.length ? "<table><tr><th>alias</th><th>interface</th></tr>" +
+ prov.map(([a, k]) => "<tr><td><code>" + esc(a) + "</code></td><td>" + ref(k, "iface") + "</td></tr>").join("") + "</table>" : "<p class=\\"muted\\">nothing</p>") +
+ "<h3>contributes (" + contrib.length + ")</h3>" + (contrib.length ? contrib.map(([slot, items]) =>
+ "<details open><summary><code>" + esc(slot) + "</code> × " + items.length + "</summary><pre>" + esc(JSON.stringify(items, null, 2)) + "</pre></details>").join("") : "<p class=\\"muted\\">nothing</p>") +
+ (m.children.length ? "<h3>children (" + m.children.length + ")</h3><p>" + m.children.map((c) => c === "*" ? "<span class=\\"muted\\">+ plugin modules</span>" : '<a class="ref" href="#node:' + encodeURIComponent(c) + '">' + esc(c) + "</a>").join(", ") + "</p>" : "") +
+ (providers.length ? "<h3>wired into</h3><p>" + providers.map((n) => '<a class="ref" href="#node:' + encodeURIComponent(n) + '">' + esc(n) + "</a>").join(", ") + "</p>" : "");
+}
+function showIface(key) {
+ const d = T.ifaces[key];
+ if (!d) return "<h2>" + esc(key) + "</h2><p class=\\"muted\\">not in this table</p>";
+ const methods = Object.entries(d.methods);
+ const fields = Object.entries(d.fields ?? {});
+ const slots = Object.entries(d.slots ?? {});
+ const providedBy = Object.entries(modules).filter(([, m]) => Object.values(m.provides).includes(key)).map(([n]) => n);
+ const requiredBy = Object.entries(modules).filter(([, m]) => Object.values(m.requires).some((r) => r.iface === key)).map(([n]) => n);
+ return "<h2><span class=\\"kind iface\\">interface</span>" + esc(d.name) + "</h2><p class=\\"hash\\">" + esc(key) + "</p>" +
+ "<pre>" + [...methods.map(([n, s]) => method(n, s)), ...fields.map(([n, e]) => esc(n) + ("maybe" in e ? "?" : "") + ": " + expr("maybe" in e ? e.maybe : e))].join("\\n") + (methods.length + fields.length ? "" : "<span class=\\"muted\\">(no members)</span>") + "</pre>" +
+ (slots.length ? "<h3>slots</h3><table><tr><th>slot</th><th>data</th><th>code</th></tr>" + slots.map(([n, s]) => "<tr><td><code>" + esc(n) + "</code></td><td><code class=\\"sig\\">" + expr(s.data ?? s) + "</code></td><td>" + (s.code ? '<code class="sig">' + expr(s.code) + "</code>" : "<span class=\\"muted\\">—</span>") + "</td></tr>").join("") + "</table>" : "") +
+ "<h3>provided by</h3><p>" + (providedBy.length ? providedBy.map((n) => '<a class="ref" href="#node:' + encodeURIComponent(n) + '">' + esc(n) + "</a>").join(", ") : "<span class=\\"muted\\">no module — a consumer-declared shape</span>") + "</p>" +
+ "<h3>required by</h3><p>" + (requiredBy.length ? requiredBy.map((n) => '<a class="ref" href="#node:' + encodeURIComponent(n) + '">' + esc(n) + "</a>").join(", ") : "<span class=\\"muted\\">nobody</span>") + "</p>";
+}
+function showType(key) {
+ const t = T.types[key];
+ return "<h2><span class=\\"kind slot\\">type</span>" + esc(short(key)) + "</h2><p class=\\"hash\\">" + esc(key) + "</p><pre>" + (t === undefined ? "<span class=\\"muted\\">host-declared: compared by name</span>" : data(t)) + "</pre>";
+}
+function route() {
+ const h = decodeURIComponent(location.hash.slice(1));
+ const i = h.indexOf(":");
+ const kind = h.slice(0, i), key = h.slice(i + 1);
+ const el = document.getElementById("detail");
+ el.innerHTML = kind === "node" && modules[key] ? showNode(key) : kind === "iface" ? showIface(key) : kind === "type" ? showType(key) : el.innerHTML;
+ document.querySelectorAll("nav button").forEach((b) => b.classList.toggle("current", b.dataset.go === kind + ":" + encodeURIComponent(key)));
+}
+document.getElementById("tree").addEventListener("click", (e) => {
+ const b = e.target.closest("button[data-go]");
+ if (b) location.hash = b.dataset.go;
+});
+document.getElementById("q").addEventListener("input", (e) => {
+ const q = e.target.value.trim().toLowerCase();
+ // Descendants first (reverse document order): a parent stays visible while a child
+ // matches, and that has to be this query's answer, not the previous one's.
+ [...document.querySelectorAll("nav li[data-name]")].reverse().forEach((li) => {
+ li.classList.toggle("hidden", q !== "" && !li.dataset.name.toLowerCase().includes(q) && !li.querySelector("li[data-name]:not(.hidden)"));
+ });
+});
+window.addEventListener("hashchange", route);
+if (!location.hash && roots[0]) location.hash = "node:" + encodeURIComponent(roots[0]);
+route();
+</script>
+</body>
+</html>
+`;
+
+fs.mkdirSync(outDir, { recursive: true });
+fs.writeFileSync(path.join(outDir, "index.html"), page);
+fs.writeFileSync(path.join(outDir, "ifaces.json"), text);
+console.log(
+ `iface-page: wrote ${outDir}/index.html + ifaces.json (${table.hash.slice(0, 12)}, ${Object.keys(table.modules).length} nodes, ${Object.keys(table.ifaces).length} interfaces)`,
+);