diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 408376b8a..09930363d 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -116,6 +116,14 @@ MetaObjects, in the way the [`library/`](library/) entries do (see - **An attribute promoted from a pack into core keeps its name and meaning.** Promotion moves which provider registers the attribute. It does not rename it or change what it does, so a model that used the attribute under the pack loads and behaves the same once core owns it. +- **Recorded exception: the systems vocabulary in 1.4.0.** + [ADR-0070](spec/decisions/ADR-0070-systems-estates-and-apis.md) (call 12) moves the `systems` + pack's vocabulary into core and renames part of it (`resource.database` to `resource.rdb`, + `system.internal` and `.external` to `system.software`, and the rest listed there), without a + second independent consumer. The two rules above are waived for that vocabulary only: the + pack was never published, so no adopter's model loads under the old names, and an entity file + names its resource, so the resource must load in every port. Any other promotion follows the + two rules above. A pack in this repository is one of two kinds ([ADR-0069](spec/decisions/ADR-0069-independent-packs.md)). A **bundled pack** (`db`, `rules`, diff --git a/bun.lock b/bun.lock index a7e99ebc7..75e770e3a 100644 --- a/bun.lock +++ b/bun.lock @@ -423,6 +423,7 @@ "devDependencies": { "@metaobjectsdev/conformance": "workspace:*", "@stryker-mutator/core": "^9.6.1", + "ajv": "^8.20.0", "bun-types": "latest", "typescript": "^5.6.0", }, diff --git a/changelog.d/adr-0070-systems-and-reference-facet.md b/changelog.d/adr-0070-systems-and-reference-facet.md new file mode 100644 index 000000000..fd65b6d2f --- /dev/null +++ b/changelog.d/adr-0070-systems-and-reference-facet.md @@ -0,0 +1,11 @@ +- **Spec: ADR-0070 records the 1.4.0 design for systems, estates and APIs, and the provider + definition format gains a reference facet.** ADR-0070 records the seventeen accepted calls + (one `system.software` kind with an owner, organizations, locations, `environment.stage`, + deployment and provision nodes with no platform, product or size, grants that stay inside + their system, the eventing and batch API vocabulary, and core versus pack placement), and + GOVERNANCE.md records the exception for promoting the systems vocabulary into core. + `spec/metamodel-definitions.md` specifies the `ref` facet a reference attribute carries + (`targetType`, `targetSubTypes`, `fieldPath`, `sameSystem`, `errorCode`, `wrongSystemCode`) + and the kind-typed `Parent.child` lookup, and `spec/metamodel-definition.schema.json` is the + format's JSON Schema, which every core definition file validates against unchanged. + Specification only: no port reads the facet yet, and `metamodelVersion` does not move. diff --git a/server/typescript/packages/metadata/package.json b/server/typescript/packages/metadata/package.json index 1bfe71622..425d1f919 100644 --- a/server/typescript/packages/metadata/package.json +++ b/server/typescript/packages/metadata/package.json @@ -75,6 +75,7 @@ "devDependencies": { "@metaobjectsdev/conformance": "workspace:*", "@stryker-mutator/core": "^9.6.1", + "ajv": "^8.20.0", "bun-types": "latest", "typescript": "^5.6.0" } diff --git a/server/typescript/packages/metadata/test/definition-schema.test.ts b/server/typescript/packages/metadata/test/definition-schema.test.ts new file mode 100644 index 000000000..3716b8dd4 --- /dev/null +++ b/server/typescript/packages/metadata/test/definition-schema.test.ts @@ -0,0 +1,176 @@ +// definition-schema — spec/metamodel-definition.schema.json describes the provider +// definition format, including the reference facet (`ref` on an attr child) that +// spec/metamodel-definitions.md specifies. +// +// Two guarantees: +// 1. Every definition file in spec/metamodel/ validates against the schema +// unchanged, so the schema is the format the files are written in and not a +// looser or stricter one. +// 2. The reference facet's shape rules hold: where `ref` may appear, which keys +// it takes, and the sameSystem/wrongSystemCode and fieldPath pairings. +// +// No reader reads `ref` yet; each port's spec reader learns it in its own change. + +import { describe, test, expect } from "bun:test"; +import { readFileSync, readdirSync, existsSync } from "node:fs"; +import { join, dirname } from "node:path"; +import Ajv2020 from "ajv/dist/2020"; + +function repoRoot(): string { + let dir = import.meta.dir; + for (let i = 0; i < 12; i++) { + if (existsSync(join(dir, "spec")) && existsSync(join(dir, "server"))) return dir; + dir = dirname(dir); + } + throw new Error("repo root not found"); +} +const root = repoRoot(); +const schema = JSON.parse(readFileSync(join(root, "spec", "metamodel-definition.schema.json"), "utf-8")); +const validate = new Ajv2020({ allErrors: true, strict: true }).compile(schema); + +const specDir = join(root, "spec", "metamodel"); +const definitionFiles = readdirSync(specDir).filter((f) => f.endsWith(".json")).sort(); + +function errorsOf(doc: unknown): string { + return validate(doc) ? "" : JSON.stringify(validate.errors, null, 2); +} + +/** A one-type definition whose single attr child is `attr`. */ +function withAttr(attr: Record): unknown { + return { + provider: "test", + types: [ + { + type: "grant", + subType: "rdb", + description: "test", + children: [{ type: "attr", subType: "string", name: "resource", min: 1, max: 1, ...attr }], + }, + ], + }; +} + +describe("definition schema — the existing definition files", () => { + test("spec/metamodel holds the 22 core definition files", () => { + expect(definitionFiles.length).toBe(22); + }); + + for (const file of definitionFiles) { + test(`${file} validates unchanged`, () => { + const doc = JSON.parse(readFileSync(join(specDir, file), "utf-8")); + expect(errorsOf(doc)).toBe(""); + }); + } + + test("no existing definition file uses the reference facet yet", () => { + for (const file of definitionFiles) { + const doc = JSON.parse(readFileSync(join(specDir, file), "utf-8")) as { + types?: { children?: object[] }[]; + extends?: { children?: object[] }[]; + }; + const children = [...(doc.types ?? []), ...(doc.extends ?? [])].flatMap((t) => t.children ?? []); + expect(children.filter((c) => "ref" in c)).toEqual([]); + } + }); +}); + +describe("definition schema — the reference facet", () => { + test("a full facet on a string attr is accepted", () => { + const doc = withAttr({ + ref: { + targetType: "resource", + targetSubTypes: ["rdb"], + sameSystem: true, + errorCode: "ERR_REF_UNRESOLVED", + wrongSystemCode: "ERR_GRANT_CROSSES_SYSTEM", + }, + }); + expect(errorsOf(doc)).toBe(""); + }); + + test("the minimal facet is targetType alone", () => { + expect(errorsOf(withAttr({ ref: { targetType: "role" } }))).toBe(""); + }); + + test("a list-valued string attr may carry the facet", () => { + expect(errorsOf(withAttr({ isArray: true, ref: { targetType: "location" } }))).toBe(""); + }); + + test("a fieldPath facet (an existing descriptor's shape) is accepted", () => { + const doc = withAttr({ ref: { targetType: "object", fieldPath: true, errorCode: "ERR_INVALID_REFERENCE" } }); + expect(errorsOf(doc)).toBe(""); + }); + + test("targetType is required", () => { + expect(errorsOf(withAttr({ ref: { targetSubTypes: ["rdb"] } }))).not.toBe(""); + }); + + test("targetType may not be the wildcard", () => { + expect(errorsOf(withAttr({ ref: { targetType: "*" } }))).not.toBe(""); + }); + + test("targetSubTypes may not be empty, repeat, or hold the wildcard", () => { + expect(errorsOf(withAttr({ ref: { targetType: "resource", targetSubTypes: [] } }))).not.toBe(""); + expect(errorsOf(withAttr({ ref: { targetType: "resource", targetSubTypes: ["rdb", "rdb"] } }))).not.toBe(""); + expect(errorsOf(withAttr({ ref: { targetType: "resource", targetSubTypes: ["*"] } }))).not.toBe(""); + }); + + test("an unknown facet key is refused", () => { + expect(errorsOf(withAttr({ ref: { targetType: "resource", targetSubType: "rdb" } }))).not.toBe(""); + }); + + test("sameSystem requires wrongSystemCode", () => { + expect(errorsOf(withAttr({ ref: { targetType: "role", sameSystem: true } }))).not.toBe(""); + }); + + test("wrongSystemCode without sameSystem is refused", () => { + expect(errorsOf(withAttr({ ref: { targetType: "role", wrongSystemCode: "ERR_X" } }))).not.toBe(""); + expect( + errorsOf(withAttr({ ref: { targetType: "role", sameSystem: false, wrongSystemCode: "ERR_X" } })), + ).not.toBe(""); + }); + + test("fieldPath and sameSystem do not combine", () => { + const doc = withAttr({ + ref: { targetType: "object", fieldPath: true, sameSystem: true, wrongSystemCode: "ERR_X" }, + }); + expect(errorsOf(doc)).not.toBe(""); + }); + + test("error codes must look like loader codes", () => { + expect(errorsOf(withAttr({ ref: { targetType: "role", errorCode: "not a code" } }))).not.toBe(""); + }); + + test("the facet is refused on a non-string attr", () => { + expect(errorsOf(withAttr({ subType: "boolean", ref: { targetType: "role" } }))).not.toBe(""); + }); + + test("the facet is refused on a structural child", () => { + const doc = { + provider: "test", + types: [ + { + type: "role", + subType: "service", + description: "test", + children: [{ type: "grant", subType: "*", name: "*", min: 0, max: null, ref: { targetType: "resource" } }], + }, + ], + }; + expect(errorsOf(doc)).not.toBe(""); + }); + + test("the facet is accepted in an extends entry", () => { + const doc = { + provider: "test", + extends: [ + { + type: "source", + subType: "rdb", + children: [{ type: "attr", subType: "string", name: "resource", min: 0, max: 1, ref: { targetType: "resource", targetSubTypes: ["rdb"] } }], + }, + ], + }; + expect(errorsOf(doc)).toBe(""); + }); +}); diff --git a/spec/README.md b/spec/README.md index 00e83cf92..3fd575877 100644 --- a/spec/README.md +++ b/spec/README.md @@ -31,6 +31,7 @@ Each implementation passes the same conformance fixtures under [`fixtures/confor |---|---| | [`metamodel.md`](metamodel.md) | The 11-type vocabulary, structural keys, subtypes, fused-key node encoding. The normative type system. | | [`wire-format.md`](wire-format.md) | JSON shape, body-key order, package resolution, overlay merging, attribute value rules. The normative serialization contract. | +| [`metamodel-definitions.md`](metamodel-definitions.md) | The provider definition file format every port reads (`metamodel/*.json`), the reference facet and how a reference is looked up. Its JSON Schema is [`metamodel-definition.schema.json`](metamodel-definition.schema.json). | | [`conformance-tests.md`](conformance-tests.md) | How to run cross-language conformance fixtures. The contract every implementation passes. | | [`roadmap.md`](roadmap.md) | Release direction, the FR → issue → spec index, and roadmap history. Status and target releases live in GitHub issues labelled `FR`. | | [`design-docs/`](design-docs/) | Project design documents -- historical context and current in-flight design decisions. | diff --git a/spec/decisions/ADR-0070-systems-estates-and-apis.md b/spec/decisions/ADR-0070-systems-estates-and-apis.md new file mode 100644 index 000000000..bccacb214 --- /dev/null +++ b/spec/decisions/ADR-0070-systems-estates-and-apis.md @@ -0,0 +1,213 @@ +# ADR-0070: Systems, estates and APIs + +## Status + +**Accepted** (2026-11-25), for release 1.4.0. This record registers no vocabulary: +`metamodelVersion` and `expected-registry.json` are unchanged by it. The vocabulary it decides +lands in later changes, each of which moves the manifest itself. + +It revises two decisions of the earlier semantic-infrastructure design ("round 1"), which was +never recorded as an ADR and never built in core: the per-environment node as the last settings +layer (call 5 below), and one role reading two other systems' databases (call 9). It amends +[GOVERNANCE.md](../../GOVERNANCE.md#extension-packs-and-the-core-metamodel) for one promotion +(below). It builds on ADR-0007 (the source catalog), ADR-0023 (no attribute a generator could +compute), ADR-0030 (the API surface and the organization tier), ADR-0037 (subtype, attribute or +nothing), ADR-0042 and ADR-0059 (how references resolve), ADR-0066 (the API vocabulary) and +ADR-0069 (independent packs). + +## Context + +Since 1.3.0 an estate is described by independent packs (`packs/systems`, `delivery`, `config`, +`railway`, `cloudflare`). They are TypeScript only, unpublished (`"publish": false`), and some of +their vocabulary does not hold up when a second organization reads the same file: + +- `system.internal` and `system.external` describe the reader, not the system. A vendor's + product is internal in the vendor's repository and external in its customer's. +- Product and platform names are subtypes (`deployment.railway`, `deployment.worker`, + `vault.infisical`, `cloudflare.d1`). Moving a system to another platform would change the + model. +- Region codes, replica counts and sizes sit on deployment nodes, though they differ between + production and a preview of the same system. +- Nothing in the provider definition format can say what a reference may point at, so + `System.child` references are resolved by hand-written code in one pack + (`packs/systems/typescript/src/refs.ts`), in TypeScript only. +- Core's API vocabulary (ADR-0066) has request and response only. Events and file feeds between + systems have no words. + +A design for systems, organizations, locations, environments, deployments and APIs was written +against a fictional five-organization estate (six systems, every resource kind, all three API +styles, data confined to Europe and the US) and three ways to deploy it with only the settings +changing. It put seventeen calls to the captain, who accepted every recommendation on +2026-11-25. + +## The test every subtype and attribute passes + +Asked in order; the first "no" decides. + +| # | Question | If no | +|---|---|---| +| 1 | **Reader.** If another organization loaded this file, would it still be true, word for word? | Not metadata. Derive it from relationships that are true for everyone (owner, deployment, grant). | +| 2 | **Platform.** If every product and platform underneath were replaced, would it still be true? | A setting. | +| 3 | **Choice.** Must it be the same in every environment the system runs in? | A setting. | +| 4 | **Kind** (ADR-0037). Does the thing have attributes, children or rules of its own? | An attribute, or nothing when it can be computed. | + +Words that fail question 1 on sight: internal, external, ours, theirs, local, remote, upstream, +downstream, vendor, customer, partner, third-party. + +## Decision + +The seventeen calls, as accepted. Names in `code` are the vocabulary each later change +registers. + +### A. The model + +1. **One kind of system.** `system.software`, with `@owner` naming an organization. Whether a + model deploys a system is derived from the `deployment` nodes in its own sources, never + declared. A party that publishes no metadata is written down by whoever depends on it, under + the party's own package name, so that nothing changes but a deleted file when the party + publishes. +2. **Organizations.** `organization.company` and `organization.unit` (a unit is a child of a + company or of another unit). No `vendor` or `customer` kind: both fail the reader test. +3. **Jurisdictions.** `location.jurisdiction` is a node, with `location.region` as its children + and `location.zone` under a region. Jurisdictions do not nest in 1.4.0, so a region belongs to + exactly one jurisdiction. +4. **Environments.** One kind, `environment.stage`, with `@owner`, `@purpose` (`production`, + `staging`, `test`, `development`) and `@lifespan` (`standing`, `ephemeral`). Where an + environment runs, a laptop included, is a setting. +5. **Deployment and provision nodes carry no platform, product or size. Revises round 1.** A + `deployment.system`, `deployment.app` or `provision.resource` says what runs or is kept, in + which environment, at which locations, and `@mode`, `@replication` and `@consistency`. + Platform, product, size, counts, host names and identifiers move to the settings, keyed by the + node's name. Round 1 made the node the last settings layer, able to carry sizes and platform + values; that is withdrawn. `ERR_SETTING_NAMES_NOTHING` guards the name key and ships with the + first settings change that reads it. +6. **More than one region.** `@mode`: `activeActive`, `activePassive`. `@replication`: `none`, + `standby`, `multiWriter`. `@consistency`: `strong`, `eventual`. A deployment or resource in + more than one region must state them; nothing defaults. A consumer reaches the provider copy in + its own region, else in its own jurisdiction, else the only one, and is given each address + when several remain. That last rule is tried on the fixture before it is fixed. + +### B. Resources, grants and APIs + +7. **A grant points with `@resource`**, the same word `source.rdb` uses, and `grant.api` points + with `@api`. Round 1's `on` is not used (a YAML 1.1 parser reads it as `true`). +8. **Queues and streams are two kinds**, `resource.queue` and `resource.stream`, with + `grant.queue` and `grant.stream`. Whether a message can be read again changes how the + consumer is written. +9. **Another system's data. Reverses round 1's example of one role reading two other systems' + databases.** A grant on a resource names a resource of the role's own system + (`ERR_GRANT_CROSSES_SYSTEM`); another system's data is reached through an API it provides. + The one exception is declared by the owner: the system that owns the data may declare a + `role.token` carrying the grant, with `@heldBy` naming the system that uses it. **`@heldBy` + is widened** to accept a system as well as an organization. Nobody can grant themselves access + from their own repository. +10. **The API vocabulary goes into core's experimental API provider** (`spec/metamodel/api.json`, + provider `metaobjects-rules`, ADR-0066): `api.eventing` with `operation.event` and + `binding.messaging` (an optional `@protocol` pin, a protocol and never a product); + `api.batch` with `operation.export`, `operation.import` and `binding.file`; `app @provides`; + `resource @carries`; `grant.api`. `@availableBy` takes a day for weekly and monthly feeds. + The `binding.file` attributes stay experimental until one real feed has been modelled. + +### C. Enforcement and where things live + +11. **Reference restrictions are data, read by every port.** The provider definition format + gains a reference facet on an attribute: the target type, the admitted subtypes, and whether + the target must be in the same system, with the codes to raise. Every port's spec reader + reads it and every loader enforces it; the loader resolves `System.child` with a lookup typed + by the attribute, so a role and an app in one system may share a name. The format is + [`spec/metamodel-definitions.md`](../metamodel-definitions.md), "The reference facet". +12. **Where the vocabulary lives: split by what another repository can import.** Core carries + `organization`, `system`, `app` (`service @public`, `client @shell`, `job @schedule` + `@extracts`, `@runsAs`), `build.image`, every `resource` kind (`rdb`, `keyValue`, + `objectStore`, `document`, `search`, `queue`, `stream`, `volume`) with `@residency` and + `@carries`, the four `role` kinds with `@memberOf`, `@heldBy` and `@credential`, a `grant` + per kind and `grant.api`, `source.document`, `source.search`, `source.rdb @resource`, and the + API vocabulary. The delivery pack carries `location`, `environment`, `deployment` and + `provision`. An entity file names its resource, so the resource and its system must load in + every port; nobody imports another company's estate, so the estate words stay in a pack + beside the generators that read them. +13. **Secret stores are a setting** (`secrets.stores`). `vault.infisical` stops being a subtype. + `@secret` on a setting and `@credential` on a grant stay in the model. + +### D. Testing + +14. **The fictional estate becomes a conformance fixture in step with the work.** Its systems + half and cases land with the core vocabulary, its estate half with the model rules, and each + setup's expected output with the emitter that writes it. +16. **Which ports run the model rules.** References and closed values run in every loader. The + whole-model rules run in `meta verify` through a new hook that lets a provider register rules + over the loaded model. The cases file is written so any port can run it. +17. **The doctor reports and never writes. Revises a detail of round 1.** A missing generated + credential is created by the provisioning step or the secret-copy script, never by the + doctor. + +### E. Delivery + +15. **The order of work.** References and vocabulary; then the model rules with the fixture; + then Compose for every kind of resource on one site; then Railway; then the doctor. + +### Rulings on how the calls apply + +Made when the calls were split into changes for 1.4.0: + +- **Parity.** Whatever is core runs in every port at full parity: TypeScript, C#, Java (and + Kotlin through it), Python and Rust. Rust is never preview or exempt for core. This covers the + reference facet, the core vocabulary, the rule hook and the rules over core vocabulary (API, + reference and extract rules), which every port's `verify` runs. Call 16's "TypeScript first" + applies only to rules over vocabulary in an independent pack (placement, residency, settings), + which ADR-0069 §6 lets run where the pack is carried. +- **Settings live in a separate settings file that only TypeScript reads.** They are not new keys + in `.metaobjects/config.json`, so no other port's config reader changes. +- **Terraform targets AWS. Cloudflare stays on wrangler.** The existing Cloudflare emitter keeps + writing `wrangler.jsonc`; the Terraform work starts with Amazon. This replaces the design's + "Terraform starts with Cloudflare", which call 15 above therefore does not list. + +## The promotion into core, and GOVERNANCE.md + +Call 12 moves vocabulary that the `systems` pack registers today into core, and renames some of +it on the way: `resource.database` becomes `resource.rdb`, `resource.bucket` becomes +`resource.objectStore`, `resource.keyvalue` and `resource.cache` become `resource.keyValue`, and +`system.internal` and `.external` become `system.software`. GOVERNANCE.md says +core vocabulary needs a second independent consumer and that a promoted attribute keeps its name +and meaning. This promotion is a recorded exception to both, for three reasons: + +- every pack involved is `"publish": false`, so no adopter's model loads under the old names; +- the renames are what the reader and platform tests require, so keeping the old names would + keep vocabulary this record rules out; +- the second-consumer rule protects core from vocabulary one adopter needs; here the need is + structural, because an entity file in every port names its resource. + +The exception covers the vocabulary named in call 12 only. The change that registers it in core +removes the overlapping types from the pack in the same pull request and states the mapping from +each old name to its new one. + +## Consequences + +- Wave by wave, 1.4.0 adds the reference facet to every port's spec reader, then the core + vocabulary (moving `metamodelVersion` to 1.4), then the fixture, the rule hook, the pack moves + and the emitters. Each change follows this record; none of them needs a new decision for what + is settled here. +- The existing reference codes stay (`ERR_INVALID_RELATIONSHIP`, `ERR_INVALID_REFERENCE`, + `ERR_UNRESOLVED_OBJECT_REF`). `ERR_REF_UNRESOLVED` and `ERR_REF_WRONG_KIND` apply only to + references that are new with the facet. +- The estate packs lose their product-named subtypes and their platform attributes. Because they + are unpublished, the move needs no migration guide for adopters, only a changelog entry. +- A setting is tied to a model node by name. The guard (`ERR_SETTING_NAMES_NOTHING`) is what + keeps a rename from silently orphaning it. +- Deferred past 1.4.0: Compose across sites, Terraform beyond its first cut, a generator for + file-feed jobs, a stand-in server generated from a contract, jurisdictions that nest, webhooks + and gRPC, grants that name entities or rows, and hosts and networks. + +## Related + +- [ADR-0007](ADR-0007-source-v2-paradigm-subtypes-multisource.md) — the source catalog the resource kinds share names + with. +- [ADR-0030](ADR-0030-declared-api-surface-and-org-tier-boundary.md) and + [ADR-0066](ADR-0066-business-rules-operations-and-lifecycles.md) — the API vocabulary this + extends. +- [ADR-0037](ADR-0037-metamodel-vocabulary-expansion-decision-framework.md) — question 4 of the + test. +- [ADR-0059](ADR-0059-references-resolve-once-after-the-tree.md) — the resolver the facet's + lookup builds on. +- [ADR-0069](ADR-0069-independent-packs.md) — where the estate vocabulary lives. +- [`spec/metamodel-definitions.md`](../metamodel-definitions.md) — the reference facet. diff --git a/spec/decisions/README.md b/spec/decisions/README.md index 1440e0a11..66a033cd6 100644 --- a/spec/decisions/README.md +++ b/spec/decisions/README.md @@ -66,6 +66,7 @@ Write one when a decision is **cross-cutting** (affects more than one language p - [ADR-0067 — Generated code is layered, and hand-written code attaches at the service seam](ADR-0067-layering-and-the-service-seam.md) — *Accepted* (layers 0 to 6; a service module per metadata package whose surface is its operations; hand-written bodies, policy and event handling implement generated interfaces and are passed in, in every language; a layer is a generator an app chooses, per package, with no named sets; the actor is an app-defined type; amends ADR-0045) - [ADR-0068 — The list query is part of the cross-port REST contract](ADR-0068-list-query-cross-port-contract.md) — *Accepted* (`?search`, `filter[or]`/`filter[and]`, the nesting cap, the bare-field and leading-`%` refusals, the value-format check, the `in` cap and the invalid_json / invalid_id / pagination.invalid_value / constraint_violation responses are contract in every port; `fixtures/list-query-conformance/` and the api-contract `list-query/` sub-corpus are the authority; each port passes both before rc.4) - [ADR-0069 — Independent packs live in `packs/`, version themselves, and core never depends on them](ADR-0069-independent-packs.md) — *Accepted* (Metamodel N.M names the default bundle only; an independent pack has its own version, may be carried by some ports and not others, and is outside `expected-registry.json`; core never depends on a pack, held by `scripts/check-pack-boundary.ts`; the provider contract is covered by core's package version; a `packs` lane that blocks for a pack's own change and is a canary on core changes; unpublished until an estate project runs it with the drift gate enforced) +- [ADR-0070 — Systems, estates and APIs](ADR-0070-systems-estates-and-apis.md) — *Accepted* (the seventeen calls for 1.4.0: one `system.software` with an `@owner`, `organization.company`/`.unit`, location, `environment.stage`, deployment and provision nodes with no platform, product or size; grants use `@resource` and stay inside their system unless the owner hands out a `role.token` whose `@heldBy` may name a system; the eventing and batch API vocabulary in core's API provider; reference restrictions as data read by every port; core carries what another repository imports and the delivery pack the estate; secret stores and every platform fact are settings; whatever is core runs in every port, Rust included; registers no vocabulary itself, and records the GOVERNANCE exception for the systems vocabulary's promotion) > **Index gap — ADR-0031 through ADR-0051 are on disk but not listed above.** The index stopped > being maintained after ADR-0030; the files are authoritative, this list is not. Read diff --git a/spec/metamodel-definition.schema.json b/spec/metamodel-definition.schema.json new file mode 100644 index 000000000..25ac06703 --- /dev/null +++ b/spec/metamodel-definition.schema.json @@ -0,0 +1,188 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://metaobjects.dev/schema/metamodel-definition.schema.json", + "title": "MetaObjects provider definition file", + "description": "The shape of one provider definition file: spec/metamodel/*.json and every pack's metamodel/*.json. Prose: spec/metamodel-definitions.md. The TypeScript types are ProviderDefinition, TypeDef, ExtendDef and ChildDef in server/typescript/packages/metadata/src/provider-data.ts.", + "type": "object", + "required": ["provider"], + "additionalProperties": false, + "properties": { + "provider": { + "description": "The owning provider id. Groups documentation pages and records which provider registered each attribute (ADR-0062).", + "type": "string", + "minLength": 1 + }, + "types": { + "description": "The provider's type definitions. One entry may be the universal `*.*` entry, whose named attr children are common attributes accepted on every node.", + "type": "array", + "items": { "$ref": "#/$defs/typeDef" } + }, + "extends": { + "description": "Attributes and child rules this provider adds to types another provider registered.", + "type": "array", + "items": { "$ref": "#/$defs/extendDef" } + } + }, + "$defs": { + "portList": { + "type": "array", + "items": { "type": "string", "minLength": 1 }, + "uniqueItems": true + }, + "subTypeSelector": { + "description": "A single subtype, a list of admitted subtypes, or the `*` wildcard.", + "oneOf": [ + { "type": "string", "minLength": 1 }, + { + "type": "array", + "items": { "type": "string", "minLength": 1 }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "typeDef": { + "type": "object", + "required": ["type", "subType", "description"], + "additionalProperties": false, + "properties": { + "type": { "type": "string", "minLength": 1 }, + "subType": { "type": "string", "minLength": 1 }, + "description": { "type": "string" }, + "dataType": { "type": "string", "minLength": 1 }, + "rules": { "type": "string" }, + "example": { "type": "string" }, + "whenToUse": { "type": "string" }, + "implementedIn": { "$ref": "#/$defs/portList" }, + "ports": { "$ref": "#/$defs/portList" }, + "children": { + "type": "array", + "items": { "$ref": "#/$defs/childDef" } + }, + "parents": { + "type": "array", + "items": { "type": "string", "minLength": 1 }, + "uniqueItems": true + }, + "extendsBase": { "type": "boolean" }, + "maxOccurs": { "type": "integer", "minimum": 1 }, + "defaultName": { "type": "string", "minLength": 1 } + } + }, + "extendDef": { + "type": "object", + "required": ["type", "subType", "children"], + "additionalProperties": false, + "properties": { + "type": { "type": "string", "minLength": 1 }, + "subType": { "$ref": "#/$defs/subTypeSelector" }, + "children": { + "type": "array", + "items": { "$ref": "#/$defs/childDef" } + } + } + }, + "childDef": { + "description": "One entry in a type's unified children list. `type: \"attr\"` declares an attribute; any other type declares a structural child.", + "type": "object", + "required": ["type", "name", "min", "max"], + "additionalProperties": false, + "properties": { + "type": { "type": "string", "minLength": 1 }, + "subType": { "$ref": "#/$defs/subTypeSelector" }, + "name": { "type": "string", "minLength": 1 }, + "min": { "type": "integer", "minimum": 0 }, + "max": { + "oneOf": [ + { "type": "integer", "minimum": 0 }, + { "type": "null" } + ] + }, + "named": { "type": "boolean" }, + "description": { "type": "string" }, + "rules": { "type": "string" }, + "example": { "type": "string" }, + "whenToUse": { "type": "string" }, + "default": {}, + "allowedValues": { "type": "array", "minItems": 1 }, + "isArray": { "type": "boolean" }, + "ports": { "$ref": "#/$defs/portList" }, + "implementedIn": { "$ref": "#/$defs/portList" }, + "ref": { "$ref": "#/$defs/referenceFacet" } + }, + "allOf": [ + { + "description": "An attribute is single-valued (max 1) and names one value type, never a list.", + "if": { "properties": { "type": { "const": "attr" } } }, + "then": { + "properties": { + "max": { "const": 1 }, + "subType": { "type": "string" } + } + } + }, + { + "description": "The reference facet is carried only by a string attribute (single or isArray).", + "if": { "required": ["ref"], "properties": { "ref": true } }, + "then": { + "required": ["subType"], + "properties": { + "type": { "const": "attr" }, + "subType": { "const": "string" } + } + } + } + ] + }, + "referenceFacet": { + "description": "What a reference attribute may point at (spec/metamodel-definitions.md, 'The reference facet'). Read by every port's spec reader and enforced by its loader.", + "type": "object", + "required": ["targetType"], + "additionalProperties": false, + "properties": { + "targetType": { + "description": "The type the value must resolve to (`resource`, `object`, `role`). Never the `*` wildcard.", + "type": "string", + "minLength": 1, + "not": { "const": "*" } + }, + "targetSubTypes": { + "description": "The admitted subtypes of targetType. Absent: any subtype.", + "type": "array", + "items": { "type": "string", "minLength": 1, "not": { "const": "*" } }, + "minItems": 1, + "uniqueItems": true + }, + "fieldPath": { + "description": "The value is `Target.field`: the dotted tail names a field of the target and is not resolved by this facet. Only for a top-level target. Default false.", + "type": "boolean" + }, + "sameSystem": { + "description": "The target must be in the same system as the node that declares the attribute. Default false.", + "type": "boolean" + }, + "errorCode": { + "description": "The code raised when the reference does not resolve or resolves to the wrong kind. Absent: ERR_REF_UNRESOLVED and ERR_REF_WRONG_KIND.", + "type": "string", + "pattern": "^ERR_[A-Z0-9_]+$" + }, + "wrongSystemCode": { + "description": "The code raised when sameSystem fails. Required when sameSystem is true.", + "type": "string", + "pattern": "^ERR_[A-Z0-9_]+$" + } + }, + "allOf": [ + { + "if": { "required": ["sameSystem"], "properties": { "sameSystem": { "const": true } } }, + "then": { "required": ["wrongSystemCode"], "properties": { "wrongSystemCode": true } }, + "else": { "not": { "required": ["wrongSystemCode"], "properties": { "wrongSystemCode": true } } } + }, + { + "if": { "required": ["fieldPath"], "properties": { "fieldPath": { "const": true } } }, + "then": { "not": { "required": ["sameSystem"], "properties": { "sameSystem": { "const": true } } } } + } + ] + } + } +} diff --git a/spec/metamodel-definitions.md b/spec/metamodel-definitions.md new file mode 100644 index 000000000..c94215975 --- /dev/null +++ b/spec/metamodel-definitions.md @@ -0,0 +1,180 @@ +# Provider definition files and the reference facet + +A provider's vocabulary is data. Each core provider is one JSON file under +[`metamodel/`](metamodel/), and each independent pack keeps its own under +`packs//metamodel/` (ADR-0069). Every port reads the same files: it lowers each type, +attribute and child rule onto its registry, and its code supplies only what data cannot say +(factories and imperative validators). This page is the normative description of that file +format, and [`metamodel-definition.schema.json`](metamodel-definition.schema.json) is its JSON +Schema. The TypeScript types are `ProviderDefinition`, `TypeDef`, `ExtendDef` and `ChildDef` in +`server/typescript/packages/metadata/src/provider-data.ts`. + +The schema is held to the files by +`server/typescript/packages/metadata/test/definition-schema.test.ts`, which validates every file +in `spec/metamodel/` against it unchanged. + +## The file + +| Key | Meaning | +|---|---| +| `provider` | The owning provider id. It groups documentation pages, and the registry records it as the owner of each attribute the file registers (ADR-0062). | +| `types` | The types this provider registers. One entry may be the universal `*.*` entry, whose named `attr` children are common attributes accepted on every node. | +| `extends` | Attributes and child rules this provider adds to types another provider registered. `subType` is one subtype, a list, or `*` for every registered subtype. | + +A **type entry** carries `type`, `subType` and `description`, and optionally `dataType`, `rules`, +`example`, `whenToUse`, `ports`, `implementedIn`, `children`, `parents`, `extendsBase`, +`maxOccurs` and `defaultName`. Their meanings are documented on `TypeDef`. + +A **child entry** is one item of a type's unified `children` list. `type: "attr"` declares an +attribute: its `subType` is the attribute's value type (one, never a list), `max` is 1, and a +list-valued attribute sets `isArray: true`. Any other `type` declares a structural child, with +full cardinality (`min`, `max`, `null` for unbounded) and one subtype, a list, or `*`. An +attribute may also carry `default`, `allowedValues`, `ports` and `implementedIn`, and, when it +is a reference, `ref`. + +## The reference facet + +A **reference attribute** holds the name of another node. The `ref` facet on its child entry +says what that node must be. With it, "a `grant.rdb` may only name a `resource.rdb`" is one line +of data, and every port's loader enforces it without code of its own for each pack. + +```json +{ "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, + "description": "The resource this grant is on.", + "ref": { + "targetType": "resource", + "targetSubTypes": ["rdb"], + "sameSystem": true, + "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" + } } +``` + +| Key | Required | Meaning | +|---|---|---| +| `targetType` | yes | The type the value must resolve to. Never `*`. | +| `targetSubTypes` | no | The subtypes of `targetType` the value may resolve to. Absent: any. Never empty, never `*`. | +| `fieldPath` | no, default `false` | The value is `Target.field`: the reference resolves `Target`, and the last dotted segment names a field of it that this facet does not resolve. Only for a top-level target, and never with `sameSystem`. It is today's `dottedFieldPath` (`identity.reference @references`). | +| `sameSystem` | no, default `false` | The target must be in the same system as the node that declares the attribute (below). | +| `errorCode` | no | The code raised when the value does not resolve or resolves to the wrong kind. Absent: `ERR_REF_UNRESOLVED` and `ERR_REF_WRONG_KIND`. | +| `wrongSystemCode` | when `sameSystem` is `true` | The code raised when `sameSystem` fails. Present only when `sameSystem` is `true`. | + +Rules on where the facet may appear: + +- Only on an attribute (`type: "attr"`) whose value type is `string`. When the attribute is + list-valued (`isArray: true`), every element is a reference and is checked on its own. +- In a `types` entry or an `extends` entry alike. A provider may make another provider's + attribute a reference only by owning that attribute (ADR-0062). +- Error codes are loader codes (`ERR_` and upper case). A code a provider names is the + provider's to document; the two default codes and every code core uses are in + `fixtures/conformance/ERROR-CODES.json` once a reader raises them. + +**Existing references keep their codes.** Core declares four references in TypeScript code +today (`core-types.ts`: `relationship.* @objectRef` raises `ERR_INVALID_RELATIONSHIP`, +`identity.reference @references` raises `ERR_INVALID_REFERENCE`, and `field.object` and +`field.map @objectRef` raise `ERR_UNRESOLVED_OBJECT_REF`). When they move into the definition +files, each one names its code in `errorCode`, so no fixture or adopter sees a different code. +The two default codes apply to references that are new with the facet. + +**The manifest.** The registry manifest (`fixtures/registry-conformance/`) writes `ref` on an +attribute only when the attribute has one. A registry with no facet writes the manifest it +writes today, byte for byte, so a port can learn to read the facet before any definition file +uses it. + +## How a reference is looked up + +The facet's lookup builds on two rules every port already follows: ADR-0059 §2 (a reference +splits into an owner and a dotted child tail; the owner resolves by its form, and a bare owner +is package-local under ADR-0042) and ADR-0029's child addressing (a package qualifies only the +top-level node; each later dotted segment is a child's bare name). It adds two things: the +lookup is **typed by the facet**, and a bare name may be found **inside the referrer's own +containers**. + +1. **Kind-typed final segment.** The last segment of the path matches only nodes of + `targetType`. A role and an app in one system may both be named `api`: `runsAs: api` finds + the role, because `runsAs` targets `role`, and `app: Parcels.api` finds the app. Names are + unique per type within one parent, so the final segment finds at most one node of the + target type under a given parent. + +2. **Intermediate segments match by name.** Each segment before the last matches a child by + name, of any type. If two children of one parent share that name (an app and a role both + named `api`), the step is ambiguous and the reference does not resolve. Nothing today + addresses a node through a child that shares its name with a sibling. + +3. **Qualified and dotted values.** A value with `::` or a dot resolves exactly as ADR-0059 §2 + says, with the final segment typed as in rule 1: `pkg::Parcels.db`, `Parcels.db`, + `EU.EuWest`. `Parcels.db` is the system `Parcels` in the referrer's package (or at root), then + its child `db` of type `targetType`. + +4. **Bare values look in the referrer's containers first.** A bare value (no `::`, no dot) is + looked for among the children of each container of the referrer, nearest first, up to and + including the referrer's top-level node. At each container only a child of `targetType` + counts, and the first one found is the target. When no container has one, the value resolves + as a top-level node under ADR-0042 (the referrer's package, else root). So a `grant.rdb` + under `role.service api` under `system.software Parcels` reads `resource: db` as + `Parcels.db`. An `object` is always top-level and no container ever holds one, so the four + existing `object` references resolve exactly as they do today. + +5. **Which package the referrer is in** is ADR-0059 §3's: the package of the top-level node + that physically declares the attribute. A reference inherited through `extends` means what + it meant where it was written. + +6. **Untyped lookup, for the error code only.** When the typed lookup of rules 1 to 4 finds no + node, the resolver repeats the lookup along the same order (the same containers nearest first + and then the top level for a bare value, or the same qualified or dotted path), with the final + segment matching a node of any type. A container child and the top-level fallback both count. + Any same-named node found this way means the value names the wrong kind of node. The untyped + lookup never supplies a target. + +7. **Canonical spelling.** The resolver records the target and rewrites the value to its + canonical spelling (ADR-0059 §5-§6). A target found inside a container is written as its + top-level owner's canonical name plus the child path: `runsAs: api` under the system + `quillhaven::parcels::Parcels` is written `quillhaven::parcels::Parcels.api`. A `fieldPath` + value keeps its field segment. + +## What the loader checks, in order + +For each value of an attribute that carries the facet, after the tree has loaded and before +references are bound (ADR-0059 §5): + +| Step | The check | Code when it fails | +|---|---|---| +| 1 | The typed lookup (rules 1 to 4) finds a node of `targetType` | When it finds none, the untyped lookup (rule 6) runs. It finds a same-named node: `errorCode`, else `ERR_REF_WRONG_KIND`. It finds none: `errorCode`, else `ERR_REF_UNRESOLVED` | +| 2 | The node's subtype is in `targetSubTypes`, when the facet lists them | `errorCode`, else `ERR_REF_WRONG_KIND` | +| 3 | `sameSystem`: the target is in the declaring node's system | `wrongSystemCode` | + +Two worked cases. They are normative: + +| Case | Model | Code | +|---|---|---| +| a | `runsAs: db` on an app under `system.software Parcels`. `Parcels` has a `resource.rdb db` and no `role db`. | `ERR_REF_WRONG_KIND` | +| b | `runsAs: nobody`. No node named `nobody` exists in the referrer's containers or at the top level. | `ERR_REF_UNRESOLVED` | + +These two cases become conformance fixtures in the change that first registers vocabulary using +the facet. No fixture exists before then, because no port reads the facet and the `system` and +`role` vocabulary is not registered. + +A value raises at most one error, the first that fails. Each step's message names the attribute, +the value as written and, for steps 2 and 3, what was found (its type, subtype and system). + +**The system of a node** is its nearest ancestor, or the node itself, whose type is `system`. +For `sameSystem`, the declaring node's system and the target's system must be the same node. +A declaring node with no system fails step 3, because a reference that must stay inside a system +cannot be declared outside one. The `system` type is registered by core in 1.4.0 (ADR-0070); a +facet that sets `sameSystem` before then can never pass and no definition file sets it. + +## What the facet does not do + +- It does not make an attribute required. `min` does that, and an absent attribute is the + required-attribute check's error, not the facet's. +- It checks references the loader can decide from the loaded model alone. A rule that needs the + whole model (an API with exactly one provider) or the settings is a `meta verify` rule, not a + facet (ADR-0070, call 16). +- It does not cover references whose grammar names members as well as nodes + (`@implementedBy`), which the requirement gate resolves separately (ADR-0059 §4). + +## Status + +The format and the schema are specified here. No definition file uses `ref` yet, and no port's +spec reader reads it. Each port learns to read and enforce the facet in its own change, while no +definition file uses it, so no registry output changes. The four existing core references then +move from code into the definition files, keeping their codes.