Files
Ekklesia/core/tests/core-migration-discovery.test.ts
T
ekklesiaandClaude Opus 5 c444ff570b feat: let one module contribute a browser renderer to another's capability
The platform has had a complete story for one module using another's
*backend* since ADR 0006 — capabilities, versioned ranges, provider
registration. It has had none at all for one module using another's *browser*
code, and every workaround is wrong in a way that matters: a consumer cannot
import a peer module, it cannot re-implement a renderer for a domain it does
not own, and a second `entrypoints` role would put the platform in charge of
deciding when a slot inside someone else's screen should be filled.

Add a generic browser contribution. `manifestVersion: 7` declares one:
namespaced id, its own version, a target capability, a compatible range, and
one artifact. That is the complete list, and the omissions are the decision —
no payload schema, slot, ordering, or rendering hint exists anywhere, so Core
cannot learn what a slide is because the declaration cannot express it.

Discovery resolves a contribution artifact through the *identical* loop every
other compiled entrypoint uses, inheriting the path, containment, symlink,
extension, and file-kind checks rather than getting a weaker copy of them. The
registry publishes one only when another eligible module provides the target
capability within the declared range; otherwise it is absent rather than
mounted and broken. `apps/api` serves it as a sibling of the artifact and
display routes, with the same policy: three lookup keys, one exact match, one
already-validated path, and one indistinguishable 404 for unknown, undeclared,
stale, and incompatible alike.

A consumer discovers through the host, never through a URL. Its descriptor
carries identity, version, and capability; the URL stays server-side and is
resolved exactly as `api.request("records")` is. A module can only ever see
contributions aimed at a capability it itself provides, and cannot name its
way to anything else — a mount for a withheld id fails without fetching.

The consumer owns the domain contract entirely. Input is opaque JSON, checked
structurally so a Date, a function, a cycle, or `undefined` fails at the
boundary rather than vanishing somewhere far from the mistake, and checked for
nothing else. A contributed renderer receives its own id and that input: no
API client, realtime, principal, configuration, database, storage, or
credential. Loading one grants its module nothing.

The contribution ABI is versioned separately from the module UI ABI, because
the two have different shapes and lifecycles and coupling them would force
every module to rebuild whenever either moved. It supports asynchronous
readiness, update-without-remount (a screen that remounted per tick would
restart animations and reload media), deterministic cleanup in a `finally`,
and sanitized failure that never carries the consumer's domain data. Each
renderer mounts in its own isolated root with its own stylesheet.

The template now declares a contribution, so `pnpm build` exercises the whole
authoring path, and the shell suite drives the full relationship — one module
discovering, mounting, updating, and unmounting another's React renderer with
neither importing the other.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-27 07:47:10 -05:00

244 lines
8.3 KiB
TypeScript

import { createHash } from "node:crypto";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
CORE_MIGRATION_SOURCE_ID,
discoverAllMigrations,
discoverCoreMigrations,
} from "../src/migrations/index.js";
import { ModuleMigrationDiscoveryError } from "../src/modules/index.js";
const originSnapshotId = "00000000-0000-0000-0000-000000000000";
const temporaryDirectories: string[] = [];
afterEach(async () => {
await Promise.all(
temporaryDirectories
.splice(0)
.map((directory) => rm(directory, { force: true, recursive: true })),
);
});
async function createTemporaryDirectory(prefix: string): Promise<string> {
const directory = await mkdtemp(path.join(tmpdir(), prefix));
temporaryDirectories.push(directory);
return directory;
}
/** Writes a single-migration Drizzle directory (journal + snapshot + policy + SQL). */
async function writeMigrationsDirectory(
migrationsDirectory: string,
moduleId: string,
tag: string,
sql: string,
): Promise<string> {
await mkdir(path.join(migrationsDirectory, "meta"), { recursive: true });
await Promise.all([
writeFile(
path.join(migrationsDirectory, "meta/_journal.json"),
JSON.stringify({
version: "7",
dialect: "postgresql",
entries: [{ idx: 0, version: "7", when: 1_700_000_000_000, tag, breakpoints: true }],
}),
),
writeFile(
path.join(migrationsDirectory, "meta/_ekklesia.json"),
JSON.stringify({
version: 1,
moduleId,
entries: [{ tag, destructive: { mode: "none" } }],
}),
),
writeFile(
path.join(migrationsDirectory, "meta/0000_snapshot.json"),
JSON.stringify({
version: "7",
dialect: "postgresql",
id: "10000000-0000-4000-8000-000000000001",
prevId: originSnapshotId,
}),
),
writeFile(path.join(migrationsDirectory, `${tag}.sql`), sql),
]);
return sql;
}
async function createModule(
modulesDirectory: string,
id: string,
options: { readonly dependsOn?: readonly string[] } = {},
): Promise<void> {
const moduleDirectory = path.join(modulesDirectory, id);
const migrationsDirectory = path.join(moduleDirectory, "drizzle");
await mkdir(path.join(moduleDirectory, "dist/server"), { recursive: true });
const requiredDependencies = Object.fromEntries(
(options.dependsOn ?? []).map((dependencyId) => [dependencyId, "^0.1.0"]),
);
await Promise.all([
writeFile(
path.join(moduleDirectory, "package.json"),
JSON.stringify({
name: `@test/module-${id}`,
version: "0.1.0",
type: "module",
ekklesia: { layer: "module" },
}),
),
writeFile(
path.join(moduleDirectory, "ekklesia.module.json"),
JSON.stringify({
manifestVersion: 7,
id,
name: `${id} module`,
version: "0.1.0",
compatibility: { platform: "^0.1.0", moduleSdk: "^0.1.0" },
dependencies: {
modules: { required: requiredDependencies, optional: {} },
capabilities: { required: {}, optional: {} },
},
capabilities: [],
permissions: [],
entrypoints: { server: "./dist/server/index.js", migrations: "./drizzle" },
}),
),
writeFile(
path.join(moduleDirectory, "dist/server/index.js"),
`export default { id: ${JSON.stringify(id)}, version: "0.1.0" };`,
),
]);
await writeMigrationsDirectory(
migrationsDirectory,
id,
"0000_initial",
`CREATE TABLE "${id.replaceAll("-", "_")}_records" ("id" integer);\n`,
);
}
function sha256(contents: string): string {
return createHash("sha256").update(contents).digest("hex");
}
describe("Core-owned migration discovery", () => {
it("discovers Core's own migrations with the reserved core identity and an exact checksum", async () => {
const coreMigrationsDirectory = await createTemporaryDirectory("ekklesia-core-migrations-");
const sql = await writeMigrationsDirectory(
coreMigrationsDirectory,
"core",
"0000_identity_core_tables",
'CREATE TABLE "ekklesia_core_user" ("id" text PRIMARY KEY);\n',
);
const migrations = await discoverCoreMigrations({ coreMigrationsDirectory });
expect(CORE_MIGRATION_SOURCE_ID).toBe("core");
expect(migrations).toHaveLength(1);
expect(migrations[0]).toMatchObject({
approvalRequired: false,
checksum: sha256(sql),
identity: "core:0000_identity_core_tables",
index: 0,
moduleId: "core",
tag: "0000_identity_core_tables",
});
});
it("is deterministic across repeated discovery calls", async () => {
const coreMigrationsDirectory = await createTemporaryDirectory("ekklesia-core-migrations-");
await writeMigrationsDirectory(
coreMigrationsDirectory,
"core",
"0000_identity_core_tables",
'CREATE TABLE "ekklesia_core_user" ("id" text PRIMARY KEY);\n',
);
const first = await discoverCoreMigrations({ coreMigrationsDirectory });
const second = await discoverCoreMigrations({ coreMigrationsDirectory });
expect(first).toEqual(second);
});
it("orders Core migrations before every module migration while preserving dependency-first module order", async () => {
const modulesDirectory = await createTemporaryDirectory("ekklesia-modules-");
const coreMigrationsDirectory = await createTemporaryDirectory("ekklesia-core-migrations-");
await writeMigrationsDirectory(
coreMigrationsDirectory,
"core",
"0000_identity_core_tables",
'CREATE TABLE "ekklesia_core_user" ("id" text PRIMARY KEY);\n',
);
// "calendar" depends on "people"; created on disk in the opposite order so only the
// dependency graph (not directory order) can explain the resulting sequence.
await createModule(modulesDirectory, "calendar", { dependsOn: ["people"] });
await createModule(modulesDirectory, "people");
const aggregate = await discoverAllMigrations({
coreMigrationsDirectory,
moduleDiscovery: { moduleSdkVersion: "0.1.0", modulesDirectory, platformVersion: "0.1.0" },
});
expect(aggregate.modules.map((module) => module.moduleId)).toEqual([
"core",
"people",
"calendar",
]);
expect(aggregate.migrations.map((migration) => migration.identity)).toEqual([
"core:0000_identity_core_tables",
"people:0000_initial",
"calendar:0000_initial",
]);
});
it("rejects an installed module that reuses the reserved core migration identity", async () => {
const modulesDirectory = await createTemporaryDirectory("ekklesia-modules-");
const coreMigrationsDirectory = await createTemporaryDirectory("ekklesia-core-migrations-");
await writeMigrationsDirectory(
coreMigrationsDirectory,
"core",
"0000_identity_core_tables",
'CREATE TABLE "ekklesia_core_user" ("id" text PRIMARY KEY);\n',
);
await createModule(modulesDirectory, "core");
let captured: unknown;
try {
await discoverAllMigrations({
coreMigrationsDirectory,
moduleDiscovery: { moduleSdkVersion: "0.1.0", modulesDirectory, platformVersion: "0.1.0" },
});
} catch (error) {
captured = error;
}
expect(captured).toBeInstanceOf(ModuleMigrationDiscoveryError);
expect((captured as ModuleMigrationDiscoveryError).issues).toEqual([
expect.objectContaining({ code: "MODULE_MIGRATION_ID_DUPLICATE", moduleId: "core" }),
]);
});
it("keeps a fresh, module-free repository honestly reporting only Core's migration", async () => {
const modulesDirectory = await createTemporaryDirectory("ekklesia-modules-");
const coreMigrationsDirectory = await createTemporaryDirectory("ekklesia-core-migrations-");
await writeMigrationsDirectory(
coreMigrationsDirectory,
"core",
"0000_identity_core_tables",
'CREATE TABLE "ekklesia_core_user" ("id" text PRIMARY KEY);\n',
);
const aggregate = await discoverAllMigrations({
coreMigrationsDirectory,
moduleDiscovery: { moduleSdkVersion: "0.1.0", modulesDirectory, platformVersion: "0.1.0" },
});
expect(aggregate.discoveredModules).toEqual([]);
expect(aggregate.modules).toHaveLength(1);
expect(aggregate.modules[0]?.moduleId).toBe("core");
expect(aggregate.migrations).toHaveLength(1);
});
});