From 5d14dcdddd36601c4006e8509f4fcd52384eede7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 22:31:21 -0500 Subject: [PATCH 01/12] feat(metadata): read and enforce the reference facet in the TypeScript loader The spec reader carries ref on an attr entry; the generic resolver enforces it (target type, subtype list, same system, the facet's codes); the symbol table resolves System.child and pkg::System.child with a kind-typed final segment and looks a bare value up in the referrer's containers first; the registry manifest writes ref only on an attribute that has one. No definition file uses the facet, so no registry or generated output changes. --- CHANGELOG.md | 10 + fixtures/registry-conformance/README.md | 8 + .../packages/metadata/src/core-types.ts | 2 +- .../typescript/packages/metadata/src/index.ts | 13 +- .../metadata/src/loader/meta-data-loader.ts | 2 +- .../metadata/src/loader/resolve-references.ts | 64 +++- .../metadata/src/loader/symbol-table.ts | 171 +++++++++ .../metadata/src/loader/validation-passes.ts | 2 +- .../src/loader/validation-registry.ts | 234 +++++++------ .../packages/metadata/src/provider-data.ts | 60 +++- .../metadata/src/registry-manifest.ts | 31 ++ .../packages/metadata/src/registry.ts | 7 +- .../metadata/src/shared/base-types.ts | 6 + .../packages/metadata/src/validation-types.ts | 63 +++- .../metadata/test/reference-facet.test.ts | 325 ++++++++++++++++++ spec/metamodel-definitions.md | 16 +- 16 files changed, 879 insertions(+), 135 deletions(-) create mode 100644 server/typescript/packages/metadata/src/loader/symbol-table.ts create mode 100644 server/typescript/packages/metadata/test/reference-facet.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 13d261aca3..5807845221 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,16 @@ here.** ## [Unreleased] +- **The TypeScript loader reads and enforces the reference facet** (`ref` on a `type: "attr"` + entry of a provider definition, `spec/metamodel-definitions.md`). A reference attribute can now + say in data what it may name (target type, admitted subtypes, same system), and the loader + checks it with no code per provider: the lookup is typed by the target, a dotted value resolves + `System.child` and `pkg::System.child`, a bare value is looked for in the referrer's own + containers first, and a value names nothing (`ERR_REF_UNRESOLVED`), the wrong kind of node + (`ERR_REF_WRONG_KIND`) or a node of another system (the facet's own code). The registry manifest + writes `ref` only on an attribute that has one. No definition file uses the facet yet, so no + registry, manifest or generated output changes. + - **`meta verify --uuid-values` lists the stored uuids that 1.3.0's write check refuses.** It is a read-only check to run before upgrading. With `--db ` (SQLite, libSQL or Postgres), or with `--dialect d1 [--d1 ] [--remote]`, it reads every place the model types `field.uuid`, in diff --git a/fixtures/registry-conformance/README.md b/fixtures/registry-conformance/README.md index 3c828d0cbd..68097854a4 100644 --- a/fixtures/registry-conformance/README.md +++ b/fixtures/registry-conformance/README.md @@ -276,6 +276,14 @@ still fails everywhere. `@object` (ADR-0001) and `@objectAdapter` (ADR-0005) are `["java", "kotlin"]`, the JVM runtime. They used to be carved out as `PRESENTATION_ONLY` / `NATIVE_BINDING`; both reasons are retired. +### The reference facet (`ref`) + +An attr whose definition entry carries the reference facet (`spec/metamodel-definitions.md`) +carries `"ref"` in the manifest, after any `ports` and before `description`: `targetType`, then +`targetSubTypes` (sorted), `fieldPath` and `sameSystem` (only when `true`), `errorCode` and +`wrongSystemCode` (only when present). An attr with no facet writes no `ref`, so the canonical +does not change until a definition file uses one. + ### EXCLUDED from v1 — deferred follow-ons (documented, not silent) These were evaluated against the three "open boundary calls" in the design spec diff --git a/server/typescript/packages/metadata/src/core-types.ts b/server/typescript/packages/metadata/src/core-types.ts index 48b338d92b..75daf7235b 100644 --- a/server/typescript/packages/metadata/src/core-types.ts +++ b/server/typescript/packages/metadata/src/core-types.ts @@ -513,7 +513,7 @@ function registerCoreTypeDefs(registry: TypeRegistry): void { { attr: IDENTITY_REFERENCE_ATTR_REFERENCES, targetType: TYPE_OBJECT, - dottedFieldPath: true, + fieldPath: true, errorCode: "ERR_INVALID_REFERENCE", }, ]; diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index 4a2b1ff113..e49ecf96f1 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -317,7 +317,7 @@ export { METAMODEL_TYPE_PAGE_REF, } from "./metamodel-docs/index.js"; export type { MetamodelDocsPage } from "./metamodel-docs/index.js"; -export type { RegistryManifest, ManifestType, ManifestAttr, ManifestChild } from "./registry-manifest.js"; +export type { RegistryManifest, ManifestType, ManifestAttr, ManifestChild, ManifestRef } from "./registry-manifest.js"; // Registry coverage (SP-G Unit 5) — untested-vocabulary report (manifest vs // fixture corpora). NODE-ONLY: registry-coverage.ts statically imports node:fs @@ -341,7 +341,16 @@ export type { MetaDataTypeProvider } from "./provider.js"; export { applyProviderDefinition } from "./provider-data.js"; export type { ProviderDefinition, TypeDef, ChildDef, ExtendDef, FactoryMap, ValidatorMap } from "./provider-data.js"; // The validation hook a provider's TypeDefinition may carry (`validate`). -export type { NodeValidator, ValidationContext, SymbolTable, LoaderCode } from "./validation-types.js"; +export type { + NodeValidator, + ValidationContext, + SymbolTable, + LoaderCode, + ReferenceFacet, + ReferenceDescriptor, + ReferenceMatch, +} from "./validation-types.js"; +export { REF_UNRESOLVED_CODE, REF_WRONG_KIND_CODE } from "./validation-types.js"; // DataType classification export { diff --git a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts index f14f6b003d..9681742b40 100644 --- a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts +++ b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts @@ -797,7 +797,7 @@ export class MetaDataLoader { // ADR-0059 R5 — after the last validation pass, before freeze: resolve every // reference once, record its target and rewrite it to its canonical spelling. - resolveReferences(root); + resolveReferences(root, this._registry); } // If nothing parsed successfully, synthesize an empty root so callers diff --git a/server/typescript/packages/metadata/src/loader/resolve-references.ts b/server/typescript/packages/metadata/src/loader/resolve-references.ts index 4b7ec7e21a..f4232166b9 100644 --- a/server/typescript/packages/metadata/src/loader/resolve-references.ts +++ b/server/typescript/packages/metadata/src/loader/resolve-references.ts @@ -32,6 +32,10 @@ import { } from "../naming-refs.js"; import { resolveSuperRef } from "../super-resolve.js"; import { dimensionViaTerminal } from "./reporting-validation.js"; +import type { TypeRegistry } from "../registry.js"; +import type { ReferenceFacet } from "../validation-types.js"; +import { CHILD_REF_SEPARATOR } from "../shared/structural.js"; +import { SymbolTableImpl } from "./symbol-table.js"; /** One resolved reference: its owner object and the canonical spelling. */ interface Resolved { @@ -73,12 +77,42 @@ function referrerPackage(root: MetaData, node: MetaData, attr: string, declPkg: return declPkg; } +/** Resolves one reference value of `attr` on `node`, or undefined when it names nothing. */ +type ResolveValue = (value: string) => Resolved | undefined; + +/** A facet reference (spec/metamodel-definitions.md, rule 7): the target the typed + * lookup finds, spelled as its top-level owner's canonical name plus the child path. A + * `fieldPath` value keeps its field segment. */ +function facetResolver( + symbols: SymbolTableImpl, + node: MetaData, + facet: ReferenceFacet, + declPkg: string, +): ResolveValue { + return (value) => { + const target = symbols.lookup(node, value, facet, declPkg).target; + if (target === undefined) return undefined; + const owner = topLevelNodeOf(target); + let tail = ""; + for (let n: MetaData = target; n !== owner && n.parent !== undefined; n = n.parent) { + tail = `${CHILD_REF_SEPARATOR}${n.name}${tail}`; + } + if (facet.fieldPath === true) tail = splitChildTail(value).tail; + return { target, canonical: spellRef(owner, declPkg, tail) }; + }; +} + function resolveAttr(root: MetaData, node: MetaData, attr: MetaAttr, declPkg: string): void { - const value = attr.value; const refPkg = referrerPackage(root, node, attr.name, declPkg); + bindAttr(node, attr, (v) => resolveOne(root, v, refPkg, declPkg)); +} + +/** Record each resolved value's target on `attr` and rewrite it to its canonical spelling. */ +function bindAttr(node: MetaData, attr: MetaAttr, resolveValue: ResolveValue): void { + const value = attr.value; if (typeof value === "string") { if (value === "") return; - const r = resolveOne(root, value, refPkg, declPkg); + const r = resolveValue(value); if (r === undefined) return; attr.resolvedTarget = r.target; if (r.canonical !== value) { @@ -89,7 +123,7 @@ function resolveAttr(root: MetaData, node: MetaData, attr: MetaAttr, declPkg: st } if (Array.isArray(value) && value.every((v) => typeof v === "string")) { const items = value as readonly string[]; - const resolved = items.map((v) => (v === "" ? undefined : resolveOne(root, v, refPkg, declPkg))); + const resolved = items.map((v) => (v === "" ? undefined : resolveValue(v))); if (resolved.every((r) => r === undefined)) return; attr.resolvedTarget = resolved.map((r) => r?.target); const canonical: AttrValue = items.map((v, i) => resolved[i]?.canonical ?? v); @@ -122,9 +156,19 @@ function resolveExtends(root: MetaData, node: MetaData): void { /** * Resolve every own reference attribute (ADR-0059 R4) and every `extends` in the * tree, record the targets, and rewrite resolved values to their canonical spelling. - * Must run after the last validation pass and before `freeze()`. + * With `registry`, an attribute whose schema carries the reference facet is resolved + * too, by the facet's typed lookup. Must run after the last validation pass and before + * `freeze()`. */ -export function resolveReferences(root: MetaData): void { +export function resolveReferences(root: MetaData, registry?: TypeRegistry): void { + let symbols: SymbolTableImpl | undefined; + const facetOf = (node: MetaData, name: string): ReferenceFacet | undefined => { + if (registry === undefined) return undefined; + const schema = + registry.find(node.type, node.subType)?.attributes.find((a) => a.name === name) ?? + registry.getCommonAttrs().find((a) => a.name === name); + return schema?.ref; + }; const visit = (node: MetaData): void => { if (node !== root) { resolveExtends(root, node); @@ -134,7 +178,15 @@ export function resolveReferences(root: MetaData): void { // ADR-0039: own — this pass rewrites the declared-here layer; an inherited // attribute is resolved once, on the node that declares it. for (const attr of node.ownMetaAttrs()) { - if (isRefBearingAttr(node, attr.name)) resolveAttr(root, node, attr, declPkg); + if (isRefBearingAttr(node, attr.name)) { + resolveAttr(root, node, attr, declPkg); + continue; + } + const facet = facetOf(node, attr.name); + if (facet !== undefined) { + symbols ??= SymbolTableImpl.build(root); + bindAttr(node, attr, facetResolver(symbols, node, facet, declPkg)); + } } } // ADR-0039: own — structural walk over the physical declaration tree. diff --git a/server/typescript/packages/metadata/src/loader/symbol-table.ts b/server/typescript/packages/metadata/src/loader/symbol-table.ts new file mode 100644 index 0000000000..7976b64a1a --- /dev/null +++ b/server/typescript/packages/metadata/src/loader/symbol-table.ts @@ -0,0 +1,171 @@ +// The symbol table every reference check resolves against — built once per load (the +// binder analogue). Two lookups: +// +// `resolve(type, ref, pkg)` — a top-level node of one type, by ADR-0059 R2 form. +// `lookup(referrer, value, facet, pkg)` — the reference facet's lookup +// (spec/metamodel-definitions.md, "How a reference is looked up"): the final +// segment is typed by the facet, a dotted value walks `System.child` (or +// `pkg::System.child`) through children by name, and a bare value is looked for in +// the referrer's own containers, nearest first, before the top level. When the +// typed lookup finds nothing, an untyped one along the same order tells a value +// that names the wrong kind of node from one that names nothing. + +import type { MetaData } from "../shared/meta-data.js"; +import { ownerCandidateKeys, RefOverDropError, splitChildTail } from "../naming-refs.js"; +import { CHILD_REF_SEPARATOR, PACKAGE_SEPARATOR } from "../shared/structural.js"; +import { TYPE_OBJECT } from "../shared/base-types.js"; +import type { ReferenceFacet, ReferenceMatch, SymbolTable } from "../validation-types.js"; + +/** Children of one node grouped by name, in child order (ADR-0039: resolving). */ +type ChildIndex = Map; + +export class SymbolTableImpl implements SymbolTable { + /** Top-level nodes per type, keyed by resolution key. Indexed PER TYPE so a + * reference can target a non-`object` node kind and so a template and an object + * sharing `pkg::Name` never collide. */ + private readonly byType = new Map>(); + /** Every top-level node by resolution key, of any type: the owner of a dotted path + * matches by name of any type, and two of different types under one key are + * ambiguous. */ + private readonly byKey = new Map(); + /** Per-node child index, built the first time a lookup steps into the node. */ + private readonly childIndexes = new Map(); + + private constructor(private readonly root: MetaData) {} + + static build(root: MetaData): SymbolTableImpl { + const t = new SymbolTableImpl(root); + // ADR-0039: root has no super; children()==ownChildren() but resolving is the default. + for (const child of root.children()) { + let bucket = t.byType.get(child.type); + if (bucket === undefined) { + bucket = new Map(); + t.byType.set(child.type, bucket); + } + // ADR-0042: key by the canonical resolution key ONLY (the FQN, or the bare + // name for a root-level/empty-package object) — NO bare-name fallback, so a + // bare ref never binds a same-named node in another package. + const key = child.resolutionKey(); + bucket.set(key, child); + const all = t.byKey.get(key); + if (all === undefined) t.byKey.set(key, [child]); + else all.push(child); + } + return t; + } + + /** ADR-0059 R2 resolution within the `type` bucket: `::Rest` root-absolute, + * `..::Rest` parent-relative, `pkg::Name` exact, bare `Name` in the referrer's own + * package then root-level. Exact keys only. An over-dropping `..::` resolves to + * nothing here; the walk reports it as ERR_BAD_ATTR_VALUE. */ + resolve(type: string, ref: string, referrerPkg: string): MetaData | undefined { + const bucket = this.byType.get(type); + if (bucket === undefined) return undefined; + let keys: readonly string[]; + try { + keys = ownerCandidateKeys(ref, referrerPkg); + } catch (e) { + if (e instanceof RefOverDropError) return undefined; + throw e; + } + for (const key of keys) { + const hit = bucket.get(key); + if (hit !== undefined) return hit; + } + return undefined; + } + + resolveObject(ref: string, referrerPkg: string): MetaData | undefined { + return this.resolve(TYPE_OBJECT, ref, referrerPkg); + } + + lookup(referrer: MetaData, value: string, facet: ReferenceFacet, referrerPkg: string): ReferenceMatch { + // A `fieldPath` value is `Target.field`: only the top-level `Target` is resolved. + const ref = facet.fieldPath === true ? splitChildTail(value).owner : value; + try { + ownerCandidateKeys(splitChildTail(ref).owner, referrerPkg); + } catch (e) { + if (e instanceof RefOverDropError) return { overDrop: true }; + throw e; + } + const target = this.find(referrer, ref, facet.targetType, referrerPkg); + if (target !== undefined) return { target }; + // Rule 6: the untyped lookup, along the same order, only picks the error code. + const wrongKind = this.find(referrer, ref, undefined, referrerPkg); + return wrongKind !== undefined ? { wrongKind } : {}; + } + + /** The node `ref` names whose final segment is of `type` (any type when undefined). */ + private find( + referrer: MetaData, + ref: string, + type: string | undefined, + referrerPkg: string, + ): MetaData | undefined { + const { owner, tail } = splitChildTail(ref); + if (tail === "") { + // Rule 4: a bare value is looked for among the children of each container of + // the referrer, nearest first, up to and including its top-level node. + if (!owner.includes(PACKAGE_SEPARATOR)) { + for (let c = referrer.parent; c !== undefined && c !== this.root; c = c.parent) { + const hit = this.childNamed(c, owner, type); + if (hit !== undefined) return hit; + } + } + return this.topLevel(owner, type, referrerPkg); + } + // Rule 3: `Owner.child[.grand]` — the owner by its form, then each segment by name. + const path = tail.slice(CHILD_REF_SEPARATOR.length).split(CHILD_REF_SEPARATOR); + if (path.some((p) => p === "")) return undefined; + let current = this.topLevel(owner, undefined, referrerPkg); + // Rule 2: an intermediate segment matches a child by name, of any type; two + // children sharing the name make the step ambiguous. + for (let i = 0; current !== undefined && i < path.length - 1; i++) { + const named = this.childIndex(current).get(path[i]!) ?? []; + current = named.length === 1 ? named[0] : undefined; + } + if (current === undefined) return undefined; + // Rule 1: the final segment is typed. + return this.childNamed(current, path[path.length - 1]!, type); + } + + /** A top-level node by ADR-0059 R2 form: of `type`, or — untyped — the one node + * under the first key that has any (two of different types are ambiguous). */ + private topLevel(owner: string, type: string | undefined, referrerPkg: string): MetaData | undefined { + if (type !== undefined) return this.resolve(type, owner, referrerPkg); + let keys: readonly string[]; + try { + keys = ownerCandidateKeys(owner, referrerPkg); + } catch (e) { + if (e instanceof RefOverDropError) return undefined; + throw e; + } + for (const key of keys) { + const hits = this.byKey.get(key); + if (hits !== undefined) return hits.length === 1 ? hits[0] : undefined; + } + return undefined; + } + + /** The first child of `parent` named `name`, of `type` when given. */ + private childNamed(parent: MetaData, name: string, type: string | undefined): MetaData | undefined { + const named = this.childIndex(parent).get(name); + if (named === undefined) return undefined; + return type === undefined ? named[0] : named.find((c) => c.type === type); + } + + private childIndex(parent: MetaData): ChildIndex { + let index = this.childIndexes.get(parent); + if (index === undefined) { + index = new Map(); + // ADR-0039: resolving — a child inherited through `extends` is addressable too. + for (const child of parent.children()) { + const list = index.get(child.name); + if (list === undefined) index.set(child.name, [child]); + else list.push(child); + } + this.childIndexes.set(parent, index); + } + return index; + } +} diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 2d6d235d0e..170e549848 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -3374,7 +3374,7 @@ function formatReferenceCandidates(candidates: readonly MetaReferenceIdentity[]) } // NOTE: identity.reference @references resolution moved to the validation registry -// (defaultValidationRegistry → a declarative reference descriptor with dottedFieldPath). +// (defaultValidationRegistry → a declarative reference descriptor with fieldPath). // --------------------------------------------------------------------------- // Index-key resolution for index.lookup AND identity.secondary (#342) diff --git a/server/typescript/packages/metadata/src/loader/validation-registry.ts b/server/typescript/packages/metadata/src/loader/validation-registry.ts index be619b9987..284c459ee6 100644 --- a/server/typescript/packages/metadata/src/loader/validation-registry.ts +++ b/server/typescript/packages/metadata/src/loader/validation-registry.ts @@ -8,65 +8,18 @@ import type { MetaData } from "../shared/meta-data.js"; import { ParseError } from "../errors.js"; +import { didYouMeanHint, referrerPackageFor } from "../naming-refs.js"; +import { TYPE_OBJECT, TYPE_SYSTEM } from "../shared/base-types.js"; +import type { TypeDefinition, TypeRegistry } from "../registry.js"; import { - didYouMeanHint, - ownerCandidateKeys, - referrerPackageFor, - RefOverDropError, -} from "../naming-refs.js"; -import { TYPE_OBJECT } from "../shared/base-types.js"; -import type { TypeRegistry } from "../registry.js"; -import type { LoaderCode, SymbolTable, ValidationContext } from "../validation-types.js"; - -/** A symbol table of every top-level node, built once per load (the binder analogue). - * Indexed PER TYPE so a reference descriptor can target a non-`object` node kind (its - * `targetType` is a free string) and so a template and an object sharing `pkg::Name` - * never collide. */ -class SymbolTableImpl implements SymbolTable { - private readonly byType = new Map>(); - - static build(root: MetaData): SymbolTableImpl { - const t = new SymbolTableImpl(); - // ADR-0039: root has no super; children()==ownChildren() but resolving is the default. - for (const child of root.children()) { - let bucket = t.byType.get(child.type); - if (bucket === undefined) { - bucket = new Map(); - t.byType.set(child.type, bucket); - } - // ADR-0042: key by the canonical resolution key ONLY (the FQN, or the bare - // name for a root-level/empty-package object) — NO bare-name fallback, so a - // bare ref never binds a same-named node in another package. - bucket.set(child.resolutionKey(), child); - } - return t; - } - - /** ADR-0059 R2 resolution within the `type` bucket: `::Rest` root-absolute, - * `..::Rest` parent-relative, `pkg::Name` exact, bare `Name` in the referrer's own - * package then root-level. Exact keys only. An over-dropping `..::` resolves to - * nothing here; the walk reports it as ERR_BAD_ATTR_VALUE. */ - resolve(type: string, ref: string, referrerPkg: string): MetaData | undefined { - const bucket = this.byType.get(type); - if (bucket === undefined) return undefined; - let keys: readonly string[]; - try { - keys = ownerCandidateKeys(ref, referrerPkg); - } catch (e) { - if (e instanceof RefOverDropError) return undefined; - throw e; - } - for (const key of keys) { - const hit = bucket.get(key); - if (hit !== undefined) return hit; - } - return undefined; - } - - resolveObject(ref: string, referrerPkg: string): MetaData | undefined { - return this.resolve(TYPE_OBJECT, ref, referrerPkg); - } -} + REF_UNRESOLVED_CODE, + REF_WRONG_KIND_CODE, + type LoaderCode, + type ReferenceDescriptor, + type SymbolTable, + type ValidationContext, +} from "../validation-types.js"; +import { SymbolTableImpl } from "./symbol-table.js"; class ValidationContextImpl implements ValidationContext { readonly errors: ParseError[] = []; @@ -83,9 +36,106 @@ class ValidationContextImpl implements ValidationContext { */ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): ParseError[] { const ctx = new ValidationContextImpl(SymbolTableImpl.build(root)); + const descriptorCache = new Map(); walk(root, "", false); return ctx.errors; + /** A type's references: the descriptors set in code plus every attribute (its own + * and the common ones) whose schema carries the reference facet. */ + function descriptorsOf(def: TypeDefinition): readonly ReferenceDescriptor[] { + let out = descriptorCache.get(def); + if (out === undefined) { + out = [...(def.references ?? []), ...referenceAttrDescriptors(def, registry)]; + descriptorCache.set(def, out); + } + return out; + } + + /** Enforce one reference attribute on `node`, every value of it when it is a list + * (spec/metamodel-definitions.md, "What the loader checks, in order"). */ + function checkReference(node: MetaData, desc: ReferenceDescriptor): void { + // ADR-0039: resolving — a reference attr (e.g. @objectRef/@through) may be + // inherited via extends; read the effective value. + const raw = node.attr(desc.attr); + const values = + typeof raw === "string" + ? [raw] + : Array.isArray(raw) + ? raw.filter((v): v is string => typeof v === "string") + : []; + // ADR-0059 R3: an inherited reference resolves in the package of the + // top-level node that physically declares it, not the inheritor's. + const refPkg = referrerPackageFor(node, desc.attr); + // Qualify the node name with its owning entity (e.g. "Order.items") so the error is + // locatable from the message alone, not just the source envelope. + const qname = node.parent?.name ? `${node.parent.name}.${node.name}` : node.name; + const label = (value: string): string => `${node.type}.${node.subType} "${qname}" @${desc.attr} "${value}"`; + const wantKind = + desc.targetSubTypes === undefined + ? desc.targetType === TYPE_OBJECT + ? "an object" + : `a ${desc.targetType}` + : desc.targetSubTypes.map((s) => `${desc.targetType}.${s}`).join(" or "); + for (const value of values) { + if (value === "") continue; // absence is the required-attr pass's job + const found = ctx.symbols.lookup(node, value, desc, refPkg); + if (found.overDrop === true) { + ctx.error( + "ERR_BAD_ATTR_VALUE", + node, + `${label(value)} climbs above the root package — each '..::' drops one segment of the declaring package.`, + ); + continue; + } + const target = found.target; + if (target === undefined) { + if (found.wrongKind !== undefined) { + const w = found.wrongKind; + ctx.error( + desc.errorCode ?? REF_WRONG_KIND_CODE, + node, + `${label(value)} names ${w.type}.${w.subType} "${w.name}", not ${wantKind}.`, + ); + continue; + } + // `did-you-mean` is object-scoped (its candidate scan is over objects), so only + // append it for object targets; a non-object target names its own kind. + const entityRef = desc.fieldPath === true ? (value.split(".")[0] ?? value) : value; + const hint = desc.targetType === TYPE_OBJECT ? didYouMeanHint(root, entityRef) : ""; + ctx.error( + desc.errorCode ?? REF_UNRESOLVED_CODE, + node, + `${label(value)} does not resolve to ${wantKind}.${hint}`, + ); + continue; + } + if (desc.targetSubTypes !== undefined && !desc.targetSubTypes.includes(target.subType)) { + // The typed lookup already guarantees target.type === desc.targetType; only the + // subType can still mismatch. + ctx.error( + desc.errorCode ?? REF_WRONG_KIND_CODE, + node, + `${label(value)} resolves to ${target.type}.${target.subType}, not ${wantKind}.`, + ); + continue; + } + if (desc.sameSystem === true) { + const mine = systemOf(node); + const theirs = systemOf(target); + if (mine === undefined || mine !== theirs) { + const where = theirs === undefined ? "no system" : `system "${theirs.resolutionKey()}"`; + const from = mine === undefined ? "a node outside any system" : `system "${mine.resolutionKey()}"`; + ctx.error( + desc.wrongSystemCode ?? REF_WRONG_KIND_CODE, + node, + `${label(value)} resolves to ${target.type}.${target.subType} "${target.name}" in ${where}, ` + + `but it must be in the same system as the declaring node, which is in ${from}.`, + ); + } + } + } + } + function walk(node: MetaData, referrerPkg: string, isTopLevel: boolean): void { // ADR-0042: a TOP-LEVEL node establishes the package context for its subtree; // nested ref-bearing nodes (relationship/field.object/identity.reference) resolve @@ -102,52 +152,7 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): : referrerPkg; const def = registry.find(node.type, node.subType); if (def) { - for (const desc of def.references ?? []) { - // ADR-0039: resolving — a reference attr (e.g. @objectRef/@through) may be - // inherited via extends; read the effective value. - const raw = node.attr(desc.attr); - if (typeof raw !== "string" || raw === "") continue; // absence is the required-attr pass's job - const entityRef = desc.dottedFieldPath ? (raw.split(".")[0] ?? raw) : raw; - // ADR-0059 R3: an inherited reference resolves in the package of the - // top-level node that physically declares it, not the inheritor's. - const refPkg = referrerPackageFor(node, desc.attr); - try { - ownerCandidateKeys(entityRef, refPkg); - } catch (e) { - if (!(e instanceof RefOverDropError)) throw e; - ctx.error( - "ERR_BAD_ATTR_VALUE", - node, - `${node.type}.${node.subType} "${node.name}" @${desc.attr} "${raw}" climbs above the root package — each '..::' drops one segment of the declaring package.`, - ); - continue; - } - const target = ctx.symbols.resolve(desc.targetType, entityRef, refPkg); - // Qualify the node name with its owning entity (e.g. "Order.items") so the error is - // locatable from the message alone, not just the source envelope. - const qname = node.parent?.name ? `${node.parent.name}.${node.name}` : node.name; - if (!target) { - // `did-you-mean` is object-scoped (its candidate scan is over objects), so only - // append it for object targets; a non-object target names its own kind. - const wantKind = desc.targetType === TYPE_OBJECT ? "an object" : `a ${desc.targetType}`; - const hint = desc.targetType === TYPE_OBJECT ? didYouMeanHint(root, entityRef) : ""; - ctx.error( - desc.errorCode, - node, - `${node.type}.${node.subType} "${qname}" @${desc.attr} "${raw}" does not resolve to ${wantKind}.${hint}`, - ); - } else if (desc.targetSubType !== undefined && target.subType !== desc.targetSubType) { - // `resolve` already guarantees target.type === desc.targetType; only the - // subType can still mismatch. - const want = `${desc.targetType}.${desc.targetSubType}`; - ctx.error( - desc.errorCode, - node, - `${node.type}.${node.subType} "${qname}" @${desc.attr} "${raw}" resolves to ` + - `${target.type}.${target.subType}, not a ${want}.`, - ); - } - } + for (const desc of descriptorsOf(def)) checkReference(node, desc); def.validate?.(node, ctx); } // ADR-0039: own — structural walk visiting every physical node once at its @@ -158,3 +163,24 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): for (const child of node.ownChildren()) walk(child, pkg, childrenAreTopLevel); } } + +/** Reference descriptors for every attribute of `def` (and every common attribute) + * whose schema carries the reference facet (spec/metamodel-definitions.md). */ +function referenceAttrDescriptors(def: TypeDefinition, registry: TypeRegistry): ReferenceDescriptor[] { + const out: ReferenceDescriptor[] = []; + const seen = new Set(); + for (const attr of [...def.attributes, ...registry.getCommonAttrs()]) { + if (attr.ref === undefined || seen.has(attr.name)) continue; + seen.add(attr.name); + out.push({ attr: attr.name, ...attr.ref }); + } + return out; +} + +/** The system of a node: its nearest ancestor, or itself, of type `system`. */ +function systemOf(node: MetaData): MetaData | undefined { + for (let n: MetaData | undefined = node; n !== undefined; n = n.parent) { + if (n.type === TYPE_SYSTEM) return n; + } + return undefined; +} diff --git a/server/typescript/packages/metadata/src/provider-data.ts b/server/typescript/packages/metadata/src/provider-data.ts index 79da270a71..495f415e1f 100644 --- a/server/typescript/packages/metadata/src/provider-data.ts +++ b/server/typescript/packages/metadata/src/provider-data.ts @@ -18,7 +18,8 @@ import type { AttrValue, MetaData } from "./shared/meta-data.js"; import type { DataType } from "./data-type.js"; import { CHILD_RULE_WILDCARD } from "./shared/structural.js"; import { SUBTYPE_BASE } from "./shared/base-types.js"; -import type { NodeValidator } from "./validation-types.js"; +import type { NodeValidator, ReferenceFacet } from "./validation-types.js"; +import { ATTR_SUBTYPE_STRING } from "./core/attr/attr-constants.js"; /** * A UNIFIED child requirement (spec §3.1). Every constraint on a type — both its @@ -73,6 +74,8 @@ export interface ChildDef { ports?: readonly string[]; /** The ports that implement this cross-port attr so far (`["java"]`); absent = every port. */ implementedIn?: readonly string[]; + /** The reference facet: what a reference attr's value may name (spec/metamodel-definitions.md). */ + ref?: ReferenceFacet; } /** @@ -496,6 +499,7 @@ function toAttrSchema(provider: string, typeKey: string, child: ChildDef): AttrS : {}), ...(child.ports !== undefined ? { ports: child.ports } : {}), ...(child.implementedIn !== undefined ? { implementedIn: child.implementedIn } : {}), + ...(child.ref !== undefined ? { ref: toReferenceFacet(provider, typeKey, child) } : {}), description: child.description ?? "", ...(child.rules !== undefined ? { rules: child.rules } : {}), ...(child.example !== undefined ? { example: child.example } : {}), @@ -503,6 +507,60 @@ function toAttrSchema(provider: string, typeKey: string, child: ChildDef): AttrS }; } +/** A loader error code, as a facet names one. */ +const LOADER_CODE = /^ERR_[A-Z0-9_]+$/; + +/** + * Read an attr entry's reference facet, refusing a facet the format does not allow + * (spec/metamodel-definitions.md, "The reference facet"; the JSON schema states the + * same rules). Copies only the keys the format defines, in its order. + */ +function toReferenceFacet(provider: string, typeKey: string, child: ChildDef): ReferenceFacet { + const ref = child.ref as unknown; + const where = `defineProviderFromData(${provider}): attr "${child.name}" on "${typeKey}"`; + const fail = (why: string): never => { + throw new Error(`${where} has an invalid reference facet: ${why}.`); + }; + if (typeof ref !== "object" || ref === null || Array.isArray(ref)) return fail("ref must be an object"); + const r = ref as Record; + const known = new Set(["targetType", "targetSubTypes", "fieldPath", "sameSystem", "errorCode", "wrongSystemCode"]); + for (const key of Object.keys(r)) if (!known.has(key)) fail(`unknown key "${key}"`); + if (child.subType !== ATTR_SUBTYPE_STRING) fail(`only a string attr may be a reference (this one is "${String(child.subType)}")`); + const { targetType, targetSubTypes, fieldPath, sameSystem, errorCode, wrongSystemCode } = r; + if (typeof targetType !== "string" || targetType === "" || targetType === CHILD_RULE_WILDCARD) { + fail("targetType must name one type, never \"*\""); + } + if (targetSubTypes !== undefined) { + if ( + !Array.isArray(targetSubTypes) || + targetSubTypes.length === 0 || + targetSubTypes.some((s) => typeof s !== "string" || s === "" || s === CHILD_RULE_WILDCARD) || + new Set(targetSubTypes).size !== targetSubTypes.length + ) { + fail("targetSubTypes must be a non-empty list of distinct subtype names, never \"*\""); + } + } + if (fieldPath !== undefined && typeof fieldPath !== "boolean") fail("fieldPath must be a boolean"); + if (sameSystem !== undefined && typeof sameSystem !== "boolean") fail("sameSystem must be a boolean"); + if (fieldPath === true && sameSystem === true) fail("fieldPath and sameSystem cannot both be true"); + for (const [key, code] of [["errorCode", errorCode], ["wrongSystemCode", wrongSystemCode]] as const) { + if (code !== undefined && (typeof code !== "string" || !LOADER_CODE.test(code))) { + fail(`${key} must be a loader code (ERR_ and upper case)`); + } + } + if ((sameSystem === true) !== (wrongSystemCode !== undefined)) { + fail("wrongSystemCode is present exactly when sameSystem is true"); + } + return { + targetType: targetType as string, + ...(targetSubTypes !== undefined ? { targetSubTypes: [...(targetSubTypes as string[])] } : {}), + ...(fieldPath !== undefined ? { fieldPath: fieldPath as boolean } : {}), + ...(sameSystem !== undefined ? { sameSystem: sameSystem as boolean } : {}), + ...(errorCode !== undefined ? { errorCode: errorCode as string } : {}), + ...(wrongSystemCode !== undefined ? { wrongSystemCode: wrongSystemCode as string } : {}), + }; +} + /** A structural (`type !== "attr"`) child entry IS a `ChildRule`. */ function toChildRule(child: ChildDef): ChildRule { return { diff --git a/server/typescript/packages/metadata/src/registry-manifest.ts b/server/typescript/packages/metadata/src/registry-manifest.ts index 5b22d5ecb2..51eab8d304 100644 --- a/server/typescript/packages/metadata/src/registry-manifest.ts +++ b/server/typescript/packages/metadata/src/registry-manifest.ts @@ -28,6 +28,7 @@ // (the intended intermediate state, same as the FR-032 sweep). import type { AttrSchema, ChildRule, TypeDefinition, TypeRegistry } from "./registry.js"; +import type { ReferenceFacet } from "./validation-types.js"; import { ATTR_SUBTYPE_STRING, ATTR_SUBTYPE_STRINGARRAY } from "./core/attr/attr-constants.js"; import { EXCLUDED_PER_TYPE_ATTRS, @@ -56,6 +57,8 @@ export interface ManifestAttr { implementedIn?: readonly string[]; /** The ports that act on a language-specific attr, sorted. Emitted ONLY when the attr names them. */ ports?: readonly string[]; + /** The reference facet (spec/metamodel-definitions.md). Emitted ONLY when the attr has one. */ + ref?: ManifestRef; /** FR-033 — human/AI-facing description of the attribute (required, non-empty). */ description: string; /** FR-033 — prose documenting the complex rules enforced in code. Emitted only when present. */ @@ -66,6 +69,21 @@ export interface ManifestAttr { whenToUse?: string; } +/** + * An attr's reference facet in the manifest. Key order is fixed: `targetType`, then + * `targetSubTypes` (sorted), `fieldPath` and `sameSystem` (each only when true), + * `errorCode`, `wrongSystemCode` (each only when present). An absent key is the + * facet's default, so two ports that read the same facet write the same bytes. + */ +export interface ManifestRef { + targetType: string; + targetSubTypes?: readonly string[]; + fieldPath?: true; + sameSystem?: true; + errorCode?: string; + wrongSystemCode?: string; +} + /** One structural child rule of a type (FR-033 constraint graph). */ export interface ManifestChild { /** The admitted child `type` (`"*"` = any). */ @@ -176,6 +194,7 @@ function toManifestAttr(attr: AttrSchema): ManifestAttr { ? { implementedIn: [...attr.implementedIn].sort(compareStrings) } : {}), ...(attr.ports !== undefined && attr.ports.length > 0 ? { ports: [...attr.ports].sort(compareStrings) } : {}), + ...(attr.ref !== undefined ? { ref: toManifestRef(attr.ref) } : {}), description: attr.description, }; if (attr.rules !== undefined) out.rules = attr.rules; @@ -184,6 +203,18 @@ function toManifestAttr(attr: AttrSchema): ManifestAttr { return out; } +/** The manifest form of a reference facet: defaults omitted, fixed key order. */ +function toManifestRef(ref: ReferenceFacet): ManifestRef { + return { + targetType: ref.targetType, + ...(ref.targetSubTypes !== undefined ? { targetSubTypes: [...ref.targetSubTypes].sort(compareStrings) } : {}), + ...(ref.fieldPath === true ? { fieldPath: true as const } : {}), + ...(ref.sameSystem === true ? { sameSystem: true as const } : {}), + ...(ref.errorCode !== undefined ? { errorCode: ref.errorCode } : {}), + ...(ref.wrongSystemCode !== undefined ? { wrongSystemCode: ref.wrongSystemCode } : {}), + }; +} + /** The canonical sort key for a child rule: childType, then the childSubType * string (or comma-joined list), then childName — ASCII codepoint compare. */ function childSubTypeKey(childSubType: string | readonly string[]): string { diff --git a/server/typescript/packages/metadata/src/registry.ts b/server/typescript/packages/metadata/src/registry.ts index cf03d751ba..7e94e5e7fb 100644 --- a/server/typescript/packages/metadata/src/registry.ts +++ b/server/typescript/packages/metadata/src/registry.ts @@ -3,7 +3,7 @@ import { SUBTYPE_BASE, TYPE_ATTR } from "./shared/base-types.js"; import { CHILD_RULE_WILDCARD } from "./shared/structural.js"; import { type AttrSubType } from "./core/attr/attr-constants.js"; import type { DataType } from "./data-type.js"; -import type { ReferenceDescriptor, NodeValidator } from "./validation-types.js"; +import type { ReferenceDescriptor, ReferenceFacet, NodeValidator } from "./validation-types.js"; import { MetaModelError } from "./errors.js"; export class TypeId { @@ -97,6 +97,11 @@ export interface AttrSchema { example?: string; /** FR-033 — guidance on when to reach for this attribute. Optional. */ whenToUse?: string; + /** + * The reference facet (spec/metamodel-definitions.md): present when the attribute's + * value names another node, and says what that node must be. The loader enforces it. + */ + ref?: ReferenceFacet; } export interface TypeDefinition { diff --git a/server/typescript/packages/metadata/src/shared/base-types.ts b/server/typescript/packages/metadata/src/shared/base-types.ts index 999789a608..94d2be295b 100644 --- a/server/typescript/packages/metadata/src/shared/base-types.ts +++ b/server/typescript/packages/metadata/src/shared/base-types.ts @@ -35,6 +35,12 @@ export const TYPE_OPERATION = "operation"; export const TYPE_BINDING = "binding"; /** ADR-0066 — an allowed move between two members of a `field.enum` (`transition.action`). */ export const TYPE_TRANSITION = "transition"; +/** + * ADR-0070 — the `system` type. Not a registered base type yet (core registers it in + * 1.4.0, so it is not in BASE_TYPES): the reference facet's `sameSystem` check reads it + * to find a node's system, its nearest ancestor of this type. + */ +export const TYPE_SYSTEM = "system"; export const BASE_TYPES = [ TYPE_METADATA, diff --git a/server/typescript/packages/metadata/src/validation-types.ts b/server/typescript/packages/metadata/src/validation-types.ts index 8b9a4d028a..8d58db7218 100644 --- a/server/typescript/packages/metadata/src/validation-types.ts +++ b/server/typescript/packages/metadata/src/validation-types.ts @@ -12,22 +12,51 @@ import type { ErrorCode } from "./errors.js"; export type LoaderCode = ErrorCode | (string & {}); /** - * Declares that one attribute on a node is a cross-reference to another node. A provider - * attaches these to its TypeDefinition; the generic resolver enforces them against the - * symbol table — so a new reference attr validates for free, present and future. + * The reference facet (spec/metamodel-definitions.md, "The reference facet"): what a + * reference attribute may point at. A provider definition carries it as `ref` on a + * `type: "attr"` child; the spec reader lowers it onto the attribute's `AttrSchema`, + * and the loader enforces it with no code per provider. */ -export interface ReferenceDescriptor { +export interface ReferenceFacet { + /** The type the value must resolve to. Never `*`. */ + readonly targetType: string; + /** The subtypes of `targetType` the value may resolve to. Absent: any. Never empty. */ + readonly targetSubTypes?: readonly string[]; + /** The value is `Target.field`: only `Target` is resolved, and it is top-level. */ + readonly fieldPath?: boolean; + /** The target must be in the same system as the node that declares the attribute. */ + readonly sameSystem?: boolean; + /** Raised when the value does not resolve or resolves to the wrong kind. Absent: + * `ERR_REF_UNRESOLVED` and `ERR_REF_WRONG_KIND`. */ + readonly errorCode?: LoaderCode; + /** Raised when `sameSystem` fails. Present exactly when `sameSystem` is true. */ + readonly wrongSystemCode?: LoaderCode; +} + +/** The code a facet with no `errorCode` raises when its value names no node. */ +export const REF_UNRESOLVED_CODE = "ERR_REF_UNRESOLVED"; +/** The code a facet with no `errorCode` raises when its value names a node of the wrong kind. */ +export const REF_WRONG_KIND_CODE = "ERR_REF_WRONG_KIND"; + +/** + * Declares that one attribute on a node is a cross-reference to another node: the + * attribute name plus its reference facet. A provider either attaches these to its + * TypeDefinition in code, or (the data form) sets `ref` on the attribute in its + * definition file; the generic resolver enforces both against the symbol table — so a + * new reference attr validates for free, present and future. + */ +export interface ReferenceDescriptor extends ReferenceFacet { /** Attr name carrying the reference value (e.g. "objectRef", "references"). */ readonly attr: string; - /** Required resolved-node type (e.g. "object"). */ - readonly targetType: string; - /** Required resolved-node subType (e.g. "value" for a payload ref), or any. */ - readonly targetSubType?: string; - /** When true the value is `Entity.field`; resolve the entity segment (before the - * first ".", since packages use "::"). */ - readonly dottedFieldPath?: boolean; - /** Code emitted on unresolved / kind-mismatch (may be a downstream code). */ - readonly errorCode: LoaderCode; +} + +/** What one reference value names: the target, or the wrong-kind node the untyped + * lookup found instead, or neither. `overDrop` marks a `..::` that climbs above the + * root package. */ +export interface ReferenceMatch { + readonly target?: MetaData; + readonly wrongKind?: MetaData; + readonly overDrop?: boolean; } /** Resolve a ref string to a top-level node under the ADR-0042 package-local @@ -45,6 +74,14 @@ export interface SymbolTable { resolve(type: string, ref: string, referrerPkg: string): MetaData | undefined; /** The common case — an `object`-target reference. Delegates to `resolve("object", …)`. */ resolveObject(ref: string, referrerPkg: string): MetaData | undefined; + /** + * Look up one reference value under a facet (spec/metamodel-definitions.md, "How a + * reference is looked up"): kind-typed final segment, `System.child` and + * `pkg::System.child` paths, a bare value found in the referrer's own containers + * first, and an untyped second lookup that only tells "wrong kind" from "unresolved". + * `referrer` is the node that carries the attribute; `referrerPkg` its R3 package. + */ + lookup(referrer: MetaData, value: string, facet: ReferenceFacet, referrerPkg: string): ReferenceMatch; } /** Handed to every validator: the symbol table + an error sink. */ diff --git a/server/typescript/packages/metadata/test/reference-facet.test.ts b/server/typescript/packages/metadata/test/reference-facet.test.ts new file mode 100644 index 0000000000..1476ac0169 --- /dev/null +++ b/server/typescript/packages/metadata/test/reference-facet.test.ts @@ -0,0 +1,325 @@ +// The reference facet (spec/metamodel-definitions.md): the spec reader carries `ref` on +// an attr entry, the loader's generic resolver enforces it, the symbol table resolves +// `System.child` and `pkg::System.child`, the lookup is kind-typed, and the registry +// manifest writes the facet only when an attr has one. +// +// No shipped definition file uses the facet yet, so these tests compose a test provider +// with a small system vocabulary of their own. + +import { describe, it, expect } from "bun:test"; +import { MetaDataLoader } from "../src/loader/meta-data-loader.js"; +import { InMemoryStringSource } from "../src/loader/meta-data-source.js"; +import { composeRegistry, type MetaDataTypeProvider } from "../src/provider.js"; +import { coreProviders } from "../src/core-types.js"; +import { + applyProviderDefinition, + defineProviderFromData, + type ChildDef, + type FactoryMap, + type ProviderDefinition, +} from "../src/provider-data.js"; +import { TypeId, type TypeRegistry } from "../src/registry.js"; +import { MetaData } from "../src/shared/meta-data.js"; +import { buildRegistryManifest, emitRegistryManifest } from "../src/registry-manifest.js"; +import { refTarget } from "../src/naming-refs.js"; +import type { ReferenceFacet } from "../src/validation-types.js"; + +class SystemTestNode extends MetaData {} + +const attr = (name: string, extra: Partial = {}): ChildDef => ({ + type: "attr", + subType: "string", + name, + min: 0, + max: 1, + description: `Test attribute ${name}.`, + ...extra, +}); + +const any = (type: string): ChildDef => ({ type, subType: "*", name: "*", min: 0, max: null }); + +/** A test vocabulary: systems holding apps, roles and resources, with references. */ +const DEFINITION: ProviderDefinition = { + provider: "test-reference-facet", + types: [ + { + type: "system", + subType: "software", + description: "A test system.", + children: [any("app"), any("role"), any("resource")], + }, + { + type: "app", + subType: "service", + description: "A test app.", + children: [ + attr("runsAs", { ref: { targetType: "role", sameSystem: true, wrongSystemCode: "ERR_RUNSAS_OTHER_SYSTEM" } }), + attr("calls", { isArray: true, max: 1, ref: { targetType: "app" } }), + ], + }, + { + type: "role", + subType: "service", + description: "A test role.", + children: [any("grant")], + }, + { + type: "grant", + subType: "rdb", + description: "A test grant.", + children: [ + attr("resource", { + ref: { + targetType: "resource", + targetSubTypes: ["rdb"], + sameSystem: true, + wrongSystemCode: "ERR_GRANT_CROSSES_SYSTEM", + }, + }), + ], + }, + { type: "resource", subType: "rdb", description: "A test database." }, + { type: "resource", subType: "queue", description: "A test queue." }, + { + type: "deployment", + subType: "test", + description: "A test deployment, outside any system.", + children: [ + attr("app", { ref: { targetType: "app" } }), + attr("anyRole", { ref: { targetType: "role", errorCode: "ERR_TEST_ROLE" } }), + attr("pinnedRole", { ref: { targetType: "role", sameSystem: true, wrongSystemCode: "ERR_TEST_OUTSIDE" } }), + ], + }, + ], + extends: [ + { + type: "metadata", + subType: "root", + children: [any("system"), any("deployment")], + }, + ], +}; + +const FACTORIES: FactoryMap = Object.fromEntries( + (DEFINITION.types ?? []).map((t) => [ + `${t.type}.${t.subType}`, + (typeId: TypeId, name: string) => new SystemTestNode(typeId, name), + ]), +); + +const testProvider: MetaDataTypeProvider = { + id: "test-reference-facet", + description: "Test vocabulary for the reference facet.", + registerTypes(registry: TypeRegistry): void { + applyProviderDefinition(registry, DEFINITION, FACTORIES); + }, +}; + +async function load(yaml: string) { + const registry = composeRegistry([...coreProviders, testProvider]); + const loader = new MetaDataLoader({ registry, strict: true }); + const { root, errors } = await loader.load([ + new InMemoryStringSource(yaml, { id: "systems.yaml", format: "yaml" }), + ]); + return { + root, + errors: errors.map((e) => ({ code: (e as { code?: string }).code, message: e.message })), + }; +} + +const codes = (errors: readonly { code: string | undefined }[]) => errors.map((e) => e.code); + +/** Two systems in package `acme`: Parcels (an app and a role both named `api`) and Ledger. */ +const MODEL = (parcelsExtra: string, outside = "") => ` +metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - resource.rdb: { name: db } + - resource.queue: { name: jobs } + - role.service: + name: api + children: + - grant.rdb: { name: g1, resource: db } + - app.service: + name: api + runsAs: api +${parcelsExtra} + - system.software: + name: Ledger + children: + - resource.rdb: { name: books } + - role.service: { name: clerk } + - app.service: { name: web, runsAs: clerk } +${outside} +`; + +describe("reference facet — the spec reader", () => { + it("lowers `ref` onto the attribute's schema", () => { + const defs = defineProviderFromData(DEFINITION, FACTORIES); + const grant = defs.find((d) => d.typeId.type === "grant")!; + expect(grant.attributes.find((a) => a.name === "resource")!.ref).toEqual({ + targetType: "resource", + targetSubTypes: ["rdb"], + sameSystem: true, + wrongSystemCode: "ERR_GRANT_CROSSES_SYSTEM", + }); + }); + + const refuse = (ref: unknown, subType = "string") => () => + defineProviderFromData( + { + provider: "bad", + types: [ + { + type: "widget", + subType: "x", + description: "x", + children: [attr("to", { subType, ref: ref as ReferenceFacet })], + }, + ], + }, + { "widget.x": (typeId, name) => new SystemTestNode(typeId, name) }, + ); + + it("refuses a facet the format does not allow", () => { + expect(refuse({ targetType: "role" }, "int")).toThrow(/only a string attr/); + expect(refuse({ targetType: "*" })).toThrow(/targetType/); + expect(refuse({ targetType: "role", targetSubTypes: [] })).toThrow(/targetSubTypes/); + expect(refuse({ targetType: "role", targetSubTypes: ["*"] })).toThrow(/targetSubTypes/); + expect(refuse({ targetType: "role", sameSystem: true })).toThrow(/wrongSystemCode/); + expect(refuse({ targetType: "role", wrongSystemCode: "ERR_X" })).toThrow(/wrongSystemCode/); + expect(refuse({ targetType: "role", fieldPath: true, sameSystem: true, wrongSystemCode: "ERR_X" })).toThrow( + /fieldPath and sameSystem/, + ); + expect(refuse({ targetType: "role", errorCode: "bad" })).toThrow(/loader code/); + expect(refuse({ targetType: "role", targetSubType: "rdb" })).toThrow(/unknown key "targetSubType"/); + }); +}); + +describe("reference facet — the loader", () => { + it("a valid model loads clean: bare names find the referrer's own system first", async () => { + const { errors } = await load(MODEL("")); + expect(errors).toEqual([]); + }); + + it("a role and an app both named `api`: the lookup is kind-typed", async () => { + const { root, errors } = await load( + MODEL(` - app.service: { name: worker, runsAs: api, calls: [api, Parcels.api] }`), + ); + expect(errors).toEqual([]); + const parcels = root.children().find((c) => c.name === "Parcels")!; + const worker = parcels.children().find((c) => c.name === "worker")!; + // runsAs targets a role: the role `api`, not the app `api`. + const runsAs = refTarget(worker, "runsAs"); + expect(runsAs?.type).toBe("role"); + expect(worker.attr("runsAs")).toBe("acme::Parcels.api"); + // calls targets an app: both spellings bind the app `api`. + expect(worker.attr("calls")).toEqual(["acme::Parcels.api", "acme::Parcels.api"]); + }); + + it("unresolved: a value naming no node is ERR_REF_UNRESOLVED", async () => { + const { errors } = await load(MODEL(` - app.service: { name: worker, calls: [nobody] }`)); + expect(codes(errors)).toEqual(["ERR_REF_UNRESOLVED"]); + expect(errors[0]!.message).toContain(`@calls "nobody"`); + }); + + it("wrong kind: a value naming another type is ERR_REF_WRONG_KIND (normative case a)", async () => { + const { errors } = await load(MODEL(` - app.service: { name: worker, runsAs: db }`)); + expect(codes(errors)).toEqual(["ERR_REF_WRONG_KIND"]); + expect(errors[0]!.message).toContain("resource.rdb"); + }); + + it("unresolved: normative case b", async () => { + const { errors } = await load(MODEL(` - app.service: { name: worker, runsAs: nobody }`)); + expect(codes(errors)).toEqual(["ERR_REF_UNRESOLVED"]); + }); + + it("wrong subtype: a grant.rdb naming a resource.queue", async () => { + const { errors } = await load( + MODEL(` - role.service: + name: mover + children: + - grant.rdb: { name: g2, resource: jobs }`), + ); + expect(codes(errors)).toEqual(["ERR_REF_WRONG_KIND"]); + expect(errors[0]!.message).toContain("resource.queue"); + }); + + it("crosses system: a grant on another system's resource raises the facet's wrongSystemCode", async () => { + const { errors } = await load( + MODEL(` - role.service: + name: auditor + children: + - grant.rdb: { name: g3, resource: Ledger.books }`), + ); + expect(codes(errors)).toEqual(["ERR_GRANT_CROSSES_SYSTEM"]); + expect(errors[0]!.message).toContain(`system "acme::Ledger"`); + }); + + it("a facet's errorCode replaces both default codes", async () => { + const outside = ` - deployment.test: { name: d1, anyRole: Parcels.nobody } + - deployment.test: { name: d2, anyRole: Parcels.db }`; + const { errors } = await load(MODEL("", outside)); + expect(codes(errors)).toEqual(["ERR_TEST_ROLE", "ERR_TEST_ROLE"]); + }); + + it("`System.child` and `pkg::System.child` resolve from outside any system", async () => { + const outside = ` - deployment.test: { name: d1, app: Parcels.api, anyRole: acme::Ledger.clerk }`; + const { root, errors } = await load(MODEL("", outside)); + expect(errors).toEqual([]); + const d1 = root.children().find((c) => c.name === "d1")!; + expect(refTarget(d1, "app")?.type).toBe("app"); + expect(d1.attr("app")).toBe("acme::Parcels.api"); + expect(d1.attr("anyRole")).toBe("acme::Ledger.clerk"); + }); + + it("a bare value from outside a system does not see inside one", async () => { + const outside = ` - deployment.test: { name: d1, app: web }`; + const { errors } = await load(MODEL("", outside)); + expect(codes(errors)).toEqual(["ERR_REF_UNRESOLVED"]); + }); + + it("sameSystem from a node outside any system fails with wrongSystemCode", async () => { + const outside = ` - deployment.test: { name: d1, pinnedRole: Parcels.api }`; + const { errors } = await load(MODEL("", outside)); + expect(codes(errors)).toEqual(["ERR_TEST_OUTSIDE"]); + }); + + it("an intermediate segment shared by two children is ambiguous", async () => { + // `Parcels.api.g1`: `api` names both a role and an app under Parcels. + const outside = ` - deployment.test: { name: d1, app: Parcels.api.g1 }`; + const { errors } = await load(MODEL("", outside)); + expect(codes(errors)).toEqual(["ERR_REF_UNRESOLVED"]); + }); +}); + +describe("reference facet — the registry manifest", () => { + it("writes `ref` only on an attribute that has one, in the fixed key order", () => { + const registry = composeRegistry([...coreProviders, testProvider]); + const manifest = buildRegistryManifest(registry); + const grant = manifest.types.find((t) => t.type === "grant" && t.subType === "rdb")!; + const resource = grant.attrs.find((a) => a.name === "resource")!; + expect(Object.keys(resource)).toEqual(["name", "valueType", "isArray", "required", "ref", "description"]); + expect(JSON.stringify(resource.ref)).toBe( + JSON.stringify({ + targetType: "resource", + targetSubTypes: ["rdb"], + sameSystem: true, + wrongSystemCode: "ERR_GRANT_CROSSES_SYSTEM", + }), + ); + const deployment = manifest.types.find((t) => t.type === "deployment")!; + expect(deployment.attrs.find((a) => a.name === "anyRole")!.ref).toEqual({ + targetType: "role", + errorCode: "ERR_TEST_ROLE", + }); + }); + + it("a registry with no facet writes no `ref` key", () => { + const text = emitRegistryManifest(composeRegistry([...coreProviders])); + expect(text).not.toContain(`"ref"`); + }); +}); diff --git a/spec/metamodel-definitions.md b/spec/metamodel-definitions.md index c942159753..7c5f063e68 100644 --- a/spec/metamodel-definitions.md +++ b/spec/metamodel-definitions.md @@ -76,7 +76,9 @@ files, each one names its code in `errorCode`, so no fixture or adopter sees a d 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 +attribute only when the attribute has one, after `ports` and before `description`. Its keys come +in the table's order: `targetType`, `targetSubTypes` (sorted), `fieldPath` and `sameSystem` (each +only when `true`), then `errorCode` and `wrongSystemCode` (each only when present). 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. @@ -174,7 +176,11 @@ facet that sets `sameSystem` before then can never pass and no definition file s ## 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. +The format and the schema are specified here. No definition file uses `ref` yet. The +TypeScript spec reader reads it and its loader enforces it (`provider-data.ts`, +`loader/symbol-table.ts`, `loader/validation-registry.ts`); its registry manifest writes the +facet as described above. The other ports learn to read and enforce the facet in their own +changes, while no definition file uses it, so no registry output changes. The two default codes +join `fixtures/conformance/ERROR-CODES.json` in the change that adds the two worked cases as +fixtures, since every port's catalog test reads that one file. The four existing core references +then move from code into the definition files, keeping their codes. From 062526fec72107d2877f484c2634efe5732de3ac Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 22:43:31 -0500 Subject: [PATCH 02/12] no-mistakes(review): apply reviewer inline fixes --- CHANGELOG.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5807845221..6f224840bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,10 +15,12 @@ here.** say in data what it may name (target type, admitted subtypes, same system), and the loader checks it with no code per provider: the lookup is typed by the target, a dotted value resolves `System.child` and `pkg::System.child`, a bare value is looked for in the referrer's own - containers first, and a value names nothing (`ERR_REF_UNRESOLVED`), the wrong kind of node - (`ERR_REF_WRONG_KIND`) or a node of another system (the facet's own code). The registry manifest - writes `ref` only on an attribute that has one. No definition file uses the facet yet, so no - registry, manifest or generated output changes. + containers first, and a value that names nothing (`ERR_REF_UNRESOLVED`), the wrong kind of node + (`ERR_REF_WRONG_KIND`) or a node of another system (the facet's own code) is refused. The + registry manifest writes `ref` only on an attribute that has one. No definition file uses the + facet yet, so no registry, manifest or generated output changes. A provider that sets + `TypeDefinition.references` in code: the descriptor's `targetSubType` is now `targetSubTypes` + (a list), `dottedFieldPath` is now `fieldPath`, and `errorCode` is optional. - **`meta verify --uuid-values` lists the stored uuids that 1.3.0's write check refuses.** It is a read-only check to run before upgrading. With `--db ` (SQLite, libSQL or Postgres), or with From 6a533a35fe35ff7c27bc8097ac0cf5d97365a31f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 22:44:46 -0500 Subject: [PATCH 03/12] no-mistakes(review): fix wrong-kind lookup, refuse structural-child ref --- .../metadata/src/loader/symbol-table.ts | 17 ++++++++--------- .../packages/metadata/src/provider-data.ts | 12 +++++++++--- .../metadata/test/reference-facet.test.ts | 17 +++++++++++++++++ 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/server/typescript/packages/metadata/src/loader/symbol-table.ts b/server/typescript/packages/metadata/src/loader/symbol-table.ts index 7976b64a1a..44b809e530 100644 --- a/server/typescript/packages/metadata/src/loader/symbol-table.ts +++ b/server/typescript/packages/metadata/src/loader/symbol-table.ts @@ -112,12 +112,13 @@ export class SymbolTableImpl implements SymbolTable { if (hit !== undefined) return hit; } } - return this.topLevel(owner, type, referrerPkg); + return type !== undefined ? this.resolve(type, owner, referrerPkg) : this.topLevelNamed(owner, referrerPkg)[0]; } // Rule 3: `Owner.child[.grand]` — the owner by its form, then each segment by name. const path = tail.slice(CHILD_REF_SEPARATOR.length).split(CHILD_REF_SEPARATOR); if (path.some((p) => p === "")) return undefined; - let current = this.topLevel(owner, undefined, referrerPkg); + const owners = this.topLevelNamed(owner, referrerPkg); + let current = owners.length === 1 ? owners[0] : undefined; // Rule 2: an intermediate segment matches a child by name, of any type; two // children sharing the name make the step ambiguous. for (let i = 0; current !== undefined && i < path.length - 1; i++) { @@ -129,22 +130,20 @@ export class SymbolTableImpl implements SymbolTable { return this.childNamed(current, path[path.length - 1]!, type); } - /** A top-level node by ADR-0059 R2 form: of `type`, or — untyped — the one node - * under the first key that has any (two of different types are ambiguous). */ - private topLevel(owner: string, type: string | undefined, referrerPkg: string): MetaData | undefined { - if (type !== undefined) return this.resolve(type, owner, referrerPkg); + /** The top-level nodes of any type under the first key, by ADR-0059 R2 form, that has any. */ + private topLevelNamed(owner: string, referrerPkg: string): readonly MetaData[] { let keys: readonly string[]; try { keys = ownerCandidateKeys(owner, referrerPkg); } catch (e) { - if (e instanceof RefOverDropError) return undefined; + if (e instanceof RefOverDropError) return []; throw e; } for (const key of keys) { const hits = this.byKey.get(key); - if (hits !== undefined) return hits.length === 1 ? hits[0] : undefined; + if (hits !== undefined) return hits; } - return undefined; + return []; } /** The first child of `parent` named `name`, of `type` when given. */ diff --git a/server/typescript/packages/metadata/src/provider-data.ts b/server/typescript/packages/metadata/src/provider-data.ts index 495f415e1f..4d9bbc67f9 100644 --- a/server/typescript/packages/metadata/src/provider-data.ts +++ b/server/typescript/packages/metadata/src/provider-data.ts @@ -266,7 +266,7 @@ export function defineProviderFromData( if (isAttrChild(child)) { attributes.push(toAttrSchema(data.provider, key, child)); } else { - childRules.push(toChildRule(child)); + childRules.push(toChildRule(data.provider, key, child)); } } lowered.set(key, { attributes, childRules }); @@ -354,7 +354,7 @@ function applyExtends(registry: TypeRegistry, data: ProviderDefinition): void { if (isAttrChild(child)) { attributes.push(toAttrSchema(data.provider, ext.type, child)); } else { - childRules.push(toChildRule(child)); + childRules.push(toChildRule(data.provider, ext.type, child)); } } for (const subType of resolveExtendSubTypes(registry, ext)) { @@ -562,7 +562,13 @@ function toReferenceFacet(provider: string, typeKey: string, child: ChildDef): R } /** A structural (`type !== "attr"`) child entry IS a `ChildRule`. */ -function toChildRule(child: ChildDef): ChildRule { +function toChildRule(provider: string, typeKey: string, child: ChildDef): ChildRule { + if (child.ref !== undefined) { + throw new Error( + `defineProviderFromData(${provider}): child "${child.name}" on "${typeKey}" has an invalid reference facet: ` + + `only an attr may be a reference.`, + ); + } return { childType: child.type, // A structural child always supplies a subType; default to the `"*"` diff --git a/server/typescript/packages/metadata/test/reference-facet.test.ts b/server/typescript/packages/metadata/test/reference-facet.test.ts index 1476ac0169..b2cc032bd7 100644 --- a/server/typescript/packages/metadata/test/reference-facet.test.ts +++ b/server/typescript/packages/metadata/test/reference-facet.test.ts @@ -197,6 +197,16 @@ describe("reference facet — the spec reader", () => { expect(refuse({ targetType: "role", errorCode: "bad" })).toThrow(/loader code/); expect(refuse({ targetType: "role", targetSubType: "rdb" })).toThrow(/unknown key "targetSubType"/); }); + + it("refuses a facet on a structural child", () => { + const child: ChildDef = { ...any("role"), ref: { targetType: "role" } }; + expect(() => + defineProviderFromData( + { provider: "bad", types: [{ type: "widget", subType: "x", description: "x", children: [child] }] }, + { "widget.x": (typeId, name) => new SystemTestNode(typeId, name) }, + ), + ).toThrow(/only an attr may be a reference/); + }); }); describe("reference facet — the loader", () => { @@ -237,6 +247,13 @@ describe("reference facet — the loader", () => { expect(codes(errors)).toEqual(["ERR_REF_UNRESOLVED"]); }); + it("wrong kind: two top-level nodes of other types share the name", async () => { + const outside = ` - system.software: { name: Shared } + - deployment.test: { name: Shared }`; + const { errors } = await load(MODEL(` - app.service: { name: worker, runsAs: Shared }`, outside)); + expect(codes(errors)).toEqual(["ERR_REF_WRONG_KIND"]); + }); + it("wrong subtype: a grant.rdb naming a resource.queue", async () => { const { errors } = await load( MODEL(` - role.service: From 06dfc9fb92785b7df3cbbf789f27e4d60e06392b Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 22:47:18 -0500 Subject: [PATCH 04/12] no-mistakes(review): apply reviewer inline fixes --- spec/metamodel-definitions.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spec/metamodel-definitions.md b/spec/metamodel-definitions.md index 7c5f063e68..3c07e1d413 100644 --- a/spec/metamodel-definitions.md +++ b/spec/metamodel-definitions.md @@ -66,7 +66,7 @@ Rules on where the facet may appear: 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. + `fixtures/conformance/ERROR-CODES.json` once a conformance fixture raises them. **Existing references keep their codes.** Core declares four references in TypeScript code today (`core-types.ts`: `relationship.* @objectRef` raises `ERR_INVALID_RELATIONSHIP`, @@ -152,8 +152,8 @@ Two worked cases. They are normative: | 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. +the facet. No fixture exists before then, because 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). From 6c08b8d1530d03dd403554772dd53b257d8db989 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 22:53:05 -0500 Subject: [PATCH 05/12] no-mistakes(review): keep inherited and canonical facet refs on one target --- .../metadata/src/loader/resolve-references.ts | 33 ++-- .../metadata/src/loader/symbol-table.ts | 49 ++++-- .../src/loader/validation-registry.ts | 22 +-- .../packages/metadata/src/naming-refs.ts | 8 +- .../packages/metadata/src/validation-types.ts | 12 +- .../metadata/test/reference-facet.test.ts | 166 +++++++++++++++++- spec/metamodel-definitions.md | 17 +- 7 files changed, 251 insertions(+), 56 deletions(-) diff --git a/server/typescript/packages/metadata/src/loader/resolve-references.ts b/server/typescript/packages/metadata/src/loader/resolve-references.ts index f4232166b9..640f63d7a6 100644 --- a/server/typescript/packages/metadata/src/loader/resolve-references.ts +++ b/server/typescript/packages/metadata/src/loader/resolve-references.ts @@ -81,8 +81,9 @@ function referrerPackage(root: MetaData, node: MetaData, attr: string, declPkg: type ResolveValue = (value: string) => Resolved | undefined; /** A facet reference (spec/metamodel-definitions.md, rule 7): the target the typed - * lookup finds, spelled as its top-level owner's canonical name plus the child path. A - * `fieldPath` value keeps its field segment. */ + * lookup finds, spelled as the top-level owner it was reached through plus the child + * names walked. A `fieldPath` value keeps its field segment. A spelling that would not + * look up the same target again keeps the value as written. */ function facetResolver( symbols: SymbolTableImpl, node: MetaData, @@ -90,15 +91,19 @@ function facetResolver( declPkg: string, ): ResolveValue { return (value) => { - const target = symbols.lookup(node, value, facet, declPkg).target; - if (target === undefined) return undefined; - const owner = topLevelNodeOf(target); - let tail = ""; - for (let n: MetaData = target; n !== owner && n.parent !== undefined; n = n.parent) { - tail = `${CHILD_REF_SEPARATOR}${n.name}${tail}`; - } - if (facet.fieldPath === true) tail = splitChildTail(value).tail; - return { target, canonical: spellRef(owner, declPkg, tail) }; + const path = symbols.lookup(node, value, facet, declPkg).path; + if (path === undefined) return undefined; + const target = path[path.length - 1]!; + const tail = + facet.fieldPath === true + ? splitChildTail(value).tail + : path + .slice(1) + .map((n) => `${CHILD_REF_SEPARATOR}${n.name}`) + .join(""); + const canonical = spellRef(path[0]!, declPkg, tail); + const again = symbols.lookup(node, canonical, facet, declPkg).path; + return { target, canonical: again?.[again.length - 1] === target ? canonical : value }; }; } @@ -178,14 +183,12 @@ export function resolveReferences(root: MetaData, registry?: TypeRegistry): void // ADR-0039: own — this pass rewrites the declared-here layer; an inherited // attribute is resolved once, on the node that declares it. for (const attr of node.ownMetaAttrs()) { - if (isRefBearingAttr(node, attr.name)) { - resolveAttr(root, node, attr, declPkg); - continue; - } const facet = facetOf(node, attr.name); if (facet !== undefined) { symbols ??= SymbolTableImpl.build(root); bindAttr(node, attr, facetResolver(symbols, node, facet, declPkg)); + } else if (isRefBearingAttr(node, attr.name)) { + resolveAttr(root, node, attr, declPkg); } } } diff --git a/server/typescript/packages/metadata/src/loader/symbol-table.ts b/server/typescript/packages/metadata/src/loader/symbol-table.ts index 44b809e530..05f00f8005 100644 --- a/server/typescript/packages/metadata/src/loader/symbol-table.ts +++ b/server/typescript/packages/metadata/src/loader/symbol-table.ts @@ -88,46 +88,59 @@ export class SymbolTableImpl implements SymbolTable { if (e instanceof RefOverDropError) return { overDrop: true }; throw e; } - const target = this.find(referrer, ref, facet.targetType, referrerPkg); - if (target !== undefined) return { target }; + // A `fieldPath` target is top-level: the referrer's containers are not searched. + const from = facet.fieldPath === true ? undefined : referrer; + const path = this.find(from, ref, facet.targetType, referrerPkg); + if (path !== undefined) return { path }; // Rule 6: the untyped lookup, along the same order, only picks the error code. - const wrongKind = this.find(referrer, ref, undefined, referrerPkg); - return wrongKind !== undefined ? { wrongKind } : {}; + const wrongKind = this.find(from, ref, undefined, referrerPkg); + return wrongKind !== undefined ? { wrongKind: wrongKind[wrongKind.length - 1]! } : {}; } - /** The node `ref` names whose final segment is of `type` (any type when undefined). */ + /** The path, top-level owner first, to the node `ref` names whose final segment is + * of `type` (any type when undefined). With no `referrer`, no container is searched. */ private find( - referrer: MetaData, + referrer: MetaData | undefined, ref: string, type: string | undefined, referrerPkg: string, - ): MetaData | undefined { + ): readonly MetaData[] | undefined { const { owner, tail } = splitChildTail(ref); if (tail === "") { // Rule 4: a bare value is looked for among the children of each container of // the referrer, nearest first, up to and including its top-level node. - if (!owner.includes(PACKAGE_SEPARATOR)) { + if (referrer !== undefined && !owner.includes(PACKAGE_SEPARATOR)) { for (let c = referrer.parent; c !== undefined && c !== this.root; c = c.parent) { const hit = this.childNamed(c, owner, type); - if (hit !== undefined) return hit; + if (hit !== undefined) return [...this.containersTo(c), hit]; } } - return type !== undefined ? this.resolve(type, owner, referrerPkg) : this.topLevelNamed(owner, referrerPkg)[0]; + const top = type !== undefined ? this.resolve(type, owner, referrerPkg) : this.topLevelNamed(owner, referrerPkg)[0]; + return top !== undefined ? [top] : undefined; } // Rule 3: `Owner.child[.grand]` — the owner by its form, then each segment by name. - const path = tail.slice(CHILD_REF_SEPARATOR.length).split(CHILD_REF_SEPARATOR); - if (path.some((p) => p === "")) return undefined; + const segments = tail.slice(CHILD_REF_SEPARATOR.length).split(CHILD_REF_SEPARATOR); + if (segments.some((p) => p === "")) return undefined; const owners = this.topLevelNamed(owner, referrerPkg); - let current = owners.length === 1 ? owners[0] : undefined; + if (owners.length !== 1) return undefined; + const path: MetaData[] = [owners[0]!]; // Rule 2: an intermediate segment matches a child by name, of any type; two // children sharing the name make the step ambiguous. - for (let i = 0; current !== undefined && i < path.length - 1; i++) { - const named = this.childIndex(current).get(path[i]!) ?? []; - current = named.length === 1 ? named[0] : undefined; + for (let i = 0; i < segments.length - 1; i++) { + const named = this.childIndex(path[path.length - 1]!).get(segments[i]!) ?? []; + if (named.length !== 1) return undefined; + path.push(named[0]!); } - if (current === undefined) return undefined; // Rule 1: the final segment is typed. - return this.childNamed(current, path[path.length - 1]!, type); + const last = this.childNamed(path[path.length - 1]!, segments[segments.length - 1]!, type); + return last !== undefined ? [...path, last] : undefined; + } + + /** The physical containers from the top-level node down to `container`, inclusive. */ + private containersTo(container: MetaData): MetaData[] { + const out: MetaData[] = []; + for (let c: MetaData | undefined = container; c !== undefined && c !== this.root; c = c.parent) out.unshift(c); + return out; } /** The top-level nodes of any type under the first key, by ADR-0059 R2 form, that has any. */ diff --git a/server/typescript/packages/metadata/src/loader/validation-registry.ts b/server/typescript/packages/metadata/src/loader/validation-registry.ts index 284c459ee6..b4a325664c 100644 --- a/server/typescript/packages/metadata/src/loader/validation-registry.ts +++ b/server/typescript/packages/metadata/src/loader/validation-registry.ts @@ -8,7 +8,7 @@ import type { MetaData } from "../shared/meta-data.js"; import { ParseError } from "../errors.js"; -import { didYouMeanHint, referrerPackageFor } from "../naming-refs.js"; +import { declaringNodeFor, didYouMeanHint, effectivePackageOf, topLevelNodeOf } from "../naming-refs.js"; import { TYPE_OBJECT, TYPE_SYSTEM } from "../shared/base-types.js"; import type { TypeDefinition, TypeRegistry } from "../registry.js"; import { @@ -63,9 +63,10 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): : Array.isArray(raw) ? raw.filter((v): v is string => typeof v === "string") : []; - // ADR-0059 R3: an inherited reference resolves in the package of the - // top-level node that physically declares it, not the inheritor's. - const refPkg = referrerPackageFor(node, desc.attr); + // ADR-0059 R3 and rule 5: an inherited reference is looked up from the node that + // physically declares it, in that node's package, not from the inheritor. + const declarer = declaringNodeFor(node, desc.attr); + const refPkg = effectivePackageOf(topLevelNodeOf(declarer)); // Qualify the node name with its owning entity (e.g. "Order.items") so the error is // locatable from the message alone, not just the source envelope. const qname = node.parent?.name ? `${node.parent.name}.${node.name}` : node.name; @@ -78,7 +79,7 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): : desc.targetSubTypes.map((s) => `${desc.targetType}.${s}`).join(" or "); for (const value of values) { if (value === "") continue; // absence is the required-attr pass's job - const found = ctx.symbols.lookup(node, value, desc, refPkg); + const found = ctx.symbols.lookup(declarer, value, desc, refPkg); if (found.overDrop === true) { ctx.error( "ERR_BAD_ATTR_VALUE", @@ -87,8 +88,8 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): ); continue; } - const target = found.target; - if (target === undefined) { + const path = found.path; + if (path === undefined) { if (found.wrongKind !== undefined) { const w = found.wrongKind; ctx.error( @@ -109,6 +110,7 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): ); continue; } + const target = path[path.length - 1]!; if (desc.targetSubTypes !== undefined && !desc.targetSubTypes.includes(target.subType)) { // The typed lookup already guarantees target.type === desc.targetType; only the // subType can still mismatch. @@ -120,8 +122,8 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): continue; } if (desc.sameSystem === true) { - const mine = systemOf(node); - const theirs = systemOf(target); + const mine = systemOf(declarer); + const theirs = path.findLast((n) => n.type === TYPE_SYSTEM); if (mine === undefined || mine !== theirs) { const where = theirs === undefined ? "no system" : `system "${theirs.resolutionKey()}"`; const from = mine === undefined ? "a node outside any system" : `system "${mine.resolutionKey()}"`; @@ -129,7 +131,7 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): desc.wrongSystemCode ?? REF_WRONG_KIND_CODE, node, `${label(value)} resolves to ${target.type}.${target.subType} "${target.name}" in ${where}, ` + - `but it must be in the same system as the declaring node, which is in ${from}.`, + `but it must be in the same system as the node that declares it, which is in ${from}.`, ); } } diff --git a/server/typescript/packages/metadata/src/naming-refs.ts b/server/typescript/packages/metadata/src/naming-refs.ts index a079fe2f5d..04468d974a 100644 --- a/server/typescript/packages/metadata/src/naming-refs.ts +++ b/server/typescript/packages/metadata/src/naming-refs.ts @@ -329,6 +329,12 @@ export function topLevelNodeOf(node: MetaData): MetaData { * so an inherited reference means what it meant where it was written. */ export function referrerPackageFor(node: MetaData, attrName: string): string { + return effectivePackageOf(topLevelNodeOf(declaringNodeFor(node, attrName))); +} + +/** The node that physically declares `attrName` for `node`: `node` itself, or the + * ancestor along its `extends` chain that wrote it (`node` when none does). */ +export function declaringNodeFor(node: MetaData, attrName: string): MetaData { let declarer: MetaData | undefined = node; const seen = new Set(); // ADR-0039: own — locating the layer that physically declares the attr. @@ -336,7 +342,7 @@ export function referrerPackageFor(node: MetaData, attrName: string): string { seen.add(declarer); declarer = declarer.superResolved; } - return effectivePackageOf(topLevelNodeOf(declarer ?? node)); + return declarer ?? node; } /** diff --git a/server/typescript/packages/metadata/src/validation-types.ts b/server/typescript/packages/metadata/src/validation-types.ts index 8d58db7218..29a01efa1b 100644 --- a/server/typescript/packages/metadata/src/validation-types.ts +++ b/server/typescript/packages/metadata/src/validation-types.ts @@ -50,11 +50,15 @@ export interface ReferenceDescriptor extends ReferenceFacet { readonly attr: string; } -/** What one reference value names: the target, or the wrong-kind node the untyped - * lookup found instead, or neither. `overDrop` marks a `..::` that climbs above the - * root package. */ +/** What one reference value names: the path to the target, or the wrong-kind node the + * untyped lookup found instead, or neither. `overDrop` marks a `..::` that climbs + * above the root package. */ export interface ReferenceMatch { - readonly target?: MetaData; + /** The nodes the lookup walked, from the top-level owner to the target (the last + * entry). A child inherited through `extends` is reached through the node it was + * looked up in, so the path is the address the value used, not the target's + * physical parents. */ + readonly path?: readonly MetaData[]; readonly wrongKind?: MetaData; readonly overDrop?: boolean; } diff --git a/server/typescript/packages/metadata/test/reference-facet.test.ts b/server/typescript/packages/metadata/test/reference-facet.test.ts index b2cc032bd7..969c19249b 100644 --- a/server/typescript/packages/metadata/test/reference-facet.test.ts +++ b/server/typescript/packages/metadata/test/reference-facet.test.ts @@ -22,6 +22,7 @@ import { TypeId, type TypeRegistry } from "../src/registry.js"; import { MetaData } from "../src/shared/meta-data.js"; import { buildRegistryManifest, emitRegistryManifest } from "../src/registry-manifest.js"; import { refTarget } from "../src/naming-refs.js"; +import { canonicalSerialize } from "../src/serializer-json.js"; import type { ReferenceFacet } from "../src/validation-types.js"; class SystemTestNode extends MetaData {} @@ -55,13 +56,14 @@ const DEFINITION: ProviderDefinition = { children: [ attr("runsAs", { ref: { targetType: "role", sameSystem: true, wrongSystemCode: "ERR_RUNSAS_OTHER_SYSTEM" } }), attr("calls", { isArray: true, max: 1, ref: { targetType: "app" } }), + attr("reads", { ref: { targetType: "resource", fieldPath: true } }), ], }, { type: "role", subType: "service", description: "A test role.", - children: [any("grant")], + children: [any("grant"), any("resource")], }, { type: "grant", @@ -88,6 +90,7 @@ const DEFINITION: ProviderDefinition = { attr("app", { ref: { targetType: "app" } }), attr("anyRole", { ref: { targetType: "role", errorCode: "ERR_TEST_ROLE" } }), attr("pinnedRole", { ref: { targetType: "role", sameSystem: true, wrongSystemCode: "ERR_TEST_OUTSIDE" } }), + attr("via", { ref: { targetType: "role" } }), ], }, ], @@ -95,7 +98,7 @@ const DEFINITION: ProviderDefinition = { { type: "metadata", subType: "root", - children: [any("system"), any("deployment")], + children: [any("system"), any("deployment"), any("app"), any("resource")], }, ], }; @@ -115,11 +118,11 @@ const testProvider: MetaDataTypeProvider = { }, }; -async function load(yaml: string) { +async function load(text: string, format: "yaml" | "json" = "yaml") { const registry = composeRegistry([...coreProviders, testProvider]); const loader = new MetaDataLoader({ registry, strict: true }); const { root, errors } = await loader.load([ - new InMemoryStringSource(yaml, { id: "systems.yaml", format: "yaml" }), + new InMemoryStringSource(text, { id: `systems.${format}`, format }), ]); return { root, @@ -313,6 +316,161 @@ describe("reference facet — the loader", () => { }); }); +/** A node by its path from the root; a step is `name` or `type:name`. */ +const at = (root: MetaData, ...steps: string[]): MetaData => + steps.reduce((n, step) => { + const [type, name] = step.includes(":") ? step.split(":") : [undefined, step]; + return n.ownChildren().find((c) => c.name === name && (type === undefined || c.type === type))!; + }, root); + +/** The node the loader bound `attrName` on `node` to (the first, for a list). */ +const boundTo = (node: MetaData, attrName: string): unknown => { + const t = node.ownMetaAttr(attrName)?.resolvedTarget; + return Array.isArray(t) ? t[0] : t; +}; + +/** Load, serialize canonically, reload: the reloaded model loads clean and `attrName` on + * the node at `referrer` names the node at `target` in both trees. Returns the value written. */ +async function roundTrip(yaml: string, referrer: string[], attrName: string, target: string[]): Promise { + const first = await load(yaml); + expect(first.errors).toEqual([]); + expect(boundTo(at(first.root, ...referrer), attrName)).toBe(at(first.root, ...target)); + const second = await load(canonicalSerialize(first.root), "json"); + expect(second.errors).toEqual([]); + expect(boundTo(at(second.root, ...referrer), attrName)).toBe(at(second.root, ...target)); + return at(second.root, ...referrer).attr(attrName); +} + +describe("reference facet — inheritance and canonical spelling", () => { + it("an inherited reference is looked up where it was written, not from the inheritor", async () => { + // Ledger has no role `api`: `web` inherits `runsAs: api` from Parcels' `base`. + const { root, errors } = await load(` +metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - role.service: { name: api } + - app.service: { name: base, runsAs: api } + - system.software: + name: Ledger + children: + - app.service: { name: web, extends: acme::Parcels.base } +`); + expect(errors).toEqual([]); + expect(refTarget(at(root, "Ledger", "web"), "runsAs")).toBe(at(root, "Parcels", "api")); + }); + + const INHERITING = (extra: string) => ` +metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - role.service: { name: clerk } + - system.software: + name: Ledger + extends: Parcels + children: + - app.service: { name: web, runsAs: clerk } +${extra} +`; + + it("an inherited child keeps the path it was addressed by, and is in that system", async () => { + const written = await roundTrip( + INHERITING(` - deployment.test: { name: d1, anyRole: Ledger.clerk }`), + ["d1"], + "anyRole", + ["Parcels", "clerk"], + ); + expect(written).toBe("acme::Ledger.clerk"); + const { root } = await load(INHERITING("")); + expect(at(root, "Ledger", "web").attr("runsAs")).toBe("acme::Ledger.clerk"); + }); + + it("a path through a shared intermediate name keeps the value as written", async () => { + const written = await roundTrip( + ` +metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - app.service: { name: api } + - role.service: + name: api + children: + - resource.rdb: { name: local } + - grant.rdb: { name: g1, resource: local } +`, + ["Parcels", "role:api", "g1"], + "resource", + ["Parcels", "role:api", "local"], + ); + expect(written).toBe("local"); + }); + + it("a top-level key shared by two types keeps the value as written", async () => { + const written = await roundTrip( + ` +metadata.root: + package: acme + children: + - deployment.test: { name: Shared } + - system.software: + name: Shared + children: + - role.service: { name: r } + - app.service: { name: a, runsAs: r } +`, + ["system:Shared", "a"], + "runsAs", + ["system:Shared", "r"], + ); + expect(written).toBe("r"); + }); + + it("a root-absolute value a container child would shadow keeps its `::`", async () => { + const written = await roundTrip( + ` +metadata.root: + children: + - app.service: { name: api } + - system.software: + name: S + children: + - app.service: { name: api } + - app.service: { name: worker, calls: ["::api"] } +`, + ["S", "worker"], + "calls", + ["app:api"], + ); + expect(written).toEqual(["::api"]); + }); + + it("a fieldPath value names a top-level target, never a container child", async () => { + const { root, errors } = await load( + MODEL(` - app.service: { name: worker, reads: db.name }`, ` - resource.rdb: { name: db }`), + ); + expect(errors).toEqual([]); + const worker = at(root, "Parcels", "worker"); + expect(refTarget(worker, "reads")).toBe(at(root, "db")); + expect(worker.attr("reads")).toBe("acme::db.name"); + }); + + it("a facet attribute named like a core reference is bound by its facet", async () => { + const { root, errors } = await load(MODEL("", ` - deployment.test: { name: d1, via: Parcels.api }`)); + expect(errors).toEqual([]); + const d1 = at(root, "d1"); + expect(refTarget(d1, "via")?.type).toBe("role"); + expect(d1.attr("via")).toBe("acme::Parcels.api"); + }); +}); + describe("reference facet — the registry manifest", () => { it("writes `ref` only on an attribute that has one, in the fixed key order", () => { const registry = composeRegistry([...coreProviders, testProvider]); diff --git a/spec/metamodel-definitions.md b/spec/metamodel-definitions.md index 3c07e1d413..b8412ff671 100644 --- a/spec/metamodel-definitions.md +++ b/spec/metamodel-definitions.md @@ -100,7 +100,10 @@ containers**. 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. + addresses a node through a child that shares its name with a sibling. A child a node + inherits through `extends` is a child of that node for this walk: `Ledger.clerk` reaches + the `clerk` that `Ledger` inherits from `Parcels`, and for `sameSystem` that target is in + `Ledger`, the system the path went through. 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`, @@ -114,7 +117,8 @@ containers**. 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. + existing `object` references resolve exactly as they do today. A `fieldPath` value names a + top-level target, so its lookup skips the containers. 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 @@ -130,8 +134,13 @@ containers**. 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. + `quillhaven::parcels::Parcels` is written `quillhaven::parcels::Parcels.api`. The path is + the one the lookup walked, not the target's physical parents, so `Ledger.clerk` for an + inherited `clerk` stays `pkg::Ledger.clerk`. A `fieldPath` value keeps its field segment. + The canonical value must look up the same target from the same node. When it would not + (an intermediate segment shared by two children, a top-level key shared by nodes of two + types, an unnamed container, or a root-level `::db` that would become a bare `db` a + container child shadows), the value is kept exactly as written. ## What the loader checks, in order From 76159283095f2d49065cadd7c94c6db32f13e58f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 22:57:51 -0500 Subject: [PATCH 06/12] no-mistakes(review): keep did-you-mean hint on wrong-kind object refs --- .../src/loader/validation-registry.ts | 10 ++--- .../metadata/test/reference-facet.test.ts | 40 +++++++++++++++++++ spec/metamodel-definitions.md | 5 ++- 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/server/typescript/packages/metadata/src/loader/validation-registry.ts b/server/typescript/packages/metadata/src/loader/validation-registry.ts index b4a325664c..610fecf0f9 100644 --- a/server/typescript/packages/metadata/src/loader/validation-registry.ts +++ b/server/typescript/packages/metadata/src/loader/validation-registry.ts @@ -90,19 +90,19 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): } const path = found.path; if (path === undefined) { + // `did-you-mean` is object-scoped (its candidate scan is over objects), so only + // append it for object targets; a non-object target names its own kind. + const entityRef = desc.fieldPath === true ? (value.split(".")[0] ?? value) : value; + const hint = desc.targetType === TYPE_OBJECT ? didYouMeanHint(root, entityRef) : ""; if (found.wrongKind !== undefined) { const w = found.wrongKind; ctx.error( desc.errorCode ?? REF_WRONG_KIND_CODE, node, - `${label(value)} names ${w.type}.${w.subType} "${w.name}", not ${wantKind}.`, + `${label(value)} names ${w.type}.${w.subType} "${w.name}", not ${wantKind}.${hint}`, ); continue; } - // `did-you-mean` is object-scoped (its candidate scan is over objects), so only - // append it for object targets; a non-object target names its own kind. - const entityRef = desc.fieldPath === true ? (value.split(".")[0] ?? value) : value; - const hint = desc.targetType === TYPE_OBJECT ? didYouMeanHint(root, entityRef) : ""; ctx.error( desc.errorCode ?? REF_UNRESOLVED_CODE, node, diff --git a/server/typescript/packages/metadata/test/reference-facet.test.ts b/server/typescript/packages/metadata/test/reference-facet.test.ts index 969c19249b..acdf5ce513 100644 --- a/server/typescript/packages/metadata/test/reference-facet.test.ts +++ b/server/typescript/packages/metadata/test/reference-facet.test.ts @@ -362,6 +362,27 @@ metadata.root: expect(refTarget(at(root, "Ledger", "web"), "runsAs")).toBe(at(root, "Parcels", "api")); }); + it("an inherited sameSystem reference is judged where it was written, even when the inheritor's system has a match", async () => { + // Ledger has its own role `api`, but `web`'s `runsAs: api` was written in Parcels. + const { root, errors } = await load(` +metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - role.service: { name: api } + - app.service: { name: base, runsAs: api } + - system.software: + name: Ledger + children: + - role.service: { name: api } + - app.service: { name: web, extends: acme::Parcels.base } +`); + expect(errors).toEqual([]); + expect(refTarget(at(root, "Ledger", "web"), "runsAs")).toBe(at(root, "Parcels", "role:api")); + }); + const INHERITING = (extra: string) => ` metadata.root: package: acme @@ -471,6 +492,25 @@ metadata.root: }); }); +describe("reference facet — the core object references", () => { + it("a wrong-kind object reference still suggests the object in another package", async () => { + // `@objectRef: Address` finds the field itself among its containers (wrong kind); the + // object `Address` exists only in package `common`. + const { errors } = await load(` +metadata.root: + children: + - object.value: { name: Address, package: common, children: [ { field.string: { name: street } } ] } + - object.value: + name: Order + package: shop + children: + - field.object: { name: Address, objectRef: Address } +`); + expect(codes(errors)).toEqual(["ERR_UNRESOLVED_OBJECT_REF"]); + expect(errors[0]!.message).toContain("An object named \"Address\" exists in: common::Address."); + }); +}); + describe("reference facet — the registry manifest", () => { it("writes `ref` only on an attribute that has one, in the fixed key order", () => { const registry = composeRegistry([...coreProviders, testProvider]); diff --git a/spec/metamodel-definitions.md b/spec/metamodel-definitions.md index b8412ff671..4671d1f089 100644 --- a/spec/metamodel-definitions.md +++ b/spec/metamodel-definitions.md @@ -108,7 +108,10 @@ containers**. 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`. + its child `db` of type `targetType`. The owner of a dotted value matches a top-level node by + name, of any type. If top-level nodes of two types share the owner's key (a template and a + system both named `acme::Shared`), the owner is ambiguous and the value does not resolve, + even when only one of them has the named child. 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 From dab66057114436fec3dcba0eb3a8c7675cf8fa4d Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 23:02:09 -0500 Subject: [PATCH 07/12] no-mistakes(review): fix `..::` field-path hint and stale reader comment --- .../metadata/src/loader/validation-registry.ts | 3 +-- .../metadata/test/definition-schema.test.ts | 2 +- .../metadata/test/reference-facet.test.ts | 18 ++++++++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/server/typescript/packages/metadata/src/loader/validation-registry.ts b/server/typescript/packages/metadata/src/loader/validation-registry.ts index 610fecf0f9..e256fb7794 100644 --- a/server/typescript/packages/metadata/src/loader/validation-registry.ts +++ b/server/typescript/packages/metadata/src/loader/validation-registry.ts @@ -92,8 +92,7 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): if (path === undefined) { // `did-you-mean` is object-scoped (its candidate scan is over objects), so only // append it for object targets; a non-object target names its own kind. - const entityRef = desc.fieldPath === true ? (value.split(".")[0] ?? value) : value; - const hint = desc.targetType === TYPE_OBJECT ? didYouMeanHint(root, entityRef) : ""; + const hint = desc.targetType === TYPE_OBJECT ? didYouMeanHint(root, value) : ""; if (found.wrongKind !== undefined) { const w = found.wrongKind; ctx.error( diff --git a/server/typescript/packages/metadata/test/definition-schema.test.ts b/server/typescript/packages/metadata/test/definition-schema.test.ts index 3716b8dd41..22bd083c63 100644 --- a/server/typescript/packages/metadata/test/definition-schema.test.ts +++ b/server/typescript/packages/metadata/test/definition-schema.test.ts @@ -9,7 +9,7 @@ // 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. +// The TypeScript spec reader reads `ref`; the other ports do not yet. import { describe, test, expect } from "bun:test"; import { readFileSync, readdirSync, existsSync } from "node:fs"; diff --git a/server/typescript/packages/metadata/test/reference-facet.test.ts b/server/typescript/packages/metadata/test/reference-facet.test.ts index acdf5ce513..d3268ea869 100644 --- a/server/typescript/packages/metadata/test/reference-facet.test.ts +++ b/server/typescript/packages/metadata/test/reference-facet.test.ts @@ -511,6 +511,24 @@ metadata.root: }); }); +describe("reference facet — the did-you-mean hint on a field path", () => { + it("a parent-relative `@references` still suggests the object in another package", async () => { + // ADR-0059 §2: `..::Address.id` from `acme::shop` names `acme::Address`; only `common::Address` exists. + const { errors } = await load(` +metadata.root: + children: + - object.value: { name: Address, package: common, children: [ { field.string: { name: id } } ] } + - object.value: + name: Order + package: acme::shop + children: + - field.string: { name: addressId } + - identity.reference: { name: address, fields: [addressId], references: "..::Address.id" } +`); + expect(errors.some((e) => e.message.includes('An object named "Address" exists in: common::Address.'))).toBe(true); + }); +}); + describe("reference facet — the registry manifest", () => { it("writes `ref` only on an attribute that has one, in the fixed key order", () => { const registry = composeRegistry([...coreProviders, testProvider]); From 1278fb766130a232d6c1848e89906759b6beb209 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 23:05:04 -0500 Subject: [PATCH 08/12] no-mistakes(review): name target system in wrong-subtype ref error --- .../metadata/src/loader/validation-registry.ts | 10 +++++----- .../packages/metadata/test/reference-facet.test.ts | 1 + 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/server/typescript/packages/metadata/src/loader/validation-registry.ts b/server/typescript/packages/metadata/src/loader/validation-registry.ts index e256fb7794..45b229d567 100644 --- a/server/typescript/packages/metadata/src/loader/validation-registry.ts +++ b/server/typescript/packages/metadata/src/loader/validation-registry.ts @@ -110,27 +110,27 @@ export function runRegisteredValidation(root: MetaData, registry: TypeRegistry): continue; } const target = path[path.length - 1]!; + const theirs = path.findLast((n) => n.type === TYPE_SYSTEM); + const where = theirs === undefined ? "no system" : `system "${theirs.resolutionKey()}"`; + const resolved = `${label(value)} resolves to ${target.type}.${target.subType} "${target.name}" in ${where}`; if (desc.targetSubTypes !== undefined && !desc.targetSubTypes.includes(target.subType)) { // The typed lookup already guarantees target.type === desc.targetType; only the // subType can still mismatch. ctx.error( desc.errorCode ?? REF_WRONG_KIND_CODE, node, - `${label(value)} resolves to ${target.type}.${target.subType}, not ${wantKind}.`, + `${resolved}, not ${wantKind}.`, ); continue; } if (desc.sameSystem === true) { const mine = systemOf(declarer); - const theirs = path.findLast((n) => n.type === TYPE_SYSTEM); if (mine === undefined || mine !== theirs) { - const where = theirs === undefined ? "no system" : `system "${theirs.resolutionKey()}"`; const from = mine === undefined ? "a node outside any system" : `system "${mine.resolutionKey()}"`; ctx.error( desc.wrongSystemCode ?? REF_WRONG_KIND_CODE, node, - `${label(value)} resolves to ${target.type}.${target.subType} "${target.name}" in ${where}, ` + - `but it must be in the same system as the node that declares it, which is in ${from}.`, + `${resolved}, but it must be in the same system as the node that declares it, which is in ${from}.`, ); } } diff --git a/server/typescript/packages/metadata/test/reference-facet.test.ts b/server/typescript/packages/metadata/test/reference-facet.test.ts index d3268ea869..eafd131b4b 100644 --- a/server/typescript/packages/metadata/test/reference-facet.test.ts +++ b/server/typescript/packages/metadata/test/reference-facet.test.ts @@ -266,6 +266,7 @@ describe("reference facet — the loader", () => { ); expect(codes(errors)).toEqual(["ERR_REF_WRONG_KIND"]); expect(errors[0]!.message).toContain("resource.queue"); + expect(errors[0]!.message).toContain(`system "acme::Parcels"`); }); it("crosses system: a grant on another system's resource raises the facet's wrongSystemCode", async () => { From 83bff0056f92ff7d0f8f39a1555dc4728c58d945 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 23:07:45 -0500 Subject: [PATCH 09/12] no-mistakes(review): apply reviewer inline fixes --- server/typescript/packages/metadata/src/naming-refs.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/server/typescript/packages/metadata/src/naming-refs.ts b/server/typescript/packages/metadata/src/naming-refs.ts index 04468d974a..8618e590cd 100644 --- a/server/typescript/packages/metadata/src/naming-refs.ts +++ b/server/typescript/packages/metadata/src/naming-refs.ts @@ -388,10 +388,12 @@ function sameNamedObjects( * ADR-0059 R7 — the object a reference attribute on `node` names: the owner the loader * bound once (`MetaAttr.resolvedTarget`), read RESOLVING so an inherited attribute * works (ADR-0039). For a dotted ref (`Week.id`, `Program.weeks`) it is the owner - * object, not the tail. A tree built without the loader has no recorded target, so the - * value is resolved here from the package of the node that declared it. Undefined when - * the attribute is absent, is a list, or names nothing. Consumers use this instead of - * comparing a reference value to a short name. + * object, not the tail. For an attribute with the reference facet, the loader records + * the node the whole path names, of the facet's target type (the `Target` of a + * `fieldPath` value). A tree built without the loader has no recorded target, so the + * value is resolved here, as an object reference, from the package of the node that + * declared it. Undefined when the attribute is absent, is a list, or names nothing. + * Consumers use this instead of comparing a reference value to a short name. */ export function refTarget(node: MetaData, attrName: string): MetaData | undefined { const seen = new Set(); From 9e735ff9710686c492e437a3653d83520d1c35d0 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 3 Dec 2026 00:48:06 -0500 Subject: [PATCH 10/12] no-mistakes(test): Catalog ERR_REF codes and update facet Status docs --- CHANGELOG.md | 4 ++- fixtures/conformance/ERROR-CODES.json | 2 ++ server/csharp/MetaObjects/Errors.cs | 4 +++ .../main/java/com/metaobjects/ErrorCode.java | 14 ++++++++++ server/python/src/metaobjects/errors.py | 4 +++ server/rust/metaobjects/data/ERROR-CODES.json | 2 ++ .../packages/metadata/src/errors.ts | 4 +++ spec/metamodel-definitions.md | 26 ++++++++++++------- 8 files changed, 50 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f224840bb..fa2539d196 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,9 @@ here.** `System.child` and `pkg::System.child`, a bare value is looked for in the referrer's own containers first, and a value that names nothing (`ERR_REF_UNRESOLVED`), the wrong kind of node (`ERR_REF_WRONG_KIND`) or a node of another system (the facet's own code) is refused. The - registry manifest writes `ref` only on an attribute that has one. No definition file uses the + registry manifest writes `ref` only on an attribute that has one. The two default codes are in + `fixtures/conformance/ERROR-CODES.json` and in the TypeScript, Python, Java and C# error-code + catalogs. No definition file uses the facet yet, so no registry, manifest or generated output changes. A provider that sets `TypeDefinition.references` in code: the descriptor's `targetSubType` is now `targetSubTypes` (a list), `dottedFieldPath` is now `fieldPath`, and `errorCode` is optional. diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index 737dbc341a..223217f0e0 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -64,6 +64,8 @@ "ERR_STORAGE_WITHOUT_OBJECT_REF": "@storage was set on a field that has no @objectRef.", "ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF": "ADR-0013: a field.object declares no @objectRef. A field.object models a typed nested value and REQUIRES @objectRef. The message states the whole ladder rather than only the escape hatch: a known key set is an object.value the field @objectRefs; dynamic keys over a known value type are a field.map (@objectRef for a value object, @valueType for a scalar); only a bag no reader pins a key in is @dbColumnType: jsonb on a field.string. Naming the escape hatch alone is what taught adopters to reach for the bag by default.", "ERR_UNRESOLVED_OBJECT_REF": "ADR-0042: a field.object / field.map @objectRef does not resolve to any object in the loaded tree (a dangling target). The ref resolves package-locally when bare (referrer's package, else root-level) and exactly when FQN — a bare cross-package ref no longer binds elsewhere. The error names same-short-name objects in other packages so the author can qualify it.", + "ERR_REF_UNRESOLVED": "spec/metamodel-definitions.md: an attribute whose definition carries the reference facet (`ref`) names a node that resolves to nothing, by the typed lookup or by the untyped lookup the loader runs to choose its error. The default code when the facet names no `errorCode`.", + "ERR_REF_WRONG_KIND": "spec/metamodel-definitions.md: an attribute whose definition carries the reference facet (`ref`) names a node of another type than the facet's `targetType`, or a subtype outside its `targetSubTypes`. The default code when the facet names no `errorCode`.", "ERR_RESERVED_ATTR": "An @-prefixed reserved structural keyword (e.g. @name, @isArray, @children) was used as an inline attribute.", "ERR_SCOPE_PATTERN_INVALID": "Phase-1 metadata-source-resolution: a scope include/exclude package pattern is malformed (empty pattern or empty :: segment).", "ERR_SOURCE_NO_PRIMARY": "An object declares source nodes but none has role=primary.", diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs index 2d340e59e8..159372272e 100644 --- a/server/csharp/MetaObjects/Errors.cs +++ b/server/csharp/MetaObjects/Errors.cs @@ -137,6 +137,10 @@ public enum ErrorCode // longer binds elsewhere. (ERR_AMBIGUOUS_REF is RETIRED: with bare = package-local, // cross-package ambiguity is unreachable.) ERR_UNRESOLVED_OBJECT_REF, + // spec/metamodel-definitions.md — the reference facet's default codes: the value + // resolves to nothing, or to a node of the wrong type or subtype. + ERR_REF_UNRESOLVED, + ERR_REF_WRONG_KIND, ERR_BAD_ATTR_FILTER, ERR_STORAGE_WITHOUT_OBJECT_REF, // ADR-0013: a field.object REQUIRES @objectRef (open/untyped JSON uses the diff --git a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java index 6e41b4c17d..7ddc67af00 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java +++ b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java @@ -332,6 +332,20 @@ public enum ErrorCode { */ ERR_UNRESOLVED_OBJECT_REF, + /** + * spec/metamodel-definitions.md: an attribute carrying the reference facet ({@code ref}) + * names a node that resolves to nothing. The facet's default code when it names no + * {@code errorCode}. + */ + ERR_REF_UNRESOLVED, + + /** + * spec/metamodel-definitions.md: an attribute carrying the reference facet ({@code ref}) + * names a node of the wrong type or subtype. The facet's default code when it names no + * {@code errorCode}. + */ + ERR_REF_WRONG_KIND, + /** An object declares source nodes but none has role=primary. */ ERR_SOURCE_NO_PRIMARY, diff --git a/server/python/src/metaobjects/errors.py b/server/python/src/metaobjects/errors.py index d63f5bb73a..d6e1b51c2d 100644 --- a/server/python/src/metaobjects/errors.py +++ b/server/python/src/metaobjects/errors.py @@ -287,6 +287,10 @@ class ErrorCode(str, Enum): # retired ADR-0041 ERR_AMBIGUOUS_REF (bare = package-local ⇒ ambiguity is # unreachable, so every unresolved ref fails closed with its per-attr code). ERR_UNRESOLVED_OBJECT_REF = "ERR_UNRESOLVED_OBJECT_REF" + # spec/metamodel-definitions.md — the reference facet's default codes: the value + # resolves to nothing, or to a node of the wrong type or subtype. + ERR_REF_UNRESOLVED = "ERR_REF_UNRESOLVED" + ERR_REF_WRONG_KIND = "ERR_REF_WRONG_KIND" # FR-033 — strict structural-placement vocabulary. ERR_CHILD_NOT_ALLOWED: a # structural child (field/identity/source/validator/… — not an attr) is placed # under a parent whose registered childRules do not admit it (the structural diff --git a/server/rust/metaobjects/data/ERROR-CODES.json b/server/rust/metaobjects/data/ERROR-CODES.json index 737dbc341a..223217f0e0 100644 --- a/server/rust/metaobjects/data/ERROR-CODES.json +++ b/server/rust/metaobjects/data/ERROR-CODES.json @@ -64,6 +64,8 @@ "ERR_STORAGE_WITHOUT_OBJECT_REF": "@storage was set on a field that has no @objectRef.", "ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF": "ADR-0013: a field.object declares no @objectRef. A field.object models a typed nested value and REQUIRES @objectRef. The message states the whole ladder rather than only the escape hatch: a known key set is an object.value the field @objectRefs; dynamic keys over a known value type are a field.map (@objectRef for a value object, @valueType for a scalar); only a bag no reader pins a key in is @dbColumnType: jsonb on a field.string. Naming the escape hatch alone is what taught adopters to reach for the bag by default.", "ERR_UNRESOLVED_OBJECT_REF": "ADR-0042: a field.object / field.map @objectRef does not resolve to any object in the loaded tree (a dangling target). The ref resolves package-locally when bare (referrer's package, else root-level) and exactly when FQN — a bare cross-package ref no longer binds elsewhere. The error names same-short-name objects in other packages so the author can qualify it.", + "ERR_REF_UNRESOLVED": "spec/metamodel-definitions.md: an attribute whose definition carries the reference facet (`ref`) names a node that resolves to nothing, by the typed lookup or by the untyped lookup the loader runs to choose its error. The default code when the facet names no `errorCode`.", + "ERR_REF_WRONG_KIND": "spec/metamodel-definitions.md: an attribute whose definition carries the reference facet (`ref`) names a node of another type than the facet's `targetType`, or a subtype outside its `targetSubTypes`. The default code when the facet names no `errorCode`.", "ERR_RESERVED_ATTR": "An @-prefixed reserved structural keyword (e.g. @name, @isArray, @children) was used as an inline attribute.", "ERR_SCOPE_PATTERN_INVALID": "Phase-1 metadata-source-resolution: a scope include/exclude package pattern is malformed (empty pattern or empty :: segment).", "ERR_SOURCE_NO_PRIMARY": "An object declares source nodes but none has role=primary.", diff --git a/server/typescript/packages/metadata/src/errors.ts b/server/typescript/packages/metadata/src/errors.ts index 8ad5c605c8..94b84b5d8e 100644 --- a/server/typescript/packages/metadata/src/errors.ts +++ b/server/typescript/packages/metadata/src/errors.ts @@ -174,6 +174,10 @@ export const ERROR_CODES = [ // package-locally (referrer's package, else root-level); FQN refs resolve // exactly — a bare cross-package ref no longer binds elsewhere. "ERR_UNRESOLVED_OBJECT_REF", + // spec/metamodel-definitions.md — the reference facet's default codes: the value + // resolves to nothing, or to a node of the wrong type or subtype. + "ERR_REF_UNRESOLVED", + "ERR_REF_WRONG_KIND", // Source v2 (ADR-0007) error codes — enforcement added during the source-v2 rollout. "ERR_RESERVED_ATTR", "ERR_SOURCE_NO_PRIMARY", diff --git a/spec/metamodel-definitions.md b/spec/metamodel-definitions.md index 4671d1f089..3d17b2d6e9 100644 --- a/spec/metamodel-definitions.md +++ b/spec/metamodel-definitions.md @@ -66,7 +66,7 @@ Rules on where the facet may appear: 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 conformance fixture raises them. + `fixtures/conformance/ERROR-CODES.json`. **Existing references keep their codes.** Core declares four references in TypeScript code today (`core-types.ts`: `relationship.* @objectRef` raises `ERR_INVALID_RELATIONSHIP`, @@ -171,6 +171,10 @@ A value raises at most one error, the first that fails. Each step's message name 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 a reference target, the ancestors are the nodes the lookup path went through, not the +target's physical parents. A target reached through an inherited child belongs to the system the +lookup path names: `Ledger.clerk`, where `Ledger` inherits `clerk` from `Parcels`, is in +`Ledger`, not in `Parcels`. 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 @@ -188,11 +192,15 @@ facet that sets `sameSystem` before then can never pass and no definition file s ## Status -The format and the schema are specified here. No definition file uses `ref` yet. The -TypeScript spec reader reads it and its loader enforces it (`provider-data.ts`, -`loader/symbol-table.ts`, `loader/validation-registry.ts`); its registry manifest writes the -facet as described above. The other ports learn to read and enforce the facet in their own -changes, while no definition file uses it, so no registry output changes. The two default codes -join `fixtures/conformance/ERROR-CODES.json` in the change that adds the two worked cases as -fixtures, since every port's catalog test reads that one file. The four existing core references -then move from code into the definition files, keeping their codes. +The format and the schema are specified here. No definition file uses `ref` yet. + +Ports whose spec reader reads and enforces `ref`: TypeScript. + +A port joins that line in its own change, while no definition file uses the facet, so no +registry output changes. A port on the line writes the facet in its registry manifest as +described above. The two default codes are in `fixtures/conformance/ERROR-CODES.json` and its +vendored Rust copy, and in the TypeScript, Python, Java (Kotlin shares it) and C# error-code +catalogs. Rust lists only the codes it raises, so its reader change adds them there. The two +worked cases become conformance fixtures, and the four existing core references move from code +into the definition files keeping their codes, in the change that first registers vocabulary +using the facet. From f0224eae577484d61170680d8432260cc191bf3a Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 3 Dec 2026 00:54:24 -0500 Subject: [PATCH 11/12] no-mistakes(document): Fragment reader entry; fix stale facet note --- CHANGELOG.md | 14 -------------- .../adr-0070-systems-and-reference-facet.md | 3 ++- changelog.d/typescript-reference-facet-reader.md | 13 +++++++++++++ 3 files changed, 15 insertions(+), 15 deletions(-) create mode 100644 changelog.d/typescript-reference-facet-reader.md diff --git a/CHANGELOG.md b/CHANGELOG.md index fa2539d196..13d261aca3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,20 +10,6 @@ here.** ## [Unreleased] -- **The TypeScript loader reads and enforces the reference facet** (`ref` on a `type: "attr"` - entry of a provider definition, `spec/metamodel-definitions.md`). A reference attribute can now - say in data what it may name (target type, admitted subtypes, same system), and the loader - checks it with no code per provider: the lookup is typed by the target, a dotted value resolves - `System.child` and `pkg::System.child`, a bare value is looked for in the referrer's own - containers first, and a value that names nothing (`ERR_REF_UNRESOLVED`), the wrong kind of node - (`ERR_REF_WRONG_KIND`) or a node of another system (the facet's own code) is refused. The - registry manifest writes `ref` only on an attribute that has one. The two default codes are in - `fixtures/conformance/ERROR-CODES.json` and in the TypeScript, Python, Java and C# error-code - catalogs. No definition file uses the - facet yet, so no registry, manifest or generated output changes. A provider that sets - `TypeDefinition.references` in code: the descriptor's `targetSubType` is now `targetSubTypes` - (a list), `dottedFieldPath` is now `fieldPath`, and `errorCode` is optional. - - **`meta verify --uuid-values` lists the stored uuids that 1.3.0's write check refuses.** It is a read-only check to run before upgrading. With `--db ` (SQLite, libSQL or Postgres), or with `--dialect d1 [--d1 ] [--remote]`, it reads every place the model types `field.uuid`, in diff --git a/changelog.d/adr-0070-systems-and-reference-facet.md b/changelog.d/adr-0070-systems-and-reference-facet.md index fd65b6d2fb..0bcfe3fec8 100644 --- a/changelog.d/adr-0070-systems-and-reference-facet.md +++ b/changelog.d/adr-0070-systems-and-reference-facet.md @@ -8,4 +8,5 @@ (`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. + The TypeScript spec reader reads and enforces the facet (see the reader entry below); the other + ports do not read it yet. No definition file uses it, and `metamodelVersion` does not move. diff --git a/changelog.d/typescript-reference-facet-reader.md b/changelog.d/typescript-reference-facet-reader.md new file mode 100644 index 0000000000..e4fca6fec3 --- /dev/null +++ b/changelog.d/typescript-reference-facet-reader.md @@ -0,0 +1,13 @@ +- **The TypeScript loader reads and enforces the reference facet** (`ref` on a `type: "attr"` + entry of a provider definition, `spec/metamodel-definitions.md`). A reference attribute can now + say in data what it may name (target type, admitted subtypes, same system), and the loader + checks it with no code per provider: the lookup is typed by the target, a dotted value resolves + `System.child` and `pkg::System.child`, a bare value is looked for in the referrer's own + containers first, and a value that names nothing (`ERR_REF_UNRESOLVED`), the wrong kind of node + (`ERR_REF_WRONG_KIND`) or a node of another system (the facet's own code) is refused. The + registry manifest writes `ref` only on an attribute that has one. The two default codes are in + `fixtures/conformance/ERROR-CODES.json` and in the TypeScript, Python, Java and C# error-code + catalogs. No definition file uses the facet yet, so no registry, manifest or generated output + changes. A provider that sets `TypeDefinition.references` in code: the descriptor's + `targetSubType` is now `targetSubTypes` (a list), `dottedFieldPath` is now `fieldPath`, and + `errorCode` is optional. From 9f0e7f280aa712bd16b6730d29f865ad912037d1 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 3 Dec 2026 01:25:08 -0500 Subject: [PATCH 12/12] no-mistakes(document): correct stale notes on nested references --- docs/features/extending-with-providers.md | 7 ++++--- packs/systems/README.md | 3 ++- packs/systems/typescript/src/refs.ts | 15 ++++++++------- spec/metamodel-definitions.md | 2 +- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/docs/features/extending-with-providers.md b/docs/features/extending-with-providers.md index 7593553b5c..110a7411e4 100644 --- a/docs/features/extending-with-providers.md +++ b/docs/features/extending-with-providers.md @@ -168,9 +168,10 @@ file format) is covered by core's package version (`docs/compatibility-policy.md `spec/metamodel/*.json` format, and register it with `applyProviderDefinition(registry, definition, factories, validators?)` from `@metaobjectsdev/metadata`. `factories` maps each `"."` to the function that constructs its node; the optional `validators` map gives -a type a `NodeValidator`, for a rule the data cannot state (a reference to a nested node, say). -The bundled packs register this way, and so do the independent packs: `packs/systems/` is a -worked example. +a type a `NodeValidator`, for a rule the data cannot state. What a reference attribute may name, +a nested node included, is data: see [the reference facet](../../spec/metamodel-definitions.md#the-reference-facet) +and, there, which ports read it. The bundled packs register this way, and so do the independent +packs: `packs/systems/` is a worked example. ## Two registration modes diff --git a/packs/systems/README.md b/packs/systems/README.md index 44d327500f..6258facc04 100644 --- a/packs/systems/README.md +++ b/packs/systems/README.md @@ -28,7 +28,8 @@ Apps and resources are children of a system, so they are addressed the way the l any nested node (ADR-0059): `System.child` (`Shop.db`), or `pkg::System.child` from another package. A bare name means a node of the referrer's own system (of the kind the attribute wants, when an app and a resource share the name), then a top-level node of that name in the -referrer's package. This bare-name rule is the systems packs' convention, not the loader's. +referrer's package. The systems packs apply this rule in their own validators, not through the +loader's [reference facet](../../spec/metamodel-definitions.md#the-reference-facet). - `@needs` must name `resource.*` nodes, and `@calls` must name `app.*` or `system.external` nodes. A name that resolves to nothing, or to the wrong kind of node, fails the load with diff --git a/packs/systems/typescript/src/refs.ts b/packs/systems/typescript/src/refs.ts index a66eecf8d5..317147f360 100644 --- a/packs/systems/typescript/src/refs.ts +++ b/packs/systems/typescript/src/refs.ts @@ -1,12 +1,13 @@ // Resolving a reference to a node inside a system. // -// Apps and resources are children of a system.internal, so they are not top-level nodes -// and the loader's reference descriptors (which bind top-level nodes only) cannot reach -// them. They are addressed the house way instead (ADR-0059): `System.child` binds the -// system among the top-level nodes and walks to its child, and `pkg::System.child` -// does so from another package. A bare name is a convenience for the common case, a -// node in the referrer's own system, then a top-level node of that name (an outside -// system declared at the document root). +// Apps and resources are children of a system.internal, so they are not top-level nodes. +// The pack resolves them in its own validator: its supported core range (>=1.3.0) includes +// releases whose loader reference descriptors bind top-level nodes only, and @calls admits +// two target types, which one reference facet cannot name. They are addressed the house +// way (ADR-0059): `System.child` binds the system among the top-level nodes and walks to +// its child, and `pkg::System.child` does so from another package. A bare name is a +// convenience for the common case, a node in the referrer's own system, then a top-level +// node of that name (an outside system declared at the document root). import { CHILD_REF_SEPARATOR, diff --git a/spec/metamodel-definitions.md b/spec/metamodel-definitions.md index 172c114c26..65c08b6cbc 100644 --- a/spec/metamodel-definitions.md +++ b/spec/metamodel-definitions.md @@ -53,7 +53,7 @@ of data, and every port's loader enforces it without code of its own for each pa |---|---|---| | `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`). | +| `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`. `identity.reference @references` has this shape. | | `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`. |