diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjs index 4453500..aa411eb 100644 --- a/.dependency-cruiser.cjs +++ b/.dependency-cruiser.cjs @@ -20,6 +20,17 @@ const ENTRY = "(index|server|ui|client)(/index)?\\.tsx?$"; const SEE = "docs/adr/0003-package-shaped-layers.md"; +/** Paths outside `src/modules` that a module owns, written by `npm run generate:modules` (ADR 0017 §4). */ +const OWNED = require("./src/config/modules.owns.generated.json").owned; +/** The bell imports `notifications` until plan 006 M10 composes it from the modules' feeds; M10 deletes this list. */ +const PENDING_M10 = [ + "src/app/(main)/dashboard/layout.tsx", + "src/app/(main)/dashboard/_components/notification-actions.ts", + "src/app/(main)/dashboard/_components/notification-view.ts", + "src/app/(main)/dashboard/_components/notification-view.test.ts", +]; +const exactPath = (path) => `^${path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(/|$)`; + const upwardRule = (name, from, higher) => ({ name, severity: "error", @@ -31,6 +42,22 @@ const upwardRule = (name, from, higher) => ({ /** @type {import('dependency-cruiser').IConfiguration} */ module.exports = { forbidden: [ + { + name: "modules-only-through-composition", + severity: "error", + comment: + "outside src/modules, only the generated composition, the presets and a module's owned paths import a module; add the path to the module's owns and run npm run generate:modules (docs/adr/0017-a-module-is-a-folder.md §4)", + from: { + path: "^(src|workers)/", + pathNot: [ + "^src/modules/", + "^src/config/[^/]+\\.generated\\.ts$", + "^src/verticals/", + ...[...OWNED, ...PENDING_M10].map(exactPath), + ], + }, + to: { path: "^src/modules/" }, + }, upwardRule("no-upward-import-from-platform", PLATFORM, LAYERS), ...LAYERS.slice(0, -1).map((layer, i) => upwardRule(`no-upward-import-from-${layer}`, `^src/${layer}/`, LAYERS.slice(i + 1)), diff --git a/.gitattributes b/.gitattributes index 63edd80..7bb520a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1 @@ -src/config/*.generated.ts linguist-generated=true +src/config/*.generated.* linguist-generated=true diff --git a/scripts/generate-modules.test.ts b/scripts/generate-modules.test.ts index 4d1d562..c840b3f 100644 --- a/scripts/generate-modules.test.ts +++ b/scripts/generate-modules.test.ts @@ -8,6 +8,7 @@ import { compositionProblems, type ModuleServer } from "@/core/module"; import { type Generated, generate, + MODULE_OWNS_PATH, MODULE_SERVERS_PATH, MODULE_UIS_PATH, MODULES_PATH, @@ -74,11 +75,14 @@ describe("the generated module list (ADR 0017 §5)", () => { expect(generated.problems).toEqual([]); }); - it.each([MODULES_PATH, MODULE_SERVERS_PATH, MODULE_UIS_PATH])("%s matches the module folders", (path) => { - expect(readFileSync(join(ROOT, path), "utf8"), `${path} is stale: run npm run generate:modules`).toBe( - generated.files?.[path], - ); - }); + it.each([MODULES_PATH, MODULE_SERVERS_PATH, MODULE_UIS_PATH, MODULE_OWNS_PATH])( + "%s matches the module folders", + (path) => { + expect(readFileSync(join(ROOT, path), "utf8"), `${path} is stale: run npm run generate:modules`).toBe( + generated.files?.[path], + ); + }, + ); it("requires what the import graph shows (ADR 0017's first test, against census C0)", () => { const installed = Object.keys(generated.graph); diff --git a/scripts/generate-modules.ts b/scripts/generate-modules.ts index b6468b5..87096ad 100644 --- a/scripts/generate-modules.ts +++ b/scripts/generate-modules.ts @@ -31,6 +31,8 @@ export const ROOT = fileURLToPath(new URL("..", import.meta.url)); export const MODULES_PATH = "src/config/modules.generated.ts"; export const MODULE_SERVERS_PATH = "src/config/modules.server.generated.ts"; export const MODULE_UIS_PATH = "src/config/modules.client.generated.ts"; +/** The paths modules own outside their folders, which `.dependency-cruiser.cjs` allows to import them (ADR 0017 §4). */ +export const MODULE_OWNS_PATH = "src/config/modules.owns.generated.json"; const HEADER = "// Written by `npm run generate:modules` from the folders of src/modules; do not edit. A test fails when it is stale (ADR 0017 §5)."; @@ -188,6 +190,12 @@ function renderClient(folders: readonly string[]): string { ].join("\n"); } +/** The owned paths before Biome formats them: sorted, so the file changes only when an `owns` list does. */ +function renderOwns(modules: readonly InstalledModule[]): string { + const owned = [...new Set(modules.flatMap(({ manifest }) => manifest.owns))].sort(byCode); + return `${JSON.stringify({ $comment: "Written by npm run generate:modules from the modules' owns; do not edit.", owned })}\n`; +} + /** The module list before Biome formats it. */ function render(modules: readonly InstalledModule[], graph: Readonly>): string { const names = modules.map(({ folder }) => [folder, manifestExportOf(folder)] as const); @@ -248,6 +256,7 @@ export async function generate(root: string = ROOT): Promise { [MODULES_PATH]: formatted(root, MODULES_PATH, render(modules, graph)), [MODULE_SERVERS_PATH]: formatted(root, MODULE_SERVERS_PATH, renderServers(modules)), [MODULE_UIS_PATH]: formatted(root, MODULE_UIS_PATH, renderClient(uiFolders(root, modules))), + [MODULE_OWNS_PATH]: formatted(root, MODULE_OWNS_PATH, renderOwns(modules)), }, } : {}), diff --git a/src/config/modules.owns.generated.json b/src/config/modules.owns.generated.json new file mode 100644 index 0000000..3ed2325 --- /dev/null +++ b/src/config/modules.owns.generated.json @@ -0,0 +1,48 @@ +{ + "$comment": "Written by npm run generate:modules from the modules' owns; do not edit.", + "owned": [ + "e2e/smoke/bookings-day.spec.ts", + "e2e/smoke/bookings-new-reservation.spec.ts", + "e2e/smoke/bookings-touch.spec.ts", + "e2e/smoke/bookings-walk-in.spec.ts", + "e2e/smoke/bookings-writes.spec.ts", + "e2e/smoke/bookings.spec.ts", + "e2e/smoke/customers.spec.ts", + "e2e/smoke/invoice.spec.ts", + "e2e/smoke/notifications.spec.ts", + "e2e/smoke/panel.spec.ts", + "e2e/smoke/parties.spec.ts", + "e2e/smoke/products.spec.ts", + "e2e/workers/cross-door.spec.ts", + "evals/mcp/fixtures/bookings", + "evals/mcp/fixtures/customers", + "evals/mcp/tasks/bookings.json", + "evals/mcp/tasks/customers.json", + "scripts/eval-mcp.bookings.test.ts", + "scripts/eval-mcp.customers.test.ts", + "src/app/(main)/dashboard/bookings", + "src/app/(main)/dashboard/customers", + "src/app/(main)/dashboard/invoice", + "src/app/(main)/dashboard/parties", + "src/app/(main)/dashboard/products", + "src/config/approvals.bookings.test.ts", + "src/config/approvals.customers.test.ts", + "src/config/approvals.notifications.test.ts", + "src/config/approvals.parties.test.ts", + "src/config/bookings.test.ts", + "src/config/catalog-collections.test.ts", + "src/config/customers.test.ts", + "src/config/inventory-units.test.ts", + "src/config/mcp-manifest.bookings.test.ts", + "src/config/mcp-manifest.customers.test.ts", + "src/config/mcp.server.bookings.test.ts", + "src/config/mcp.server.catalog.test.ts", + "src/config/mcp.server.customers.test.ts", + "src/config/mcp.server.inventory.test.ts", + "src/config/mcp.server.notifications.test.ts", + "src/config/mcp.server.parties.test.ts", + "src/config/mcp.server.resources.test.ts", + "src/config/mcp.server.staff.test.ts", + "src/config/notifications.test.ts" + ] +} diff --git a/src/modules/parties/module.ts b/src/modules/parties/module.ts index 50ee85f..ce5b4ec 100644 --- a/src/modules/parties/module.ts +++ b/src/modules/parties/module.ts @@ -29,5 +29,10 @@ export const partiesModule = defineModule({ parties: { schema: partySchema, required: true, ext: { entity: "party", optional: true } }, }, references: [], - owns: ["src/config/approvals.parties.test.ts", "src/config/mcp.server.parties.test.ts"], + owns: [ + "e2e/smoke/parties.spec.ts", + "src/app/(main)/dashboard/parties", + "src/config/approvals.parties.test.ts", + "src/config/mcp.server.parties.test.ts", + ], }); diff --git a/workers/demo-store/src/demo-store.ts b/workers/demo-store/src/demo-store.ts index a15eaec..3518856 100644 --- a/workers/demo-store/src/demo-store.ts +++ b/workers/demo-store/src/demo-store.ts @@ -16,13 +16,20 @@ import { createMockAdapter, createSessionStore, type DemoSession } from "@/core/ import { type CallResult, err } from "@/core/result"; import { boundSession } from "./bounds"; +import { seedFingerprint } from "./seed-shape"; import { DurableObject } from "cloudflare:workers"; +/** Bump by hand when the snapshot's own format changes (its approvals, replays or policy); the seeds need no bump. */ +export const STORE_FORMAT = 7; + /** - * Bump when the shape of the persisted session changes: a mismatch resets the object to the seed. A test pins it to - * a fingerprint of the seeds' structure, so a seed change without a bump fails there. + * The version of a saved session (ADR 0017 §8): the snapshot format and the fingerprint of the seeds it was written + * against, compared as text. A mismatch resets the session to the seed. The `:` keeps it text in the INTEGER column, + * so a session saved under the old numeric version resets once. */ -export const SCHEMA_VERSION = 6; +export const STORE_VERSION = `${STORE_FORMAT}:${seedFingerprint( + Object.fromEntries(Object.entries(DEMO).map(([vertical, { seed }]) => [vertical, seed])), +)}`; /** A session is deleted this long after its last write; the demo cookie is renewed on each write for as long. */ const IDLE_MS = 2 * 60 * 60 * 1000; @@ -159,7 +166,7 @@ export class DemoStore extends DurableObject implements DemoStoreRpc { const row = this.readRow(); if (row === undefined) return store; const saved = - row.schema_version === SCHEMA_VERSION && typeof row.snapshot === "string" ? snapshotOf(row.snapshot) : undefined; + row.schema_version === STORE_VERSION && typeof row.snapshot === "string" ? snapshotOf(row.snapshot) : undefined; if (saved === undefined) { this.ctx.storage.sql.exec("DELETE FROM session"); return store; @@ -186,7 +193,7 @@ export class DemoStore extends DurableObject implements DemoStoreRpc { }); this.ctx.storage.sql.exec( "INSERT OR REPLACE INTO session (id, schema_version, owner, snapshot) VALUES (1, ?, ?, ?)", - SCHEMA_VERSION, + STORE_VERSION, owner, snapshot, ); diff --git a/workers/demo-store/src/seed-shape.ts b/workers/demo-store/src/seed-shape.ts index 7d75607..e747a5b 100644 --- a/workers/demo-store/src/seed-shape.ts +++ b/workers/demo-store/src/seed-shape.ts @@ -10,15 +10,31 @@ const shapeOf = (value: unknown): string => { return value === null ? "null" : typeof value; }; +/** Every row id under a value, with where it sits: a row added to or removed from a collection moves the fingerprint. */ +const idsOf = (value: unknown, path: string): string[] => { + if (Array.isArray(value)) return value.flatMap((item) => idsOf(item, `${path}[]`)); + if (value === null || typeof value !== "object") return []; + const row = value as Readonly>; + const own = typeof row.id === "string" ? [`${path}#${row.id}`] : []; + return [ + ...own, + ...Object.keys(row) + .sort() + .flatMap((key) => idsOf(row[key], `${path}.${key}`)), + ]; +}; + /** - * A stable fingerprint (FNV-1a) of the seeds' structure. A saved session was written against one structure, so when - * this changes `SCHEMA_VERSION` must be bumped; a test pins both together and fails until they move as one. + * A stable fingerprint (FNV-1a) of the seeds: their structure and their row ids, not their other values (ADR 0017 §8). + * A saved session was written against one set of seeds, so the store's version carries this and resets a session + * saved against another, whether a module, a collection, a field or a row came or went. */ -export function seedShapeHash(seeds: Readonly>): string { - const text = Object.keys(seeds) - .sort() - .map((name) => `${name}=${shapeOf(seeds[name])}`) - .join(";"); +export function seedFingerprint(seeds: Readonly>): string { + const names = Object.keys(seeds).sort(); + const text = [ + ...names.map((name) => `${name}=${shapeOf(seeds[name])}`), + ...names.flatMap((name) => idsOf(seeds[name], name)).sort(), + ].join(";"); let hash = 0x811c9dc5; for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193) >>> 0; return hash.toString(16); diff --git a/workers/demo-store/test/demo-store.test.ts b/workers/demo-store/test/demo-store.test.ts index 27b4384..ca4c3c6 100644 --- a/workers/demo-store/test/demo-store.test.ts +++ b/workers/demo-store/test/demo-store.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; import { inputFor } from "@/config/adapter-contract.testkit"; import { MAX_REPLAYS } from "../src/bounds"; -import { SCHEMA_VERSION } from "../src/demo-store"; +import { STORE_VERSION } from "../src/demo-store"; import { clientFor, contextFor, stubFor } from "./support"; import { abortAllDurableObjects, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test"; @@ -226,7 +226,7 @@ describe("DemoStore", () => { ); state.storage.sql.exec( "INSERT INTO session VALUES (1, ?, ?, 'not json')", - SCHEMA_VERSION, + STORE_VERSION, `hospitality:${sessionId}`, ); }); @@ -304,7 +304,7 @@ describe("DemoStore", () => { const client = clientFor(sessionId); await writeSequentially(client, MAX_REPLAYS + 1); - expect(await savedRow(sessionId)).toEqual({ schemaVersion: SCHEMA_VERSION, replays: MAX_REPLAYS }); + expect(await savedRow(sessionId)).toEqual({ schemaVersion: STORE_VERSION, replays: MAX_REPLAYS }); }); it("refuses a caller from another catalogue with the way to fix it", async () => { diff --git a/workers/demo-store/test/schema-version.test.ts b/workers/demo-store/test/schema-version.test.ts deleted file mode 100644 index c23b400..0000000 --- a/workers/demo-store/test/schema-version.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { DEMO } from "@/config/demo-kernel"; - -import { SCHEMA_VERSION } from "../src/demo-store"; -import { seedShapeHash } from "../src/seed-shape"; - -describe("SCHEMA_VERSION", () => { - it("moves together with the structure of the seeds", () => { - // A saved session was written against one seed structure. When this fails, the seeds changed shape: bump - // SCHEMA_VERSION in src/demo-store.ts so saved sessions reset, then update both numbers here. - const seeds = Object.fromEntries(Object.entries(DEMO).map(([vertical, { seed }]) => [vertical, seed])); - expect([SCHEMA_VERSION, seedShapeHash(seeds)]).toEqual([6, "1aefe55a"]); - }); - - it("changes the fingerprint when a collection gains a field", () => { - expect(seedShapeHash({ bookings: [{ id: "a" }] })).not.toBe(seedShapeHash({ bookings: [{ id: "a", note: "x" }] })); - }); - - it("ignores values and the order of keys", () => { - expect(seedShapeHash({ bookings: [{ id: "a", n: 1 }] })).toBe(seedShapeHash({ bookings: [{ n: 2, id: "b" }] })); - }); -}); diff --git a/workers/demo-store/test/store-version.test.ts b/workers/demo-store/test/store-version.test.ts new file mode 100644 index 0000000..c83fd17 --- /dev/null +++ b/workers/demo-store/test/store-version.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; + +import { DEMO } from "@/config/demo-kernel"; + +import { STORE_FORMAT, STORE_VERSION } from "../src/demo-store"; +import { seedFingerprint } from "../src/seed-shape"; + +const seeds = Object.fromEntries(Object.entries(DEMO).map(([vertical, { seed }]) => [vertical, seed])); + +/** ADR 0017 §8: a saved session resets when the snapshot format or the seeds it was written against change. */ +describe("the demo store's version", () => { + it("is the snapshot format and the seeds' fingerprint, as text that never reads as a number", () => { + expect(STORE_VERSION).toBe(`${STORE_FORMAT}:${seedFingerprint(seeds)}`); + expect(Number.isNaN(Number(STORE_VERSION))).toBe(true); + }); + + it("moves when a collection gains a row", () => { + expect(seedFingerprint({ bookings: [{ id: "a" }] })).not.toBe( + seedFingerprint({ bookings: [{ id: "a" }, { id: "b" }] }), + ); + }); + + it("moves when a collection gains a field", () => { + expect(seedFingerprint({ bookings: [{ id: "a" }] })).not.toBe( + seedFingerprint({ bookings: [{ id: "a", note: "x" }] }), + ); + }); + + it("moves when a module's collection goes", () => { + expect(seedFingerprint({ hospitality: { bookings: [{ id: "a" }], stock: [{ id: "s" }] } })).not.toBe( + seedFingerprint({ hospitality: { bookings: [{ id: "a" }] } }), + ); + }); + + it("ignores values other than ids, and the order of keys", () => { + expect(seedFingerprint({ bookings: [{ id: "a", n: 1 }] })).toBe(seedFingerprint({ bookings: [{ n: 2, id: "a" }] })); + }); +});