Skip to content

feat(metadata): read and enforce the reference facet in the TypeScript loader - #695

Merged
dmealing merged 13 commits into
mainfrom
fm/mo-140-w1-b1-ts
Dec 3, 2026
Merged

dmealing merged 13 commits into
mainfrom
fm/mo-140-w1-b1-ts

Conversation

@dmealing

@dmealing dmealing commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

What Changed

  • The TypeScript spec reader now accepts and validates ref on a provider definition's attribute entry, and the loader enforces it. Lookup is typed by target and resolves System.child, pkg::System.child (including inherited children) and bare names from the referrer's containers first. It checks resolution, allowed subtypes and same-system, then rewrites the value to a canonical spelling only if that spelling reloads to the same target. The registry manifest writes ref only on attributes that have it. No definition file uses the facet yet.
  • For providers that set TypeDefinition.references in code, targetSubType becomes the list targetSubTypes, dottedFieldPath becomes fieldPath, and errorCode is now optional. The symbol table moves to loader/symbol-table.ts, the reference facet types and default codes are exported, and new tests in reference-facet.test.ts cover the facet with a test provider.
  • ERR_REF_UNRESOLVED and ERR_REF_WRONG_KIND are added to the shared error-code fixture, its vendored Rust copy, and the TypeScript, Python and Java catalogs. The spec now defines the manifest key order, inherited-child and canonical-spelling rules, and lists TypeScript beside C# as ports that read the facet. Related docs, comments and a changelog fragment are updated.

This is the second no-mistakes run on this branch.

Validation

Risk Assessment

✅ Low: The facet is read only, and no definition file uses it yet, so no registry, manifest or generated output changes. Existing core references keep their error codes. The merge with main left no duplicate error codes, the Status line matches the owner's decision, and earlier rounds already reviewed the remaining logic.

Testing

I drove the reference facet through the real meta CLI and the public library with a disposable test provider, and every scenario behaved as the spec describes. The valid model, including a role and an app both named api, verified clean. Each broken variant exited 1 with the expected code. Canonical spellings reloaded to the same targets. A base-versus-target comparison found no differences in 575 conformance fixtures (5 with non-core providers were skipped in this comparison), an unchanged registry manifest with no ref key, and identical codes and messages for the four core reference errors sampled. Broad regression came from the configured scripts/ci-local.sh --affected --strict-toolchains run, which had already passed at this commit. The change has no UI, so the evidence is CLI and library transcripts. The throwaway project was removed and the worktree is clean.

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
An adopter registers a provider with ref and runs meta verify: a valid model passes (role and app both named api, bare, dotted, qualified and list values), and unresolved, wrong-kind, wrong-subt… ✅ pass live cli-verify-reference-facet.log: valid model exit 0; ERR_REF_UNRESOLVED, ERR_REF_WRONG_KIND (kind and subtype), ERR_RUNSAS_OTHER_SYSTEM and a bad list element each exit 1 with a message naming the attr…
A library user serializes a loaded model to canonical JSON and reloads it: every reference binds the same target, inherited paths such as Ledger.clerk are kept, and attempts to cross systems or use… ✅ pass live library-canonical-roundtrip.log: clean loads report errors=0, sameValuesAndTargets=true and idempotent=true; Parcels.clerk from Ledger raises ERR_RUNSAS_OTHER_SYSTEM; the shared intermediate api i…
A user with no facet in their vocabulary upgrades and sees no change: same loader errors, warnings and canonical output, same registry manifest, and core references keep their error codes ✅ pass live base-vs-target-no-output-change.log: 575 conformance fixtures identical and 0 differing (5 non-core-provider fixtures skipped here); manifest equals base and the committed expected-registry.json with…
Evidence: meta verify transcript: adopter provider with the ref facet (valid and broken models)
# meta CLI (this branch, c510e09ae1) against a throwaway adopter project whose metaobjects.config.ts registers a provider using the ref facet
--- metaobjects.config.ts
import { defineConfig } from "@metaobjectsdev/cli";
import { applyProviderDefinition, MetaData } from "@metaobjectsdev/metadata";

class Node extends MetaData {}
const attr = (name: string, ref: object, extra: object = {}) =>
  ({ type: "attr", subType: "string", name, min: 0, max: 1, description: name, ref, ...extra });
const any = (type: string) => ({ type, subType: "*", name: "*", min: 0, max: null });

const definition = {
  provider: "adopter-systems",
  types: [
    { type: "system", subType: "software", description: "system", children: [any("app"), any("role"), any("resource")] },
    { type: "app", subType: "service", description: "app", children: [
      attr("runsAs", { targetType: "role", sameSystem: true, wrongSystemCode: "ERR_RUNSAS_OTHER_SYSTEM" }),
      attr("calls", { targetType: "app" }, { isArray: true }),
    ] },
    { type: "role", subType: "service", description: "role", children: [any("grant")] },
    { type: "grant", subType: "rdb", description: "grant", children: [
      attr("resource", { targetType: "resource", targetSubTypes: ["rdb"], sameSystem: true, wrongSystemCode: "ERR_GRANT_CROSSES_SYSTEM" }),
    ] },
    { type: "resource", subType: "rdb", description: "db" },
    { type: "resource", subType: "queue", description: "queue" },
  ],
  extends: [{ type: "metadata", subType: "root", children: [any("system")] }],
};
const factories = Object.fromEntries(definition.types.map((t) =>
  [`${t.type}.${t.subType}`, (id: any, name: string) => new Node(id, name)]));

export default defineConfig({
  outDir: "out",
  dialect: "sqlite",
  providers: [{ id: "adopter-systems", description: "adopter systems",
    registerTypes(r: any) { applyProviderDefinition(r, definition as any, factories as any); } }],
  generators: [],
});

===== model-ok =====
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 }
          - app.service: { name: worker, runsAs: "acme::Parcels.api", calls: [api, Parcels.worker] }
$ meta verify --templates
meta: meta verify — no template.* nodes found; the template gate had nothing to check.
meta: meta verify — not run: schema (--db <url>), codegen (--codegen), deps (--deps), replay (--replay)
verify[6]{gate,ran,ok}:
  templates,true,true
  schema,false,true
  codegen,false,true
  deps,false,true
  requirements,true,true
  replay,false,true
exitCode: 0
summary: "2 gate(s) ran, all clean"
help[1]: no drift and nothing advisory to answer — nothing to do
antiPatterns:
  status: ran
  total: 0
  rows: []
requirements:
  status: ran
  total: 0
  rows: []
overlays:
  status: ran
  total: 0
  rows: []
names:
  status: ran
  total: 0
  rows: []
deprecations:
  status: ran
  total: 0
  rows: []
fields:
  status: ran
  total: 0
  rows: []
notRepresented[2]: "per-gate drift detail for every gate but schema (which template variable drifted, which generated file differs, which migration failed to replay) — printed as text on stderr; this payload carries each gate's pass/fail verdict, and the schema gate's differences in schemaDrift",the loader's own warnings and the agent-context/manifest advisories — printed as text on stderr
exit=0

===== unresolved =====
(diff from model-ok)
13c13
<           - app.service: { name: api, runsAs: api }
---
>           - app.service: { name: api, runsAs: nobody }
$ meta verify --templates
meta: failed to load metadata: ERR_REF_UNRESOLVED: app.service "Parcels.api" @runsAs "nobody" does not resolve to a role.
  in meta.systems.yaml at $['metadata.root'].children[0]['system.software'].children[3]['app.service']
error: "failed to load metadata: app.service \"Parcels.api\" @runsAs \"nobody\" does not resolve to a role."
code: ERR_REF_UNRESOLVED
files[1]: meta.systems.yaml
jsonPath: "$['metadata.root'].children[0]['system.software'].children[3]['app.service']"
hint: fix the metadata error above and re-run
exit=1

===== wrongkind =====
(diff from model-ok)
13c13
<           - app.service: { name: api, runsAs: api }
---
>           - app.service: { name: api, runsAs: db }
$ meta verify --templates
meta: failed to load metadata: ERR_REF_WRONG_KIND: app.service "Parcels.api" @runsAs "db" names resource.rdb "db", not a role.
  in meta.systems.yaml at $['metadata.root'].children[0]['system.software'].children[3]['app.service']
error: "failed to load metadata: app.service \"Parcels.api\" @runsAs \"db\" names resource.rdb \"db\", not a role."
code: ERR_REF_WRONG_KIND
files[1]: meta.systems.yaml
jsonPath: "$['metadata.root'].children[0]['system.software'].children[3]['app.service']"
hint: fix the metadata error above and re-run
exit=1

===== wrongsubtype =====
(diff from model-ok)
12c12
<                 - grant.rdb: { name: g1, resource: db }
---
>                 - grant.rdb: { name: g1, resource: jobs }
$ meta verify --templates
meta: failed to load metadata: ERR_REF_WRONG_KIND: grant.rdb "api.g1" @resource "jobs" resolves to resource.queue "jobs" in system "acme::Parcels", not resource.rdb.
  in meta.systems.yaml at $['metadata.root'].children[0]['system.software'].children[2]['role.service'].children[0]['grant.rdb']
error: "failed to load metadata: grant.rdb \"api.g1\" @resource \"jobs\" resolves to resource.queue \"jobs\" in system \"acme::Parcels\", not resource.rdb."
code: ERR_REF_WRONG_KIND
files[1]: meta.systems.yaml
jsonPath: "$['metadata.root'].children[0]['system.software'].children[2]['role.service'].children[0]['grant.rdb']"
hint: fix the metadata error above and re-run
exit=1

===== crosses =====
(diff from model-ok)
14a15,18
>     - system.software:
>         name: Ledger
>         children:
>           - app.service: { name: web, runsAs: "acme::Parcels.api" }
$ meta verify --templates
meta: failed to load metadata: ERR_RUNSAS_OTHER_SYSTEM: app.service "Ledger.web" @runsAs "acme::Parcels.api" resolves to role.service "api" in system "acme::Parcels", but it must be in the same system as the node that declares it, which is in system "acme::Ledger".
  in meta.systems.yaml at $['metadata.root'].children[1]['system.software'].children[0]['app.service']
error: "failed to load metadata: app.service \"Ledger.web\" @runsAs \"acme::Parcels.api\" resolves to role.service \"api\" in system \"acme::Parcels\", but it must be in the same system as the node that declares it, which is in system \"acme::Ledger\"."
code: ERR_RUNSAS_OTHER_SYSTEM
files[1]: meta.systems.yaml
jsonPath: "$['metadata.root'].children[1]['system.software'].children[0]['app.service']"
hint: fix the metadata error above and re-run
exit=1

===== list =====
(diff from model-ok)
14c14
<           - app.service: { name: worker, runsAs: "acme::Parcels.api", calls: [api, Parcels.worker] }
---
>           - app.service: { name: worker, runsAs: "acme::Parcels.api", calls: [api, Parcels.ghost, db] }
$ meta verify --templates
meta: failed to load metadata: ERR_REF_UNRESOLVED: app.service "Parcels.worker" @calls "Parcels.ghost" does not resolve to a app.
  in meta.systems.yaml at $['metadata.root'].children[0]['system.software'].children[4]['app.service']
error: "failed to load metadata: app.service \"Parcels.worker\" @calls \"Parcels.ghost\" does not resolve to a app."
code: ERR_REF_UNRESOLVED
files[1]: meta.systems.yaml
jsonPath: "$['metadata.root'].children[0]['system.software'].children[4]['app.service']"
hint: fix the metadata error above and re-run
exit=1
Evidence: Library load, canonical serialize and reload transcript, with adversarial cases

===== bare, dotted, qualified; role and app both named api =====
metadata.root:
  package: acme
  children:

    - system.software:
        name: Parcels
        children:
          - role.service: { name: api }
          - role.service: { name: ops }
          - app.service: { name: api, runsAs: api }
          - app.service: { name: worker, runsAs: Parcels.ops, calls: [api, Parcels.worker, "acme::Parcels.worker"] }
loaded:
  system:Parcels/app:api @runsAs = "acme::Parcels.api"  ->  system:Parcels/role:api
  system:Parcels/app:worker @runsAs = "acme::Parcels.ops"  ->  system:Parcels/role:ops
  system:Parcels/app:worker @calls = ["acme::Parcels.api","acme::Parcels.worker","acme::Parcels.worker"]  ->  system:Parcels/app:api, system:Parcels/app:worker, system:Parcels/app:worker
reload of canonical JSON: errors=0 sameValuesAndTargets=true idempotent=true

===== inherited child: Ledger.clerk stays on Ledger and is in system Ledger =====
metadata.root:
  package: acme
  children:

    - system.software:
        name: Parcels
        abstract: true
        children:
          - role.service: { name: clerk }
    - system.software:
        name: Ledger
        extends: Parcels
        children:
          - app.service: { name: web, runsAs: Ledger.clerk }
loaded:
  system:Ledger/app:web @runsAs = "acme::Ledger.clerk"  ->  system:Parcels/role:clerk
reload of canonical JSON: errors=0 sameValuesAndTargets=true idempotent=true

===== ADVERSARIAL inherited child addressed through the base system from Ledger crosses systems =====
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: Parcels.clerk }
errors:
  ERR_RUNSAS_OTHER_SYSTEM: app.service "Ledger.web" @runsAs "Parcels.clerk" resolves to role.service "clerk" in system "acme::Parcels", but it must be in the same system as the node that declares it, which is in system "acme::Ledger".

===== ADVERSARIAL inherited reference keeps its meaning where written (inheritor has its own role api) =====
metadata.root:
  package: acme
  children:

    - system.software:
        name: Parcels
        children:
          - role.service: { name: api }
          - app.service: { name: base, abstract: true, runsAs: api }
    - system.software:
        name: Ledger
        children:
          - role.service: { name: api }
          - app.service: { name: web, extends: acme::Parcels.base }
loaded:
  system:Parcels/app:base @runsAs = "acme::Parcels.api"  ->  system:Parcels/role:api
reload of canonical JSON: errors=0 sameValuesAndTargets=true idempotent=true

===== ADVERSARIAL intermediate segment shared by an app and a role =====
metadata.root:
  package: acme
  children:

    - system.software:
        name: Parcels
        children:
          - role.service: { name: api, children: [ { grant.rdb: { name: x } } ] }
          - app.service: { name: api }
          - app.service: { name: w, calls: [Parcels.api.x] }
errors:
  ERR_REF_UNRESOLVED: app.service "Parcels.w" @calls "Parcels.api.x" does not resolve to a app.

===== ADVERSARIAL every bad element of a list is reported; two bad refs, two errors =====
metadata.root:
  package: acme
  children:

    - system.software:
        name: Parcels
        children:
          - resource.rdb: { name: db }
          - app.service: { name: worker, calls: [Parcels.ghost, db, Parcels.worker] }
errors:
  ERR_REF_UNRESOLVED: app.service "Parcels.worker" @calls "Parcels.ghost" does not resolve to a app.
  ERR_REF_WRONG_KIND: app.service "Parcels.worker" @calls "db" names resource.rdb "db", not a app.

===== ADVERSARIAL sameSystem declared outside any role; empty and trailing-dot segments =====
metadata.root:
  package: acme
  children:

    - system.software:
        name: Parcels
        children:
          - role.service: { name: api }
          - app.service: { name: w, runsAs: "Parcels..api" }
          - app.service: { name: v, runsAs: "Parcels.api." }
          - app.service: { name: u, runsAs: "..::..::Parcels.api" }
errors:
  ERR_REF_UNRESOLVED: app.service "Parcels.w" @runsAs "Parcels..api" does not resolve to a role.
  ERR_REF_UNRESOLVED: app.service "Parcels.v" @runsAs "Parcels.api." does not resolve to a role.
  ERR_BAD_ATTR_VALUE: app.service "Parcels.u" @runsAs "..::..::Parcels.api" climbs above the root package — each '..::' drops one segment of the declaring package.
exit=0
Evidence: Base versus target comparison: conformance corpus, registry manifest, core reference errors
base 99b6d20919 vs target c510e09ae1, core providers, strict
fixtures identical (errors+messages, warnings, canonical JSON): 575 (of which error fixtures: 320); skipped (non-core providers): 5; differing: 0
registry manifest: base==target true; target==committed expected-registry.json true; "ref" keys in target: 0

# field.object @objectRef missing
base [ "ERR_UNRESOLVED_OBJECT_REF: field.object \"Order.a\" @objectRef \"Nope\" does not resolve to an object." ]
target [ "ERR_UNRESOLVED_OBJECT_REF: field.object \"Order.a\" @objectRef \"Nope\" does not resolve to an object." ]

# field.map @objectRef missing
base [ "ERR_UNRESOLVED_OBJECT_REF: field.map \"Order.a\" @objectRef \"Nope\" does not resolve to an object." ]
target [ "ERR_UNRESOLVED_OBJECT_REF: field.map \"Order.a\" @objectRef \"Nope\" does not resolve to an object." ]

# relationship @objectRef missing
base [ "ERR_INVALID_RELATIONSHIP: relationship.association \"Order.a\" @objectRef \"Nope\" does not resolve to an object." ]
target [ "ERR_INVALID_RELATIONSHIP: relationship.association \"Order.a\" @objectRef \"Nope\" does not resolve to an object." ]

# identity.reference @references missing
base [ "ERR_INVALID_REFERENCE: identity.reference \"Order.a\" @references \"Nope.id\" does not resolve to an object." ]
target [ "ERR_INVALID_REFERENCE: identity.reference \"Order.a\" @references \"Nope.id\" does not resolve to an object." ]
exit=0
Evidence: Round-trip driver script
// Drives the public library surface: load -> canonicalSerialize -> reload; targets must be the same nodes.
import { MetaDataLoader, InMemoryStringSource, composeRegistry, coreProviders, canonicalSerialize, refTarget } from "../server/typescript/packages/metadata/src/index.js";
import cfg from "./provider.js";
const registry = () => composeRegistry([...coreProviders, cfg]);
async function load(text: string, format: "yaml" | "json") {
  const l = new MetaDataLoader({ registry: registry(), strict: true });
  return l.load([new InMemoryStringSource(text, { id: "m." + format, format })]);
}
const path = (n: any): string => { const o: string[] = []; for (; n && n.parent; n = n.parent) o.unshift(`${n.type}:${n.name}`); return o.join("/"); };
function refs(root: any) {
  const out: string[] = [];
  const walk = (n: any) => {
    for (const a of ["runsAs", "calls", "resource"]) {
      const m = n.ownMetaAttrs?.().find((x: any) => x.name === a);
      if (!m) continue;
      const t = Array.isArray(m.resolvedTarget) ? m.resolvedTarget.map(path).join(", ") : path(m.resolvedTarget);
      out.push(`${path(n)} @${a} = ${JSON.stringify(m.value)}  ->  ${t}`);
    }
    for (const c of n.ownChildren()) walk(c);
  };
  walk(root); return out;
}
async function drive(label: string, yaml: string) {
  console.log(`\n===== ${label} =====\n${yaml.trim()}`);
  const a = await load(yaml, "yaml");
  if (a.errors.length) { console.log("errors:"); for (const e of a.errors as any[]) console.log(`  ${e.code}: ${e.message}`); return; }
  const r1 = refs(a.root); console.log("loaded:"); r1.forEach((l) => console.log("  " + l));
  const json = canonicalSerialize(a.root);
  const b = await load(json, "json");
  const r2 = refs(b.root);
  console.log(`reload of canonical JSON: errors=${b.errors.length} sameValuesAndTargets=${JSON.stringify(r1) === JSON.stringify(r2)} idempotent=${canonicalSerialize(b.root) === json}`);
  if (JSON.stringify(r1) !== JSON.stringify(r2) || b.errors.length) { r2.forEach((l) => console.log("  reload " + l)); for (const e of b.errors as any[]) console.log(e.message); process.exitCode = 1; }
}
const M = (body: string) => `metadata.root:\n  package: acme\n  children:\n${body}`;
await drive("bare, dotted, qualified; role and app both named api", M(`
    - system.software:
        name: Parcels
        children:
          - role.service: { name: api }
          - role.service: { name: ops }
          - app.service: { name: api, runsAs: api }
          - app.service: { name: worker, runsAs: Parcels.ops, calls: [api, Parcels.worker, "acme::Parcels.worker"] }`));
await drive("inherited child: Ledger.clerk stays on Ledger and is in system Ledger", M(`
    - system.software:
        name: Parcels
        abstract: true
        children:
          - role.service: { name: clerk }
    - system.software:
        name: Ledger
        extends: Parcels
        children:
          - app.service: { name: web, runsAs: Ledger.clerk }`));
await drive("ADVERSARIAL inherited child addressed through the base system from Ledger crosses systems", M(`
    - system.software:
        name: Parcels
        children:
          - role.service: { name: clerk }
    - system.software:
        name: Ledger
        extends: Parcels
        children:
          - app.service: { name: web, runsAs: Parcels.clerk }`));
await drive("ADVERSARIAL inherited reference keeps its meaning where written (inheritor has its own role api)", M(`
    - system.software:
        name: Parcels
        children:
          - role.service: { name: api }
          - app.service: { name: base, abstract: true, runsAs: api }
    - system.software:
        name: Ledger
        children:
          - role.service: { name: api }
          - app.service: { name: web, extends: acme::Parcels.base }`));
await drive("ADVERSARIAL intermediate segment shared by an app and a role", M(`
    - system.software:
        name: Parcels
        children:
          - role.service: { name: api, children: [ { grant.rdb: { name: x } } ] }
          - app.service: { name: api }
          - app.service: { name: w, calls: [Parcels.api.x] }`));
await drive("ADVERSARIAL every bad element of a list is reported; two bad refs, two errors", M(`
    - system.software:
        name: Parcels
        children:
          - resource.rdb: { name: db }
          - app.service: { name: worker, calls: [Parcels.ghost, db, Parcels.worker] }`));
await drive("ADVERSARIAL sameSystem declared outside any role; empty and trailing-dot segments", M(`
    - system.software:
        name: Parcels
        children:
          - role.service: { name: api }
          - app.service: { name: w, runsAs: "Parcels..api" }
          - app.service: { name: v, runsAs: "Parcels.api." }
          - app.service: { name: u, runsAs: "..::..::Parcels.api" }`));
Evidence: Test provider used by the round-trip script
import { applyProviderDefinition, MetaData } from "../server/typescript/packages/metadata/src/index.js";

class Node extends MetaData {}
const attr = (name: string, ref: object, extra: object = {}) =>
  ({ type: "attr", subType: "string", name, min: 0, max: 1, description: name, ref, ...extra });
const any = (type: string) => ({ type, subType: "*", name: "*", min: 0, max: null });

const definition = {
  provider: "adopter-systems",
  types: [
    { type: "system", subType: "software", description: "system", children: [any("app"), any("role"), any("resource")] },
    { type: "app", subType: "service", description: "app", children: [
      attr("runsAs", { targetType: "role", sameSystem: true, wrongSystemCode: "ERR_RUNSAS_OTHER_SYSTEM" }),
      attr("calls", { targetType: "app" }, { isArray: true }),
    ] },
    { type: "role", subType: "service", description: "role", children: [any("grant")] },
    { type: "grant", subType: "rdb", description: "grant", children: [
      attr("resource", { targetType: "resource", targetSubTypes: ["rdb"], sameSystem: true, wrongSystemCode: "ERR_GRANT_CROSSES_SYSTEM" }),
    ] },
    { type: "resource", subType: "rdb", description: "db" },
    { type: "resource", subType: "queue", description: "queue" },
  ],
  extends: [{ type: "metadata", subType: "root", children: [any("system")] }],
};
const factories = Object.fromEntries(definition.types.map((t) =>
  [`${t.type}.${t.subType}`, (id: any, name: string) => new Node(id, name)]));

export default { id: "adopter-systems", description: "adopter systems",
    registerTypes(r: any) { applyProviderDefinition(r, definition as any, factories as any); } };
Evidence: Base versus target comparison script
// Differential: base-commit loader vs target loader over the shared conformance corpus, plus the registry manifest.
import { join } from "node:path";
import { readFileSync } from "node:fs";
import { discoverFixtures, isContractOnlyFixture, isDocsOnlyFixture } from "@metaobjectsdev/conformance";
const W = join(import.meta.dir, "..");
const load = async (root: string) => {
  const s = join(root, "server/typescript/packages/metadata");
  return {
    ...(await import(join(s, "src/index.ts"))),
    ...(await import(join(s, "src/loader/sources/directory-source.ts"))),
    ...(await import(join(s, "src/registry-manifest.ts"))),
  };
};
const base: any = await load(join(import.meta.dir, "base"));
const head: any = await load(W);
// Fixture provider sets, built per side from that side's modules.
const { PROVIDERS } = await import(join(W, "server/typescript/packages/metadata/test/conformance/adapter.ts"));
const corpus = join(W, "fixtures/conformance");
const fixtures = (await discoverFixtures(corpus)).filter((f) => !isDocsOnlyFixture(f) && !isContractOnlyFixture(f));
async function run(m: any, fix: any) {
  try {
    const reg = m.composeRegistry(m.coreProviders);
    const r = await new m.MetaDataLoader({ registry: reg, strict: true }).load(await new m.DirectorySource(fix.inputDir).expand());
    return JSON.stringify({
      errors: r.errors.map((e: any) => [e.code, e.message]),
      warnings: (r.warnings ?? []).map((w: any) => w.message ?? w),
      canonical: r.errors.length ? null : m.canonicalSerialize(r.root),
    });
  } catch (e: any) { return "threw " + e.message; }
}
let same = 0, withErrors = 0, skippedProviders = 0; const differ: any[] = [];
for (const f of fixtures) {
  if (f.providers.some((p: string) => !/^metaobjects-/.test(p))) { skippedProviders++; continue; }
  const a = await run(base, f), b = await run(head, f);
  if (a === b) { same++; if (a.includes('"errors":[[')) withErrors++; } else differ.push([f.name, a.slice(0, 600), b.slice(0, 600)]);
}
console.log(`base 99b6d20919 vs target c510e09ae1, core providers, strict`);
console.log(`fixtures identical (errors+messages, warnings, canonical JSON): ${same} (of which error fixtures: ${withErrors}); skipped (non-core providers): ${skippedProviders}; differing: ${differ.length}`);
for (const d of differ) console.log(d.join("\n  "), "\n");
const mb = base.emitRegistryManifest(base.composeRegistry(base.coreProviders));
const mh = head.emitRegistryManifest(head.composeRegistry(head.coreProviders));
const committed = readFileSync(join(W, "fixtures/registry-conformance/expected-registry.json"), "utf8");
console.log(`registry manifest: base==target ${mb === mh}; target==committed expected-registry.json ${mh === committed}; "ref" keys in target: ${(mh.match(/"ref":/g) ?? []).length}`);
// Core reference codes and messages, including list and field-path forms.
const model = (child: string) => JSON.stringify({ "metadata.root": { package: "shop", children: [
  { "object.entity": { name: "Order", children: [ { "field.long": { name: "id" } }, JSON.parse(child) ] } } ] } });
for (const [label, child] of [
  ["field.object @objectRef missing", '{"field.object":{"name":"a","@objectRef":"Nope"}}'],
  ["field.map @objectRef missing", '{"field.map":{"name":"a","@objectRef":"Nope"}}'],
  ["relationship @objectRef missing", '{"relationship.association":{"name":"a","@objectRef":"Nope","@cardinality":"one"}}'],
  ["identity.reference @references missing", '{"identity.reference":{"name":"a","@fields":["id"],"@references":"Nope.id"}}'],
] as const) {
  console.log(`\n# ${label}`);
  for (const [side, m] of [["base", base], ["target", head]] as const) {
    const r = await new m.MetaDataLoader({ registry: m.composeRegistry(m.coreProviders), strict: true }).load([new m.InMemoryStringSource(model(child), { id: "m.json", format: "json" })]);
    console.log(side, r.errors.filter((e: any) => /REF|RELATIONSHIP/.test(e.code)).map((e: any) => `${e.code}: ${e.message}`));
  }
}

Pipeline

Updates from git push no-mistakes

✅ **Intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
An adopter registers a provider with ref and runs meta verify: a valid model passes (role and app both named api, bare, dotted, qualified and list values), and unresolved, wrong-kind, wrong-subt… ✅ pass live cli-verify-reference-facet.log: valid model exit 0; ERR_REF_UNRESOLVED, ERR_REF_WRONG_KIND (kind and subtype), ERR_RUNSAS_OTHER_SYSTEM and a bad list element each exit 1 with a message naming the attr…
A library user serializes a loaded model to canonical JSON and reloads it: every reference binds the same target, inherited paths such as Ledger.clerk are kept, and attempts to cross systems or use… ✅ pass live library-canonical-roundtrip.log: clean loads report errors=0, sameValuesAndTargets=true and idempotent=true; Parcels.clerk from Ledger raises ERR_RUNSAS_OTHER_SYSTEM; the shared intermediate api i…
A user with no facet in their vocabulary upgrades and sees no change: same loader errors, warnings and canonical output, same registry manifest, and core references keep their error codes ✅ pass live base-vs-target-no-output-change.log: 575 conformance fixtures identical and 0 differing (5 non-core-provider fixtures skipped here); manifest equals base and the committed expected-registry.json with…
  • scripts/ci-local.sh --affected --strict-toolchains
  • Broad regression came from the configured test command scripts/ci-local.sh --affected --strict-toolchains, which had already run and passed at target commit c510e09ae1. I did not re-run it, and I changed no source or test files.
  • bun server/typescript/packages/cli/bin/meta.ts verify --templates against a throwaway adopter project whose metaobjects.config.ts registers a provider using ref: one valid model, then unresolved, wrong kind, wrong subtype, crosses system and bad list element variants
  • bun roundtrip.ts: library load, then canonicalSerialize, then reload, comparing rewritten values and bound targets, with adversarial cases for inherited children and references, an ambiguous intermediate segment, two bad list elements, empty or trailing-dot segments and an over-dropping ..::
  • bun .tmp-diff.ts: base 99b6d20919 loader against the target loader over fixtures/conformance with core providers, the registry manifest against fixtures/registry-conformance/expected-registry.json, and the four existing core reference errors
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

…t 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.
# Conflicts:
#	changelog.d/adr-0070-systems-and-reference-facet.md
#	spec/metamodel-definitions.md
@dmealing
dmealing merged commit 34ee208 into main Dec 3, 2026
11 checks passed
@dmealing
dmealing deleted the fm/mo-140-w1-b1-ts branch December 3, 2026 06:40
dmealing added a commit that referenced this pull request Dec 3, 2026
…697)

The spec reader in providers.rs validates `ref` on an attr entry (refusing a bad facet, or
one on a structural child) and carries it to AttrSchema::reference. The registered walk
enforces it through a kind-typed symbol table: System.child and pkg::System.child, bare values
found in the referrer's containers first, an untyped lookup only for the wrong-kind code, and
sameSystem judged on the walked path. The reference pass writes the walked path and keeps a
value as written when its canonical spelling would not look up the same target. The registry
manifest writes `ref` only when present. A provider's own code keeps its spelling in
MetaError::provider_code. A parent-relative `..::Owner.field` value resolves its owner.

A same-document root-level node and a same-named packaged node are no longer merged, which
closes yaml-ref-root-escape: yaml-conformance is 19 of 19 with an empty ledger. No definition
file uses the facet, so no registry, manifest or generated output changes. Mirrors the
TypeScript (#695), C# (#694) and Java (#696) loaders.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant