From 5345eaf599bdd6f1f7ce00386f8bf62e7feb67dc Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Fri, 4 Dec 2026 19:23:22 -0500
Subject: [PATCH 1/8] feat(metadata): grants and the resource on a source in
every port
Adds ADR-0070 part 2 to metaobjects-systems-core in TypeScript, C#,
Java/Kotlin, Python and Rust:
- role grants: grant.rdb (@schema, @access, @maintain), grant.keyValue,
.objectStore, .document, .search, .queue and .stream, each naming a
resource of its own kind and its own system in @resource
(ERR_GRANT_CROSSES_SYSTEM), and grant.api (@api, @operations,
@credential).
- @runsAs must name a role.service of the app's own system
(ERR_RUNSAS_OTHER_SYSTEM).
- source.rdb takes @resource; new source.document (@resource,
@collection) and source.search (@resource, @index), registered by the
systems provider rather than core.
- Inside a system a name is used once per type: a second child of the same
type and name but another subtype is ERR_DUPLICATE_NAME. A same-subtype
redeclaration still merges.
Nine conformance fixtures, including the ambiguous bare @heldBy name that
PR 710 left untested. The TS and Python "targetSubTypes narrows" tests now
assert ERR_REF_WRONG_KIND on holder. Regenerated: the registry manifest,
the metamodel docs, the site reference and payload, the requirement
harness, plus requirement entries for the new subtypes.
---
AGENTS.md | 2 +-
changelog.d/systems-grants-and-sources.md | 29 ++
docs/CONFORMANCE.md | 10 +-
examples/showcase/site-payload.json | 4 +-
fixtures/conformance/ERROR-CODES.json | 4 +-
.../expected-errors.json | 15 +
.../input/meta.parcels.json | 30 ++
.../expected-errors.json | 15 +
.../input/meta.ledger.json | 35 ++
.../input/meta.parcels.json | 32 ++
.../expected-errors.json | 15 +
.../input/meta.parcels.json | 31 ++
.../expected-errors.json | 15 +
.../input/meta.parcels.json | 32 ++
.../expected-errors.json | 15 +
.../input/meta.parcels.json | 32 ++
.../expected-errors.json | 15 +
.../input/meta.ledger.json | 35 ++
.../input/meta.parcels.json | 32 ++
.../expected-errors.json | 15 +
.../input/meta.parcels.json | 45 ++
.../expected-errors.json | 15 +
.../input/meta.ledger.json | 35 ++
.../input/meta.parcels.json | 25 +
.../systems-grants-and-sources/expected.json | 292 +++++++++++
.../input/meta.ledger.json | 32 ++
.../input/meta.parcels.json | 262 ++++++++++
fixtures/metamodel-docs/data/INDEX.md.json | 57 +-
.../metamodel-docs/data/providers.md.json | 48 +-
.../metamodel-docs/data/types/app.md.json | 8 +-
.../metamodel-docs/data/types/grant.md.json | 379 ++++++++++++++
.../metamodel-docs/data/types/role.md.json | 30 +-
.../metamodel-docs/data/types/source.md.json | 83 ++-
fixtures/metamodel-docs/expected/INDEX.md | 13 +-
fixtures/metamodel-docs/expected/providers.md | 15 +-
fixtures/metamodel-docs/expected/types/app.md | 8 +-
.../metamodel-docs/expected/types/grant.md | 199 +++++++
.../metamodel-docs/expected/types/role.md | 10 +-
.../metamodel-docs/expected/types/source.md | 41 +-
.../expected-registry.json | 485 +++++++++++++++++-
fixtures/registry-conformance/providers.json | 3 +-
.../csharp/RequirementHarnessTests.cs | 42 +-
.../java/RequirementHarnessTest.java | 52 +-
.../kotlin/RequirementHarnessTest.kt | 52 +-
.../python/test_requirement_harness.py | 52 +-
.../typescript/requirement-harness.test.ts | 52 +-
metaobjects/meta.requirements.yaml | 96 +++-
scripts/check-requirements-ledger.ts | 2 +-
scripts/site/reference.test.ts | 4 +-
.../MetamodelDocsTests.cs | 2 +-
.../metamodel/provider-descriptions.json | 2 +-
.../ReferenceFacetTests.cs | 69 ++-
.../Core/Systems/SystemsMetaDataProvider.cs | 12 +-
server/csharp/MetaObjects/Errors.cs | 4 +
server/csharp/MetaObjects/Parser.cs | 15 +
.../Persistence/Source/SourceConstants.cs | 10 +
server/csharp/MetaObjects/Shared/BaseTypes.cs | 2 +
.../MetaObjects/SpecMetamodel/source.json | 2 +-
.../MetaObjects/SpecMetamodel/systems.json | 141 ++++-
.../metamodel/provider-descriptions.json | 2 +-
.../main/java/com/metaobjects/ErrorCode.java | 6 +
.../loader/parser/BaseMetaDataParser.java | 18 +-
.../validation/RegisteredValidation.java | 2 +-
.../metaobjects/source/DocumentSource.java | 30 ++
.../com/metaobjects/source/SearchSource.java | 30 ++
.../com/metaobjects/systems/SystemsNode.java | 6 +
.../systems/SystemsTypesMetaDataProvider.java | 59 ++-
.../validation/ReferenceFacetTest.java | 40 +-
server/python/src/metaobjects/core_types.py | 3 +-
server/python/src/metaobjects/errors.py | 4 +
server/python/src/metaobjects/loader/merge.py | 17 +
.../meta/core/systems/systems_provider.py | 10 +-
.../persistence/source/source_constants.py | 5 +
server/python/src/metaobjects/parser.py | 38 +-
.../metamodel/provider-descriptions.json | 2 +-
.../metaobjects/spec_metamodel/source.json | 2 +-
.../metaobjects/spec_metamodel/systems.json | 141 ++++-
.../python/tests/unit/test_reference_facet.py | 37 +-
.../metamodel/provider-descriptions.json | 2 +-
server/rust/metaobjects/data/ERROR-CODES.json | 4 +-
.../metaobjects/data/metamodel/source.json | 2 +-
.../metaobjects/data/metamodel/systems.json | 141 ++++-
server/rust/metaobjects/src/errors.rs | 9 +
server/rust/metaobjects/src/loader.rs | 10 +-
server/rust/metaobjects/src/parser.rs | 34 +-
.../metaobjects/src/validate/refs_tests.rs | 34 +-
.../tests/conformance-expected-failures.json | 2 +-
.../metamodel/provider-descriptions.json | 2 +-
.../src/core/systems/systems-constants.ts | 49 +-
.../systems/systems-definition.embedded.ts | 456 +++++++++++++++-
.../src/core/systems/systems-provider.ts | 14 +-
.../packages/metadata/src/errors.ts | 5 +-
.../packages/metadata/src/parser-core.ts | 17 +
.../persistence/source/source-constants.ts | 23 +-
.../source/source-definition.embedded.ts | 2 +-
.../metadata/src/shared/base-types.ts | 6 +-
.../metadata/test/definition-schema.test.ts | 15 +-
.../packages/metadata/test/index.test.ts | 4 +-
.../packages/metadata/test/provider.test.ts | 3 +-
.../metadata/test/reference-facet.test.ts | 37 +-
site-reference/index.html | 57 +-
site-reference/providers.html | 15 +-
site-reference/types/app.html | 8 +-
site-reference/types/grant.html | 447 ++++++++++++++++
site-reference/types/role.html | 20 +-
site-reference/types/source.html | 87 +++-
spec/metamodel-definitions.md | 9 +-
spec/metamodel/source.json | 2 +-
spec/metamodel/systems.json | 141 ++++-
.../metamodel/provider-descriptions.json | 2 +-
110 files changed, 4978 insertions(+), 242 deletions(-)
create mode 100644 changelog.d/systems-grants-and-sources.md
create mode 100644 fixtures/conformance/error-duplicate-name-in-system/expected-errors.json
create mode 100644 fixtures/conformance/error-duplicate-name-in-system/input/meta.parcels.json
create mode 100644 fixtures/conformance/error-grant-crosses-system/expected-errors.json
create mode 100644 fixtures/conformance/error-grant-crosses-system/input/meta.ledger.json
create mode 100644 fixtures/conformance/error-grant-crosses-system/input/meta.parcels.json
create mode 100644 fixtures/conformance/error-ref-ambiguous-heldby-bare-name/expected-errors.json
create mode 100644 fixtures/conformance/error-ref-ambiguous-heldby-bare-name/input/meta.parcels.json
create mode 100644 fixtures/conformance/error-ref-unresolved-grant-resource/expected-errors.json
create mode 100644 fixtures/conformance/error-ref-unresolved-grant-resource/input/meta.parcels.json
create mode 100644 fixtures/conformance/error-ref-wrong-kind-grant-rdb-on-queue/expected-errors.json
create mode 100644 fixtures/conformance/error-ref-wrong-kind-grant-rdb-on-queue/input/meta.parcels.json
create mode 100644 fixtures/conformance/error-ref-wrong-kind-grant-stream-on-other-system-queue/expected-errors.json
create mode 100644 fixtures/conformance/error-ref-wrong-kind-grant-stream-on-other-system-queue/input/meta.ledger.json
create mode 100644 fixtures/conformance/error-ref-wrong-kind-grant-stream-on-other-system-queue/input/meta.parcels.json
create mode 100644 fixtures/conformance/error-ref-wrong-kind-source-rdb-on-document/expected-errors.json
create mode 100644 fixtures/conformance/error-ref-wrong-kind-source-rdb-on-document/input/meta.parcels.json
create mode 100644 fixtures/conformance/error-runsas-other-system/expected-errors.json
create mode 100644 fixtures/conformance/error-runsas-other-system/input/meta.ledger.json
create mode 100644 fixtures/conformance/error-runsas-other-system/input/meta.parcels.json
create mode 100644 fixtures/conformance/systems-grants-and-sources/expected.json
create mode 100644 fixtures/conformance/systems-grants-and-sources/input/meta.ledger.json
create mode 100644 fixtures/conformance/systems-grants-and-sources/input/meta.parcels.json
create mode 100644 fixtures/metamodel-docs/data/types/grant.md.json
create mode 100644 fixtures/metamodel-docs/expected/types/grant.md
create mode 100644 server/java/metadata/src/main/java/com/metaobjects/source/DocumentSource.java
create mode 100644 server/java/metadata/src/main/java/com/metaobjects/source/SearchSource.java
create mode 100644 site-reference/types/grant.html
diff --git a/AGENTS.md b/AGENTS.md
index 4eb1697b48..2067a3986a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -74,7 +74,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken.
- **Kotlin** — `codegen-kotlin` (laid out by `KotlinWriter`, ADR-0063, on the JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres.
**Cross-port conformance corpora** (every port runs the shared corpus):
-- Metamodel: `fixtures/conformance/` (599 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green.
+- Metamodel: `fixtures/conformance/` (608 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green.
- Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python / C# / Rust byte-identical; the C# and Rust drift ledgers are empty (`docs/CONFORMANCE.md`).
- Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (the Node reference helper writes them; a native tool is equally first-class, ADR-0015 Amendment 2). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".)
- API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived.
diff --git a/changelog.d/systems-grants-and-sources.md b/changelog.d/systems-grants-and-sources.md
new file mode 100644
index 0000000000..6fc4704d44
--- /dev/null
+++ b/changelog.d/systems-grants-and-sources.md
@@ -0,0 +1,29 @@
+- **Grants and the resource on a source, in every port (ADR-0070, part 2).** A role now declares
+ what it may do with `grant` children, registered by `metaobjects-systems-core` in TypeScript,
+ C#, Java and Kotlin, Python and Rust. `grant.rdb` (`@schema`, `@access` of `owner`,
+ `readWrite` or `read`, `@maintain`), `grant.keyValue` (`@keyPrefix`), `grant.objectStore`
+ (`@prefix`), `grant.document` (`@collection`), `grant.search` (`@index`), `grant.queue` and
+ `grant.stream` each name a resource of their own kind in `@resource`, with a required,
+ closed `@access`. A grant on another system's resource is `ERR_GRANT_CROSSES_SYSTEM`, and one
+ on a resource of another kind is `ERR_REF_WRONG_KIND`. `grant.api` names an API in `@api`,
+ from any system, with optional `@operations` and `@credential`. A grant is unnamed, like a
+ binding. `@runsAs`, which already named a `role.service`, must now name one of the app's own
+ system: a role of another system is `ERR_RUNSAS_OTHER_SYSTEM`.
+ `source.rdb` takes an optional `@resource` naming the `resource.rdb` it lives in, and two new
+ source subtypes, `source.document` (`@resource`, `@collection`) and `source.search`
+ (`@resource`, `@index`), place an object in a document store or a search index; no generator
+ writes from them yet. Inside a system a name is used once per type: a `role.service` and a
+ `role.user` both called `api` are now `ERR_DUPLICATE_NAME` in every port, where the loader
+ used to merge the second into the first. A redeclaration of the same subtype still merges, and
+ a duplicate outside a system (two fields of one name) is still the field lint's
+ `WARN_DUPLICATE_FIELD_NAME`. New conformance fixtures pin the grants and sources
+ (`systems-grants-and-sources`), each refusal (`error-ref-unresolved-grant-resource`,
+ `error-ref-wrong-kind-grant-rdb-on-queue`, `error-ref-wrong-kind-source-rdb-on-document`,
+ `error-ref-wrong-kind-grant-stream-on-other-system-queue`, `error-grant-crosses-system`,
+ `error-runsas-other-system`, `error-duplicate-name-in-system`), and a bare `@heldBy` name that
+ an organization and a system share (`error-ref-ambiguous-heldby-bare-name`).
+ `metamodelVersion` stays at `1.4`.
+
+ Upgrading: a model whose `@runsAs` names a role outside the app's system no longer loads,
+ nor does one that declares two children of one system with the same type and name but
+ different subtypes; rename one of them.
diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md
index cb8647c4a1..25141ba65c 100644
--- a/docs/CONFORMANCE.md
+++ b/docs/CONFORMANCE.md
@@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor
| Corpus | Fixtures | TS | Java | Kotlin | C# | Python | Rust |
|---|---|---|---|---|---|---|---|
-| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 599 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (599 / 599, empty ledger) |
+| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 608 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (608 / 608, empty ledger) |
| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | 19 / 19 |
| [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | ✓ |
| [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | — |
@@ -82,7 +82,7 @@ and render ledgers; the api-contract runner's list of sub-corpora not built yet)
shrink, and the corpora without one assert each case outright. A new fixture that fails in
Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard
failure when ADR-0065 turns the warning off. A regression still fails: the ledger's
-`minPassing` (599) is the number of fixtures known to pass, and the run fails when fewer do.
+`minPassing` (608) is the number of fixtures known to pass, and the run fails when fewer do.
Beside the corpora it runs the codegen-compile gate (below) with every shipped generator, a
scale gate over twenty copies of the fitness model, and `examples/rust-service/`'s HTTP test.
[The Rust port page](ports/rust.md#conformance) has the detail.
@@ -445,7 +445,7 @@ carry it, and a model that uses it fails there by name. There is no row per pack
## Fixture-to-doc mapping
-### `fixtures/conformance/` — metamodel loader + canonical serializer (599)
+### `fixtures/conformance/` — metamodel loader + canonical serializer (608)
| Fixture prefix | Feature doc |
|---|---|
@@ -468,7 +468,7 @@ carry it, and a model that uses it fails there by name. There is no row per pack
| `origin-*`, `error-origin-*` | [features/templates-and-payloads.md](features/templates-and-payloads.md) (payload origins) |
| `projection-*`, `error-projection-*`, `field-readonly-on-view-projection` | [features/source-kinds.md](features/source-kinds.md) (projections + the object taxonomy, ADR-0028) |
| `requirement-*`, `error-unknown-attr-requirement` | [features/requirements.md](features/requirements.md) (vocabulary only — the gate has its own corpus, `requirement-check-conformance/`; see "Split coverage" above) |
-| `systems-vocabulary`, `error-ref-wrong-kind-runsas`, `error-ref-unresolved-runsas`, `ref-target-type-list-heldby`, `error-ref-wrong-kind-heldby`, `error-ref-ambiguous-heldby`, `error-resource-residency-bad-value`, `error-app-two-builds`, `error-app-three-builds`, `error-app-build-beside-inherited` | [spec/metamodel-definitions.md](../spec/metamodel-definitions.md) (the systems vocabulary, ADR-0070: the reference facet's worked cases, including the target type list behind `@heldBy`, the closed `@residency` set, and an app's one build, counting a build it inherits) |
+| `systems-vocabulary`, `error-ref-wrong-kind-runsas`, `error-ref-unresolved-runsas`, `ref-target-type-list-heldby`, `error-ref-wrong-kind-heldby`, `error-ref-ambiguous-heldby`, `error-resource-residency-bad-value`, `error-app-two-builds`, `error-app-three-builds`, `error-app-build-beside-inherited`, `systems-grants-and-sources`, `error-ref-unresolved-grant-resource`, `error-ref-wrong-kind-grant-rdb-on-queue`, `error-ref-wrong-kind-source-rdb-on-document`, `error-ref-wrong-kind-grant-stream-on-other-system-queue`, `error-grant-crosses-system`, `error-runsas-other-system`, `error-duplicate-name-in-system`, `error-ref-ambiguous-heldby-bare-name` | [spec/metamodel-definitions.md](../spec/metamodel-definitions.md) (the systems vocabulary, ADR-0070: the reference facet's worked cases, including the target type list behind `@heldBy`, the closed `@residency` set, an app's one build, counting a build it inherits, the grants and their same-system rule, `@resource` on a source, and one name per type within a system) |
| `reporting-*`, `error-dimension-*`, `error-measure-*`, `error-ratio-*`, `error-segment-*`, `error-report-*`, `error-relative-date-*` | [features/reporting.md](features/reporting.md) (the `dimension` / `measure` / `segment` / `object.report` vocabulary and its load-time rules; design in the [FR-044 spec](superpowers/specs/2026-10-02-fr-044-core-reporting-design.md)) |
| `rules-*`, `error-rules-*` | [features/business-rules.md](features/business-rules.md) (operations, permission names and lifecycles: the vocabulary and its load-time rules, ADR-0066; the `verify` gate has its own corpus, `rules-check-conformance/`) |
| `provider-extension-*`, `provider-custom-vocabulary-*` | [features/extending-with-providers.md](features/extending-with-providers.md) (a project's own provider: a new subtype plus attributes on an existing type load with it and are refused without it, every port writing the provider in its own language) |
@@ -961,7 +961,7 @@ shared input.
## Orphaned fixtures (tested but not yet documented)
-The fixtures in the nine corpora mapped above (metamodel 599 + yaml 19 + verify 45
+The fixtures in the nine corpora mapped above (metamodel 608 + yaml 19 + verify 45
+ render 26 + persistence 68 + api-contract 191 + source-resolution 30 + scope 10 +
dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the
`cube-model` corpus, `explorer-conformance` and `list-query-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining
diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json
index aa7d4f9ff3..50c7f5b042 100644
--- a/examples/showcase/site-payload.json
+++ b/examples/showcase/site-payload.json
@@ -7,9 +7,9 @@
"metamodel": "1.4"
},
"counts": {
- "fixtures": 599,
+ "fixtures": 608,
"corpora": 49,
- "baseTypes": 27
+ "baseTypes": 28
},
"snippets": {
"showcase-model": {
diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json
index cdf78765f9..2d644faa6e 100644
--- a/fixtures/conformance/ERROR-CODES.json
+++ b/fixtures/conformance/ERROR-CODES.json
@@ -8,7 +8,7 @@
"ERR_UNKNOWN_SUBTYPE": "A node uses a subType not valid for its type.",
"ERR_ABSTRACT_SUBTYPE_AUTHORED": "A document authors a `.base` node. Every registered `base` subtype is an abstract registry anchor that concrete subtypes inherit from — it has no runtime semantics and is never authored directly. Declare a concrete subtype instead.",
"ERR_MISSING_SUBTYPE": "A node omits subType and the type has no default subType.",
- "ERR_DUPLICATE_NAME": "Two sibling nodes share the same name.",
+ "ERR_DUPLICATE_NAME": "Two children of one system share a type and a name but not a subtype (a role.service and a role.user both named api). Inside a system a name is used once per type (ADR-0070); a same-subtype redeclaration still merges.",
"ERR_UNRESOLVED_SUPER": "An extends/super reference names a node that does not exist.",
"ERR_EXTENDS_TARGET_MISMATCH": "FR-024: a dotted extends ref resolved to a node whose type or subtype does not match the extending node (a field may only extend a field of the same subtype; an identity only an identity).",
"ERR_IDENTITY_NAME_REQUIRED": "FR-024: an identity.* node has no name. Identities are named, author-chosen (e.g. \"id\"), so the dotted by-name extends form can address them.",
@@ -66,6 +66,8 @@
"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, or names nodes of two of the facet's listed target types that share the name (ambiguous). 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 than every type in it, when it is a list), or a subtype outside its `targetSubTypes`. The default code when the facet names no `errorCode`.",
+ "ERR_GRANT_CROSSES_SYSTEM": "ADR-0070, call 9: a grant on a resource (grant.rdb, .keyValue, .objectStore, .document, .search, .queue, .stream) names a resource of another system than the role that holds it. Another system's data is reached through an API that system provides (grant.api). Raised by the reference facet's sameSystem check (spec/metamodel-definitions.md).",
+ "ERR_RUNSAS_OTHER_SYSTEM": "ADR-0070: an app's @runsAs names a service role of another system. An app acts only as a role of its own system. Raised by the reference facet's sameSystem check (spec/metamodel-definitions.md).",
"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/fixtures/conformance/error-duplicate-name-in-system/expected-errors.json b/fixtures/conformance/error-duplicate-name-in-system/expected-errors.json
new file mode 100644
index 0000000000..833424be07
--- /dev/null
+++ b/fixtures/conformance/error-duplicate-name-in-system/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_DUPLICATE_NAME",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.parcels.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[0]['system.software'].children[1]['role.user']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-duplicate-name-in-system/input/meta.parcels.json b/fixtures/conformance/error-duplicate-name-in-system/input/meta.parcels.json
new file mode 100644
index 0000000000..8ec4872a14
--- /dev/null
+++ b/fixtures/conformance/error-duplicate-name-in-system/input/meta.parcels.json
@@ -0,0 +1,30 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ {
+ "system.software": {
+ "name": "Parcels",
+ "children": [
+ {
+ "role.service": {
+ "name": "api"
+ }
+ },
+ {
+ "role.user": {
+ "name": "api"
+ }
+ },
+ {
+ "app.service": {
+ "name": "api",
+ "@runsAs": "api"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-grant-crosses-system/expected-errors.json b/fixtures/conformance/error-grant-crosses-system/expected-errors.json
new file mode 100644
index 0000000000..d64f1271d6
--- /dev/null
+++ b/fixtures/conformance/error-grant-crosses-system/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_GRANT_CROSSES_SYSTEM",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.parcels.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[0]['system.software'].children[1]['role.service'].children[0]['grant.rdb']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-grant-crosses-system/input/meta.ledger.json b/fixtures/conformance/error-grant-crosses-system/input/meta.ledger.json
new file mode 100644
index 0000000000..6c893c5d3b
--- /dev/null
+++ b/fixtures/conformance/error-grant-crosses-system/input/meta.ledger.json
@@ -0,0 +1,35 @@
+{
+ "metadata.root": {
+ "package": "acme::ledger",
+ "children": [
+ {
+ "system.software": {
+ "name": "Ledger",
+ "children": [
+ {
+ "resource.rdb": {
+ "name": "db"
+ }
+ },
+ {
+ "resource.queue": {
+ "name": "jobs"
+ }
+ },
+ {
+ "role.service": {
+ "name": "api"
+ }
+ },
+ {
+ "app.service": {
+ "name": "api",
+ "@runsAs": "api"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-grant-crosses-system/input/meta.parcels.json b/fixtures/conformance/error-grant-crosses-system/input/meta.parcels.json
new file mode 100644
index 0000000000..f05adff753
--- /dev/null
+++ b/fixtures/conformance/error-grant-crosses-system/input/meta.parcels.json
@@ -0,0 +1,32 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ {
+ "system.software": {
+ "name": "Parcels",
+ "children": [
+ {
+ "resource.rdb": {
+ "name": "db"
+ }
+ },
+ {
+ "role.service": {
+ "name": "reporting",
+ "children": [
+ {
+ "grant.rdb": {
+ "@resource": "acme::ledger::Ledger.db",
+ "@access": "read"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-ref-ambiguous-heldby-bare-name/expected-errors.json b/fixtures/conformance/error-ref-ambiguous-heldby-bare-name/expected-errors.json
new file mode 100644
index 0000000000..f180dc563e
--- /dev/null
+++ b/fixtures/conformance/error-ref-ambiguous-heldby-bare-name/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_REF_UNRESOLVED",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.parcels.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['system.software'].children[0]['role.token']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-ref-ambiguous-heldby-bare-name/input/meta.parcels.json b/fixtures/conformance/error-ref-ambiguous-heldby-bare-name/input/meta.parcels.json
new file mode 100644
index 0000000000..5b91c5e155
--- /dev/null
+++ b/fixtures/conformance/error-ref-ambiguous-heldby-bare-name/input/meta.parcels.json
@@ -0,0 +1,31 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ {
+ "organization.company": {
+ "name": "Tidewell"
+ }
+ },
+ {
+ "system.software": {
+ "name": "Tidewell",
+ "children": []
+ }
+ },
+ {
+ "system.software": {
+ "name": "Parcels",
+ "children": [
+ {
+ "role.token": {
+ "name": "tidewellFeeds",
+ "@heldBy": "Tidewell"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-ref-unresolved-grant-resource/expected-errors.json b/fixtures/conformance/error-ref-unresolved-grant-resource/expected-errors.json
new file mode 100644
index 0000000000..45e0e7e200
--- /dev/null
+++ b/fixtures/conformance/error-ref-unresolved-grant-resource/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_REF_UNRESOLVED",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.parcels.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[0]['system.software'].children[1]['role.service'].children[0]['grant.rdb']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-ref-unresolved-grant-resource/input/meta.parcels.json b/fixtures/conformance/error-ref-unresolved-grant-resource/input/meta.parcels.json
new file mode 100644
index 0000000000..5de4ccd427
--- /dev/null
+++ b/fixtures/conformance/error-ref-unresolved-grant-resource/input/meta.parcels.json
@@ -0,0 +1,32 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ {
+ "system.software": {
+ "name": "Parcels",
+ "children": [
+ {
+ "resource.rdb": {
+ "name": "db"
+ }
+ },
+ {
+ "role.service": {
+ "name": "api",
+ "children": [
+ {
+ "grant.rdb": {
+ "@resource": "archive",
+ "@access": "read"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-ref-wrong-kind-grant-rdb-on-queue/expected-errors.json b/fixtures/conformance/error-ref-wrong-kind-grant-rdb-on-queue/expected-errors.json
new file mode 100644
index 0000000000..5ec63f6883
--- /dev/null
+++ b/fixtures/conformance/error-ref-wrong-kind-grant-rdb-on-queue/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_REF_WRONG_KIND",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.parcels.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[0]['system.software'].children[1]['role.service'].children[0]['grant.rdb']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-ref-wrong-kind-grant-rdb-on-queue/input/meta.parcels.json b/fixtures/conformance/error-ref-wrong-kind-grant-rdb-on-queue/input/meta.parcels.json
new file mode 100644
index 0000000000..7db8d4f5e6
--- /dev/null
+++ b/fixtures/conformance/error-ref-wrong-kind-grant-rdb-on-queue/input/meta.parcels.json
@@ -0,0 +1,32 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ {
+ "system.software": {
+ "name": "Parcels",
+ "children": [
+ {
+ "resource.queue": {
+ "name": "labelJobs"
+ }
+ },
+ {
+ "role.service": {
+ "name": "api",
+ "children": [
+ {
+ "grant.rdb": {
+ "@resource": "labelJobs",
+ "@access": "readWrite"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-ref-wrong-kind-grant-stream-on-other-system-queue/expected-errors.json b/fixtures/conformance/error-ref-wrong-kind-grant-stream-on-other-system-queue/expected-errors.json
new file mode 100644
index 0000000000..4b4acaeb71
--- /dev/null
+++ b/fixtures/conformance/error-ref-wrong-kind-grant-stream-on-other-system-queue/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_REF_WRONG_KIND",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.parcels.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[0]['system.software'].children[1]['role.service'].children[0]['grant.stream']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-ref-wrong-kind-grant-stream-on-other-system-queue/input/meta.ledger.json b/fixtures/conformance/error-ref-wrong-kind-grant-stream-on-other-system-queue/input/meta.ledger.json
new file mode 100644
index 0000000000..6c893c5d3b
--- /dev/null
+++ b/fixtures/conformance/error-ref-wrong-kind-grant-stream-on-other-system-queue/input/meta.ledger.json
@@ -0,0 +1,35 @@
+{
+ "metadata.root": {
+ "package": "acme::ledger",
+ "children": [
+ {
+ "system.software": {
+ "name": "Ledger",
+ "children": [
+ {
+ "resource.rdb": {
+ "name": "db"
+ }
+ },
+ {
+ "resource.queue": {
+ "name": "jobs"
+ }
+ },
+ {
+ "role.service": {
+ "name": "api"
+ }
+ },
+ {
+ "app.service": {
+ "name": "api",
+ "@runsAs": "api"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-ref-wrong-kind-grant-stream-on-other-system-queue/input/meta.parcels.json b/fixtures/conformance/error-ref-wrong-kind-grant-stream-on-other-system-queue/input/meta.parcels.json
new file mode 100644
index 0000000000..e26aa8d249
--- /dev/null
+++ b/fixtures/conformance/error-ref-wrong-kind-grant-stream-on-other-system-queue/input/meta.parcels.json
@@ -0,0 +1,32 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ {
+ "system.software": {
+ "name": "Parcels",
+ "children": [
+ {
+ "resource.stream": {
+ "name": "events"
+ }
+ },
+ {
+ "role.service": {
+ "name": "indexer",
+ "children": [
+ {
+ "grant.stream": {
+ "@resource": "acme::ledger::Ledger.jobs",
+ "@access": "consume"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-ref-wrong-kind-source-rdb-on-document/expected-errors.json b/fixtures/conformance/error-ref-wrong-kind-source-rdb-on-document/expected-errors.json
new file mode 100644
index 0000000000..e828842c30
--- /dev/null
+++ b/fixtures/conformance/error-ref-wrong-kind-source-rdb-on-document/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_REF_WRONG_KIND",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.parcels.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[1]['object.entity'].children[0]['source.rdb']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-ref-wrong-kind-source-rdb-on-document/input/meta.parcels.json b/fixtures/conformance/error-ref-wrong-kind-source-rdb-on-document/input/meta.parcels.json
new file mode 100644
index 0000000000..f8e74dd21d
--- /dev/null
+++ b/fixtures/conformance/error-ref-wrong-kind-source-rdb-on-document/input/meta.parcels.json
@@ -0,0 +1,45 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ {
+ "system.software": {
+ "name": "Parcels",
+ "children": [
+ {
+ "resource.document": {
+ "name": "tracking"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Shipment",
+ "children": [
+ {
+ "source.rdb": {
+ "@resource": "Parcels.tracking",
+ "@table": "shipments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "pk",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-runsas-other-system/expected-errors.json b/fixtures/conformance/error-runsas-other-system/expected-errors.json
new file mode 100644
index 0000000000..eea2677fb7
--- /dev/null
+++ b/fixtures/conformance/error-runsas-other-system/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_RUNSAS_OTHER_SYSTEM",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.parcels.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[0]['system.software'].children[1]['app.service']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-runsas-other-system/input/meta.ledger.json b/fixtures/conformance/error-runsas-other-system/input/meta.ledger.json
new file mode 100644
index 0000000000..6c893c5d3b
--- /dev/null
+++ b/fixtures/conformance/error-runsas-other-system/input/meta.ledger.json
@@ -0,0 +1,35 @@
+{
+ "metadata.root": {
+ "package": "acme::ledger",
+ "children": [
+ {
+ "system.software": {
+ "name": "Ledger",
+ "children": [
+ {
+ "resource.rdb": {
+ "name": "db"
+ }
+ },
+ {
+ "resource.queue": {
+ "name": "jobs"
+ }
+ },
+ {
+ "role.service": {
+ "name": "api"
+ }
+ },
+ {
+ "app.service": {
+ "name": "api",
+ "@runsAs": "api"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-runsas-other-system/input/meta.parcels.json b/fixtures/conformance/error-runsas-other-system/input/meta.parcels.json
new file mode 100644
index 0000000000..50a680537d
--- /dev/null
+++ b/fixtures/conformance/error-runsas-other-system/input/meta.parcels.json
@@ -0,0 +1,25 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ {
+ "system.software": {
+ "name": "Parcels",
+ "children": [
+ {
+ "role.service": {
+ "name": "api"
+ }
+ },
+ {
+ "app.service": {
+ "name": "api",
+ "@runsAs": "acme::ledger::Ledger.api"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/systems-grants-and-sources/expected.json b/fixtures/conformance/systems-grants-and-sources/expected.json
new file mode 100644
index 0000000000..c2377b011a
--- /dev/null
+++ b/fixtures/conformance/systems-grants-and-sources/expected.json
@@ -0,0 +1,292 @@
+{
+ "metadata.root": {
+ "children": [
+ {
+ "object.value": {
+ "name": "ChargeInput",
+ "package": "acme::ledger",
+ "children": [
+ {
+ "field.string": {
+ "name": "trackingNumber"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "api.operational": {
+ "name": "LedgerApi",
+ "package": "acme::ledger",
+ "children": [
+ {
+ "operation.command": {
+ "name": "charge",
+ "@inputRef": "acme::ledger::ChargeInput"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "system.software": {
+ "name": "Parcels",
+ "package": "acme::parcels",
+ "children": [
+ {
+ "resource.rdb": {
+ "name": "db"
+ }
+ },
+ {
+ "resource.keyValue": {
+ "name": "cache",
+ "@volatile": true
+ }
+ },
+ {
+ "resource.objectStore": {
+ "name": "drops"
+ }
+ },
+ {
+ "resource.document": {
+ "name": "tracking"
+ }
+ },
+ {
+ "resource.search": {
+ "name": "search"
+ }
+ },
+ {
+ "resource.queue": {
+ "name": "labelJobs"
+ }
+ },
+ {
+ "resource.stream": {
+ "name": "events"
+ }
+ },
+ {
+ "role.group": {
+ "name": "support",
+ "children": [
+ {
+ "grant.rdb": {
+ "@access": "read",
+ "@resource": "acme::parcels::Parcels.db",
+ "@schema": "app"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "role.service": {
+ "name": "api",
+ "children": [
+ {
+ "grant.rdb": {
+ "@access": "readWrite",
+ "@resource": "acme::parcels::Parcels.db",
+ "@schema": "app"
+ }
+ },
+ {
+ "grant.keyValue": {
+ "@access": "readWrite",
+ "@keyPrefix": "session:",
+ "@resource": "acme::parcels::Parcels.cache"
+ }
+ },
+ {
+ "grant.objectStore": {
+ "@access": "write",
+ "@prefix": "manifests/",
+ "@resource": "acme::parcels::Parcels.drops"
+ }
+ },
+ {
+ "grant.document": {
+ "@access": "readWrite",
+ "@collection": "scans",
+ "@resource": "acme::parcels::Parcels.tracking"
+ }
+ },
+ {
+ "grant.search": {
+ "@access": "write",
+ "@index": "shipments",
+ "@resource": "acme::parcels::Parcels.search"
+ }
+ },
+ {
+ "grant.queue": {
+ "@access": "publish",
+ "@resource": "acme::parcels::Parcels.labelJobs"
+ }
+ },
+ {
+ "grant.stream": {
+ "@access": "publish",
+ "@resource": "acme::parcels::Parcels.events"
+ }
+ },
+ {
+ "grant.api": {
+ "@api": "acme::ledger::LedgerApi",
+ "@credential": "keys/LEDGER_API_KEY",
+ "@operations": [
+ "charge"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "role.service": {
+ "name": "migrator",
+ "children": [
+ {
+ "grant.rdb": {
+ "@access": "owner",
+ "@resource": "acme::parcels::Parcels.db"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "role.service": {
+ "name": "exporter",
+ "children": [
+ {
+ "grant.rdb": {
+ "@access": "read",
+ "@maintain": true,
+ "@resource": "acme::parcels::Parcels.db",
+ "@schema": "reporting"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "app.service": {
+ "name": "api",
+ "@runsAs": "acme::parcels::Parcels.api"
+ }
+ },
+ {
+ "app.job": {
+ "name": "manifestExport",
+ "@runsAs": "acme::parcels::Parcels.exporter",
+ "@schedule": "0 2 * * *"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Shipment",
+ "package": "acme::parcels",
+ "children": [
+ {
+ "source.rdb": {
+ "@resource": "acme::parcels::Parcels.db",
+ "@schema": "app",
+ "@table": "shipments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "trackingNumber"
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "pk",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TrackingScan",
+ "package": "acme::parcels",
+ "children": [
+ {
+ "source.document": {
+ "@collection": "scans",
+ "@resource": "acme::parcels::Parcels.tracking"
+ }
+ },
+ {
+ "field.string": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "trackingNumber"
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "pk",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "ShipmentHit",
+ "package": "acme::parcels",
+ "children": [
+ {
+ "source.search": {
+ "@index": "shipments",
+ "@resource": "acme::parcels::Parcels.search"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "trackingNumber"
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "pk",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/systems-grants-and-sources/input/meta.ledger.json b/fixtures/conformance/systems-grants-and-sources/input/meta.ledger.json
new file mode 100644
index 0000000000..ae0324070a
--- /dev/null
+++ b/fixtures/conformance/systems-grants-and-sources/input/meta.ledger.json
@@ -0,0 +1,32 @@
+{
+ "metadata.root": {
+ "package": "acme::ledger",
+ "children": [
+ {
+ "object.value": {
+ "name": "ChargeInput",
+ "children": [
+ {
+ "field.string": {
+ "name": "trackingNumber"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "api.operational": {
+ "name": "LedgerApi",
+ "children": [
+ {
+ "operation.command": {
+ "name": "charge",
+ "@inputRef": "ChargeInput"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/systems-grants-and-sources/input/meta.parcels.json b/fixtures/conformance/systems-grants-and-sources/input/meta.parcels.json
new file mode 100644
index 0000000000..d26aacb627
--- /dev/null
+++ b/fixtures/conformance/systems-grants-and-sources/input/meta.parcels.json
@@ -0,0 +1,262 @@
+{
+ "metadata.root": {
+ "package": "acme::parcels",
+ "children": [
+ {
+ "system.software": {
+ "name": "Parcels",
+ "children": [
+ {
+ "resource.rdb": {
+ "name": "db"
+ }
+ },
+ {
+ "resource.keyValue": {
+ "name": "cache",
+ "@volatile": true
+ }
+ },
+ {
+ "resource.objectStore": {
+ "name": "drops"
+ }
+ },
+ {
+ "resource.document": {
+ "name": "tracking"
+ }
+ },
+ {
+ "resource.search": {
+ "name": "search"
+ }
+ },
+ {
+ "resource.queue": {
+ "name": "labelJobs"
+ }
+ },
+ {
+ "resource.stream": {
+ "name": "events"
+ }
+ },
+ {
+ "role.group": {
+ "name": "support",
+ "children": [
+ {
+ "grant.rdb": {
+ "@resource": "db",
+ "@schema": "app",
+ "@access": "read"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "role.service": {
+ "name": "api",
+ "children": [
+ {
+ "grant.rdb": {
+ "@resource": "db",
+ "@schema": "app",
+ "@access": "readWrite"
+ }
+ },
+ {
+ "grant.keyValue": {
+ "@resource": "cache",
+ "@keyPrefix": "session:",
+ "@access": "readWrite"
+ }
+ },
+ {
+ "grant.objectStore": {
+ "@resource": "Parcels.drops",
+ "@prefix": "manifests/",
+ "@access": "write"
+ }
+ },
+ {
+ "grant.document": {
+ "@resource": "tracking",
+ "@collection": "scans",
+ "@access": "readWrite"
+ }
+ },
+ {
+ "grant.search": {
+ "@resource": "search",
+ "@index": "shipments",
+ "@access": "write"
+ }
+ },
+ {
+ "grant.queue": {
+ "@resource": "labelJobs",
+ "@access": "publish"
+ }
+ },
+ {
+ "grant.stream": {
+ "@resource": "acme::parcels::Parcels.events",
+ "@access": "publish"
+ }
+ },
+ {
+ "grant.api": {
+ "@api": "acme::ledger::LedgerApi",
+ "@operations": [
+ "charge"
+ ],
+ "@credential": "keys/LEDGER_API_KEY"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "role.service": {
+ "name": "migrator",
+ "children": [
+ {
+ "grant.rdb": {
+ "@resource": "db",
+ "@access": "owner"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "role.service": {
+ "name": "exporter",
+ "children": [
+ {
+ "grant.rdb": {
+ "@resource": "db",
+ "@schema": "reporting",
+ "@access": "read",
+ "@maintain": true
+ }
+ }
+ ]
+ }
+ },
+ {
+ "app.service": {
+ "name": "api",
+ "@runsAs": "api"
+ }
+ },
+ {
+ "app.job": {
+ "name": "manifestExport",
+ "@runsAs": "exporter",
+ "@schedule": "0 2 * * *"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Shipment",
+ "children": [
+ {
+ "source.rdb": {
+ "@resource": "Parcels.db",
+ "@schema": "app",
+ "@table": "shipments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "trackingNumber"
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "pk",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TrackingScan",
+ "children": [
+ {
+ "source.document": {
+ "@resource": "Parcels.tracking",
+ "@collection": "scans"
+ }
+ },
+ {
+ "field.string": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "trackingNumber"
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "pk",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "ShipmentHit",
+ "children": [
+ {
+ "source.search": {
+ "@resource": "Parcels.search",
+ "@index": "shipments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "trackingNumber"
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "pk",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/metamodel-docs/data/INDEX.md.json b/fixtures/metamodel-docs/data/INDEX.md.json
index c6b239c5bb..ce382588ab 100644
--- a/fixtures/metamodel-docs/data/INDEX.md.json
+++ b/fixtures/metamodel-docs/data/INDEX.md.json
@@ -210,6 +210,51 @@
"description": "Logical UUID identity scalar. A bare scalar (no required attrs, no loader value-validation) — binds to TS string (no native UUID type); DB column is Postgres-native uuid.",
"page": "types/field.md#fielduuid"
},
+ {
+ "typeSubType": "grant.api",
+ "description": "The role may call an API, in any system: this is how one system reaches another's data. The access it implies on whatever carries the API is derived, never written.",
+ "page": "types/grant.md#grantapi"
+ },
+ {
+ "typeSubType": "grant.base",
+ "description": "Abstract grant base: what a role may do to one resource of its own system, or to one API. A grant is a child of a role. Its kind is the kind of thing it is on, so a grant.rdb names a resource.rdb. Not authored directly: a `grant.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).",
+ "page": "types/grant.md#grantbase"
+ },
+ {
+ "typeSubType": "grant.document",
+ "description": "Access to a document store of the role's own system (`resource.document`), optionally limited to one collection.",
+ "page": "types/grant.md#grantdocument"
+ },
+ {
+ "typeSubType": "grant.keyValue",
+ "description": "Access to a key-value store of the role's own system (`resource.keyValue`), optionally limited to keys with one prefix.",
+ "page": "types/grant.md#grantkeyvalue"
+ },
+ {
+ "typeSubType": "grant.objectStore",
+ "description": "Access to an object store of the role's own system (`resource.objectStore`), optionally limited to objects under one prefix.",
+ "page": "types/grant.md#grantobjectstore"
+ },
+ {
+ "typeSubType": "grant.queue",
+ "description": "Access to a message queue of the role's own system (`resource.queue`).",
+ "page": "types/grant.md#grantqueue"
+ },
+ {
+ "typeSubType": "grant.rdb",
+ "description": "Access to a relational database of the role's own system (`resource.rdb`), optionally limited to one schema.",
+ "page": "types/grant.md#grantrdb"
+ },
+ {
+ "typeSubType": "grant.search",
+ "description": "Access to a search index of the role's own system (`resource.search`), optionally limited to one index.",
+ "page": "types/grant.md#grantsearch"
+ },
+ {
+ "typeSubType": "grant.stream",
+ "description": "Access to a stream of the role's own system (`resource.stream`).",
+ "page": "types/grant.md#grantstream"
+ },
{
"typeSubType": "identity.primary",
"description": "The primary key — one per entity; @fields names its column(s), @generation the value strategy.",
@@ -455,11 +500,21 @@
"description": "Abstract base source — the shared root subtype for declaring where an object's data lives (Project E). The base carries no attrs of its own; the concrete paradigm subtype (rdb) carries the physical-storage attrs, which are contributed by the db domain provider. Not authored directly: a `source.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document.",
"page": "types/source.md#sourcebase"
},
+ {
+ "typeSubType": "source.document",
+ "description": "The document-store paradigm source (ADR-0007's `document`): the object's records are kept as documents in a collection, in the document store @resource names. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "page": "types/source.md#sourcedocument"
+ },
{
"typeSubType": "source.rdb",
- "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, not by core-types.",
+ "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, and @resource by the systems provider (metaobjects-systems-core), not by core-types.",
"page": "types/source.md#sourcerdb"
},
+ {
+ "typeSubType": "source.search",
+ "description": "The search-index paradigm source (ADR-0007's `search`): the object's records are kept in a search index, usually as a copy of data kept elsewhere. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "page": "types/source.md#sourcesearch"
+ },
{
"typeSubType": "system.base",
"description": "Abstract system base: the attributes every system.* shares (ADR-0070, call 1). Not authored directly: a `system.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).",
diff --git a/fixtures/metamodel-docs/data/providers.md.json b/fixtures/metamodel-docs/data/providers.md.json
index 79fd51111f..5331ee28e9 100644
--- a/fixtures/metamodel-docs/data/providers.md.json
+++ b/fixtures/metamodel-docs/data/providers.md.json
@@ -501,9 +501,9 @@
{
"id": "metaobjects-systems-core",
"hasDescription": true,
- "description": "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource and role.",
+ "description": "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource, role and grant, and the resource reference on source.rdb, source.document and source.search.",
"hasOwns": true,
- "owns": "`app.base`, `app.client`, `app.job`, `app.service`, `build.base`, `build.image`, `organization.base`, `organization.company`, `organization.unit`, `resource.base`, `resource.document`, `resource.keyValue`, `resource.objectStore`, `resource.queue`, `resource.rdb`, `resource.search`, `resource.stream`, `resource.volume`, `role.base`, `role.group`, `role.service`, `role.token`, `role.user`, `system.base`, `system.software`",
+ "owns": "`app.base`, `app.client`, `app.job`, `app.service`, `build.base`, `build.image`, `grant.api`, `grant.base`, `grant.document`, `grant.keyValue`, `grant.objectStore`, `grant.queue`, `grant.rdb`, `grant.search`, `grant.stream`, `organization.base`, `organization.company`, `organization.unit`, `resource.base`, `resource.document`, `resource.keyValue`, `resource.objectStore`, `resource.queue`, `resource.rdb`, `resource.search`, `resource.stream`, `resource.volume`, `role.base`, `role.group`, `role.service`, `role.token`, `role.user`, `source.document`, `source.search`, `system.base`, `system.software`",
"hasUniversal": false,
"hasContributes": true,
"contributes": [
@@ -527,6 +527,38 @@
"typeSubType": "build.image",
"attrs": "`@repository`"
},
+ {
+ "typeSubType": "grant.api",
+ "attrs": "`@api`, `@credential`, `@operations`"
+ },
+ {
+ "typeSubType": "grant.document",
+ "attrs": "`@access`, `@collection`, `@resource`"
+ },
+ {
+ "typeSubType": "grant.keyValue",
+ "attrs": "`@access`, `@keyPrefix`, `@resource`"
+ },
+ {
+ "typeSubType": "grant.objectStore",
+ "attrs": "`@access`, `@prefix`, `@resource`"
+ },
+ {
+ "typeSubType": "grant.queue",
+ "attrs": "`@access`, `@resource`"
+ },
+ {
+ "typeSubType": "grant.rdb",
+ "attrs": "`@access`, `@maintain`, `@resource`, `@schema`"
+ },
+ {
+ "typeSubType": "grant.search",
+ "attrs": "`@access`, `@index`, `@resource`"
+ },
+ {
+ "typeSubType": "grant.stream",
+ "attrs": "`@access`, `@resource`"
+ },
{
"typeSubType": "resource.base",
"attrs": "`@residency`"
@@ -555,6 +587,18 @@
"typeSubType": "role.token",
"attrs": "`@heldBy`"
},
+ {
+ "typeSubType": "source.document",
+ "attrs": "`@collection`, `@resource`"
+ },
+ {
+ "typeSubType": "source.rdb",
+ "attrs": "`@resource`"
+ },
+ {
+ "typeSubType": "source.search",
+ "attrs": "`@index`, `@resource`"
+ },
{
"typeSubType": "system.base",
"attrs": "`@owner`"
diff --git a/fixtures/metamodel-docs/data/types/app.md.json b/fixtures/metamodel-docs/data/types/app.md.json
index df7708d127..66b0ed7eff 100644
--- a/fixtures/metamodel-docs/data/types/app.md.json
+++ b/fixtures/metamodel-docs/data/types/app.md.json
@@ -20,7 +20,7 @@
"default": "",
"allowed": "",
"provider": "metaobjects-systems-core",
- "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND."
+ "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system)."
}
],
"hasChildren": true,
@@ -49,7 +49,7 @@
"default": "",
"allowed": "",
"provider": "metaobjects-systems-core",
- "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND."
+ "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system)."
},
{
"name": "shell",
@@ -87,7 +87,7 @@
"default": "",
"allowed": "",
"provider": "metaobjects-systems-core",
- "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND."
+ "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system)."
},
{
"name": "schedule",
@@ -134,7 +134,7 @@
"default": "",
"allowed": "",
"provider": "metaobjects-systems-core",
- "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND."
+ "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system)."
}
],
"hasChildren": true,
diff --git a/fixtures/metamodel-docs/data/types/grant.md.json b/fixtures/metamodel-docs/data/types/grant.md.json
new file mode 100644
index 0000000000..c23a4d3bfe
--- /dev/null
+++ b/fixtures/metamodel-docs/data/types/grant.md.json
@@ -0,0 +1,379 @@
+{
+ "family": "grant",
+ "sections": [
+ {
+ "typeSubType": "grant.api",
+ "description": "The role may call an API, in any system: this is how one system reaches another's data. The access it implies on whatever carries the API is derived, never written.",
+ "hasOwner": true,
+ "owner": "metaobjects-systems-core",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": false,
+ "hasWhenToUse": true,
+ "whenToUse": "A role whose app calls another system's API, or an outside party's token that consumes one of ours.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
+ {
+ "name": "api",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The API, by name (`pkg::ShipmentApi`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND."
+ },
+ {
+ "name": "credential",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The name of an existing key this grant uses (`keys/LARKSPUR_API_KEY`). Never a value. Written only for a key the model cannot create, such as one an outside party issued; otherwise the credential is implied, with a derived name."
+ },
+ {
+ "name": "operations",
+ "type": "string[]",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The operations of the API the role may call, by name. Absent: all of them."
+ }
+ ],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "grant.base",
+ "description": "Abstract grant base: what a role may do to one resource of its own system, or to one API. A grant is a child of a role. Its kind is the kind of thing it is on, so a grant.rdb names a resource.rdb. Not authored directly: a `grant.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).",
+ "hasOwner": true,
+ "owner": "metaobjects-systems-core",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": false,
+ "hasWhenToUse": false,
+ "hasExample": false,
+ "hasAttrs": false,
+ "attrs": [],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "grant.document",
+ "description": "Access to a document store of the role's own system (`resource.document`), optionally limited to one collection.",
+ "hasOwner": true,
+ "owner": "metaobjects-systems-core",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": true,
+ "rules": "@resource names a resource.document of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "hasWhenToUse": true,
+ "whenToUse": "A role that reads or writes documents.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
+ {
+ "name": "access",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "`readWrite`, `read`",
+ "provider": "metaobjects-systems-core",
+ "description": "readWrite: reads and writes documents. read: reads documents."
+ },
+ {
+ "name": "collection",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The one collection the grant covers. Absent: every collection."
+ },
+ {
+ "name": "resource",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The document store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ }
+ ],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "grant.keyValue",
+ "description": "Access to a key-value store of the role's own system (`resource.keyValue`), optionally limited to keys with one prefix.",
+ "hasOwner": true,
+ "owner": "metaobjects-systems-core",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": true,
+ "rules": "@resource names a resource.keyValue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "hasWhenToUse": true,
+ "whenToUse": "A role that reads or writes a cache or a key-value store.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
+ {
+ "name": "access",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "`readWrite`, `read`",
+ "provider": "metaobjects-systems-core",
+ "description": "readWrite: reads and writes values. read: reads values."
+ },
+ {
+ "name": "keyPrefix",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The key prefix the grant covers. Absent: every key."
+ },
+ {
+ "name": "resource",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The key-value store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ }
+ ],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "grant.objectStore",
+ "description": "Access to an object store of the role's own system (`resource.objectStore`), optionally limited to objects under one prefix.",
+ "hasOwner": true,
+ "owner": "metaobjects-systems-core",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": true,
+ "rules": "@resource names a resource.objectStore of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "hasWhenToUse": true,
+ "whenToUse": "A role that uploads, downloads or manages files and blobs.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
+ {
+ "name": "access",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "`read`, `write`, `readWrite`, `manage`",
+ "provider": "metaobjects-systems-core",
+ "description": "read: reads objects. write: writes objects and cannot read them. readWrite: both. manage: also deletes objects and changes the store's settings."
+ },
+ {
+ "name": "prefix",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The object key prefix the grant covers. Absent: every object."
+ },
+ {
+ "name": "resource",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The object store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ }
+ ],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "grant.queue",
+ "description": "Access to a message queue of the role's own system (`resource.queue`).",
+ "hasOwner": true,
+ "owner": "metaobjects-systems-core",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": true,
+ "rules": "@resource names a resource.queue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "hasWhenToUse": true,
+ "whenToUse": "A role that sends work to a queue or takes work from it.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
+ {
+ "name": "access",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "`publish`, `consume`",
+ "provider": "metaobjects-systems-core",
+ "description": "publish: sends messages. consume: receives and acknowledges them."
+ },
+ {
+ "name": "resource",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The queue this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a queue of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ }
+ ],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "grant.rdb",
+ "description": "Access to a relational database of the role's own system (`resource.rdb`), optionally limited to one schema.",
+ "hasOwner": true,
+ "owner": "metaobjects-systems-core",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": true,
+ "rules": "@resource names a resource.rdb of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "hasWhenToUse": true,
+ "whenToUse": "A role that connects to the database: the app's service role, a reporting job, the role migrations run as (`access: owner`).",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
+ {
+ "name": "access",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "`owner`, `readWrite`, `read`",
+ "provider": "metaobjects-systems-core",
+ "description": "owner: creates and changes the schema's tables (the role migrations run as). readWrite: reads and writes rows. read: reads rows."
+ },
+ {
+ "name": "maintain",
+ "type": "boolean",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The role may also refresh materialized views and run maintenance on the tables it covers (PostgreSQL's MAINTAIN privilege). Absent means it may not."
+ },
+ {
+ "name": "resource",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The relational database this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a database of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ },
+ {
+ "name": "schema",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The one schema the grant covers. Absent: every schema of the database."
+ }
+ ],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "grant.search",
+ "description": "Access to a search index of the role's own system (`resource.search`), optionally limited to one index.",
+ "hasOwner": true,
+ "owner": "metaobjects-systems-core",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": true,
+ "rules": "@resource names a resource.search of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "hasWhenToUse": true,
+ "whenToUse": "A role that queries an index or keeps it up to date.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
+ {
+ "name": "access",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "`read`, `write`, `manage`",
+ "provider": "metaobjects-systems-core",
+ "description": "read: queries. write: adds, changes and removes documents. manage: also creates and drops indexes."
+ },
+ {
+ "name": "index",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The one index the grant covers. Absent: every index."
+ },
+ {
+ "name": "resource",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The search index this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; an index of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ }
+ ],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ },
+ {
+ "typeSubType": "grant.stream",
+ "description": "Access to a stream of the role's own system (`resource.stream`).",
+ "hasOwner": true,
+ "owner": "metaobjects-systems-core",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": true,
+ "rules": "@resource names a resource.stream of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "hasWhenToUse": true,
+ "whenToUse": "A role that appends to a stream or reads it.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
+ {
+ "name": "access",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "`publish`, `consume`",
+ "provider": "metaobjects-systems-core",
+ "description": "publish: appends messages. consume: reads them, in a consumer group of its own."
+ },
+ {
+ "name": "resource",
+ "type": "string",
+ "required": "yes",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The stream this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a stream of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ }
+ ],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ }
+ ]
+}
diff --git a/fixtures/metamodel-docs/data/types/role.md.json b/fixtures/metamodel-docs/data/types/role.md.json
index e122e565ca..e53fe64379 100644
--- a/fixtures/metamodel-docs/data/types/role.md.json
+++ b/fixtures/metamodel-docs/data/types/role.md.json
@@ -32,8 +32,10 @@
"description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND."
}
],
- "hasChildren": false,
- "children": [],
+ "hasChildren": true,
+ "children": [
+ "`grant.*` — 0..*"
+ ],
"hasParents": false
},
{
@@ -68,8 +70,10 @@
"description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND."
}
],
- "hasChildren": false,
- "children": [],
+ "hasChildren": true,
+ "children": [
+ "`grant.*` — 0..*"
+ ],
"hasParents": false
},
{
@@ -104,8 +108,10 @@
"description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND."
}
],
- "hasChildren": false,
- "children": [],
+ "hasChildren": true,
+ "children": [
+ "`grant.*` — 0..*"
+ ],
"hasParents": false
},
{
@@ -149,8 +155,10 @@
"description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND."
}
],
- "hasChildren": false,
- "children": [],
+ "hasChildren": true,
+ "children": [
+ "`grant.*` — 0..*"
+ ],
"hasParents": false
},
{
@@ -185,8 +193,10 @@
"description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND."
}
],
- "hasChildren": false,
- "children": [],
+ "hasChildren": true,
+ "children": [
+ "`grant.*` — 0..*"
+ ],
"hasParents": false
}
]
diff --git a/fixtures/metamodel-docs/data/types/source.md.json b/fixtures/metamodel-docs/data/types/source.md.json
index 088948a705..1c5ebeef29 100644
--- a/fixtures/metamodel-docs/data/types/source.md.json
+++ b/fixtures/metamodel-docs/data/types/source.md.json
@@ -17,9 +17,45 @@
"children": [],
"hasParents": false
},
+ {
+ "typeSubType": "source.document",
+ "description": "The document-store paradigm source (ADR-0007's `document`): the object's records are kept as documents in a collection, in the document store @resource names. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "hasOwner": true,
+ "owner": "metaobjects-systems-core",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": false,
+ "hasWhenToUse": true,
+ "whenToUse": "An object kept as documents in a document store.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
+ {
+ "name": "collection",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The collection that holds the documents. Absent: derived from the object's name."
+ },
+ {
+ "name": "resource",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The document store, by name (`Parcels.docs`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a document store, is ERR_REF_WRONG_KIND."
+ }
+ ],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
+ },
{
"typeSubType": "source.rdb",
- "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, not by core-types.",
+ "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, and @resource by the systems provider (metaobjects-systems-core), not by core-types.",
"hasOwner": true,
"owner": "metaobjects-core-types",
"hasImplementedIn": false,
@@ -76,6 +112,15 @@
"provider": "metaobjects-db",
"description": "Physical SQL stored-procedure name for source.rdb @kind: \"storedProc\". Same internal slot as @table."
},
+ {
+ "name": "resource",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The relational database this source's table or view lives in: a `resource.rdb`, by name (`Parcels.db`, or `pkg::Parcels.db` from another package). Optional: a model that declares no systems names none. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a relational database, is ERR_REF_WRONG_KIND."
+ },
{
"name": "role",
"type": "string",
@@ -134,6 +179,42 @@
"hasChildren": false,
"children": [],
"hasParents": false
+ },
+ {
+ "typeSubType": "source.search",
+ "description": "The search-index paradigm source (ADR-0007's `search`): the object's records are kept in a search index, usually as a copy of data kept elsewhere. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "hasOwner": true,
+ "owner": "metaobjects-systems-core",
+ "hasImplementedIn": false,
+ "hasPorts": false,
+ "hasRules": false,
+ "hasWhenToUse": true,
+ "whenToUse": "An object searched by text and filters.",
+ "hasExample": false,
+ "hasAttrs": true,
+ "attrs": [
+ {
+ "name": "index",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The index that holds the documents. Absent: derived from the object's name."
+ },
+ {
+ "name": "resource",
+ "type": "string",
+ "required": "no",
+ "default": "",
+ "allowed": "",
+ "provider": "metaobjects-systems-core",
+ "description": "The search index resource, by name (`Parcels.search`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a search index, is ERR_REF_WRONG_KIND."
+ }
+ ],
+ "hasChildren": false,
+ "children": [],
+ "hasParents": false
}
]
}
diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md
index 08fd2c6d61..800c390301 100644
--- a/fixtures/metamodel-docs/expected/INDEX.md
+++ b/fixtures/metamodel-docs/expected/INDEX.md
@@ -57,6 +57,15 @@ children and the cardinality of that subtype. Documentation attributes
| `field.timestamp` | Date + time-of-day instant (optionally with timezone). Binds to the native date/temporal type; DB column is TIMESTAMP(TZ). Pair with @autoSet for created/updated stamping. | [types/field.md#fieldtimestamp](types/field.md#fieldtimestamp) |
| `field.uri` | A URI/URL string (ADR-0036/0037 — a concept with a native type + behavior, so a subtype not a @stringFormat). Binds to TS string (TS has no native URI type, same as field.uuid); other ports bind to their native URI type (Java java.net.URI, C# System.Uri, Python urllib.parse, Kotlin java.net.URI) and parse scheme/authority/path. DB column is text (Postgres has no uri type). Codegen emits a URL/URI validator (TS Zod z.string().url()). v1 ships WITHOUT @kind — the native type subsumes url/urn; @kind is reserved for a later url\|urn value-constraint. | [types/field.md#fielduri](types/field.md#fielduri) |
| `field.uuid` | Logical UUID identity scalar. A bare scalar (no required attrs, no loader value-validation) — binds to TS string (no native UUID type); DB column is Postgres-native uuid. | [types/field.md#fielduuid](types/field.md#fielduuid) |
+| `grant.api` | The role may call an API, in any system: this is how one system reaches another's data. The access it implies on whatever carries the API is derived, never written. | [types/grant.md#grantapi](types/grant.md#grantapi) |
+| `grant.base` | Abstract grant base: what a role may do to one resource of its own system, or to one API. A grant is a child of a role. Its kind is the kind of thing it is on, so a grant.rdb names a resource.rdb. Not authored directly: a `grant.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED). | [types/grant.md#grantbase](types/grant.md#grantbase) |
+| `grant.document` | Access to a document store of the role's own system (`resource.document`), optionally limited to one collection. | [types/grant.md#grantdocument](types/grant.md#grantdocument) |
+| `grant.keyValue` | Access to a key-value store of the role's own system (`resource.keyValue`), optionally limited to keys with one prefix. | [types/grant.md#grantkeyvalue](types/grant.md#grantkeyvalue) |
+| `grant.objectStore` | Access to an object store of the role's own system (`resource.objectStore`), optionally limited to objects under one prefix. | [types/grant.md#grantobjectstore](types/grant.md#grantobjectstore) |
+| `grant.queue` | Access to a message queue of the role's own system (`resource.queue`). | [types/grant.md#grantqueue](types/grant.md#grantqueue) |
+| `grant.rdb` | Access to a relational database of the role's own system (`resource.rdb`), optionally limited to one schema. | [types/grant.md#grantrdb](types/grant.md#grantrdb) |
+| `grant.search` | Access to a search index of the role's own system (`resource.search`), optionally limited to one index. | [types/grant.md#grantsearch](types/grant.md#grantsearch) |
+| `grant.stream` | Access to a stream of the role's own system (`resource.stream`). | [types/grant.md#grantstream](types/grant.md#grantstream) |
| `identity.primary` | The primary key — one per entity; @fields names its column(s), @generation the value strategy. | [types/identity.md#identityprimary](types/identity.md#identityprimary) |
| `identity.reference` | A foreign-key reference to another entity (@references target; @enforce toggles a physical FK). | [types/identity.md#identityreference](types/identity.md#identityreference) |
| `identity.secondary` | A secondary unique index on one or more fields. Always enforces uniqueness — use index.lookup for non-unique query-performance indexes. | [types/identity.md#identitysecondary](types/identity.md#identitysecondary) |
@@ -106,7 +115,9 @@ children and the cardinality of that subtype. Documentation attributes
| `role.user` | A named person, or an agent acting for one. No shared secret is generated or stored for it. | [types/role.md#roleuser](types/role.md#roleuser) |
| `segment.filter` | A named, reusable row filter on the declaring entity (FR-044). Measures and reports reference it by name; exporters emit it as a named segment. | [types/segment.md#segmentfilter](types/segment.md#segmentfilter) |
| `source.base` | Abstract base source — the shared root subtype for declaring where an object's data lives (Project E). The base carries no attrs of its own; the concrete paradigm subtype (rdb) carries the physical-storage attrs, which are contributed by the db domain provider. Not authored directly: a `source.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. | [types/source.md#sourcebase](types/source.md#sourcebase) |
-| `source.rdb` | The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, not by core-types. | [types/source.md#sourcerdb](types/source.md#sourcerdb) |
+| `source.document` | The document-store paradigm source (ADR-0007's `document`): the object's records are kept as documents in a collection, in the document store @resource names. Registered by the systems provider, not by core-types. No generator writes from it yet. | [types/source.md#sourcedocument](types/source.md#sourcedocument) |
+| `source.rdb` | The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, and @resource by the systems provider (metaobjects-systems-core), not by core-types. | [types/source.md#sourcerdb](types/source.md#sourcerdb) |
+| `source.search` | The search-index paradigm source (ADR-0007's `search`): the object's records are kept in a search index, usually as a copy of data kept elsewhere. Registered by the systems provider, not by core-types. No generator writes from it yet. | [types/source.md#sourcesearch](types/source.md#sourcesearch) |
| `system.base` | Abstract system base: the attributes every system.* shares (ADR-0070, call 1). Not authored directly: a `system.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED). | [types/system.md#systembase](types/system.md#systembase) |
| `system.software` | A system: the apps it is made of, the resources they keep their state in and the roles that act in it. The one kind of system. A file that declares one reads the same in every repository that loads it, so nothing here says whether the reader builds, runs or only calls it. Its children are addressed from outside it as `System.child` (`Parcels.db`), or `pkg::System.child` from another package. | [types/system.md#systemsoftware](types/system.md#systemsoftware) |
| `template.base` | Abstract base template — the shared root subtype for the fourth pillar (FR-004, ADR-0011). A template is a typed payload bound to either a rendered text artifact (prompt/output) or a tool-call envelope. The base carries no attrs of its own; concrete subtypes add their reference + governance attrs. Not authored directly: a `template.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. | [types/template.md#templatebase](types/template.md#templatebase) |
diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md
index e1893b0a06..24e2d772b7 100644
--- a/fixtures/metamodel-docs/expected/providers.md
+++ b/fixtures/metamodel-docs/expected/providers.md
@@ -173,9 +173,9 @@ Business rules (ADR-0066, experimental): the declared API surface (api / operati
## metaobjects-systems-core
-Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource and role.
+Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource, role and grant, and the resource reference on source.rdb, source.document and source.search.
-**Owns (registers):** `app.base`, `app.client`, `app.job`, `app.service`, `build.base`, `build.image`, `organization.base`, `organization.company`, `organization.unit`, `resource.base`, `resource.document`, `resource.keyValue`, `resource.objectStore`, `resource.queue`, `resource.rdb`, `resource.search`, `resource.stream`, `resource.volume`, `role.base`, `role.group`, `role.service`, `role.token`, `role.user`, `system.base`, `system.software`
+**Owns (registers):** `app.base`, `app.client`, `app.job`, `app.service`, `build.base`, `build.image`, `grant.api`, `grant.base`, `grant.document`, `grant.keyValue`, `grant.objectStore`, `grant.queue`, `grant.rdb`, `grant.search`, `grant.stream`, `organization.base`, `organization.company`, `organization.unit`, `resource.base`, `resource.document`, `resource.keyValue`, `resource.objectStore`, `resource.queue`, `resource.rdb`, `resource.search`, `resource.stream`, `resource.volume`, `role.base`, `role.group`, `role.service`, `role.token`, `role.user`, `source.document`, `source.search`, `system.base`, `system.software`
**Contributes attributes:**
@@ -184,6 +184,14 @@ Systems (ADR-0070): organization, system.software, app (service, client, job), b
- `app.job`: `@schedule`
- `app.service`: `@public`
- `build.image`: `@repository`
+- `grant.api`: `@api`, `@credential`, `@operations`
+- `grant.document`: `@access`, `@collection`, `@resource`
+- `grant.keyValue`: `@access`, `@keyPrefix`, `@resource`
+- `grant.objectStore`: `@access`, `@prefix`, `@resource`
+- `grant.queue`: `@access`, `@resource`
+- `grant.rdb`: `@access`, `@maintain`, `@resource`, `@schema`
+- `grant.search`: `@access`, `@index`, `@resource`
+- `grant.stream`: `@access`, `@resource`
- `resource.base`: `@residency`
- `resource.keyValue`: `@volatile`
- `resource.objectStore`: `@publicRead`
@@ -191,6 +199,9 @@ Systems (ADR-0070): organization, system.software, app (service, client, job), b
- `resource.rdb`: `@schemas`
- `role.base`: `@credential`, `@memberOf`
- `role.token`: `@heldBy`
+- `source.document`: `@collection`, `@resource`
+- `source.rdb`: `@resource`
+- `source.search`: `@index`, `@resource`
- `system.base`: `@owner`
## metaobjects-ui
diff --git a/fixtures/metamodel-docs/expected/types/app.md b/fixtures/metamodel-docs/expected/types/app.md
index 8fbcfc1ec1..926cdfd6e2 100644
--- a/fixtures/metamodel-docs/expected/types/app.md
+++ b/fixtures/metamodel-docs/expected/types/app.md
@@ -20,7 +20,7 @@ Abstract app base: the attributes every app.* shares. Not authored directly: an
| Attribute | Type | Required | Default | Allowed values | Provider | Description |
| --- | --- | --- | --- | --- | --- | --- |
-| `@runsAs` | string | no | | | metaobjects-systems-core | The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND. |
+| `@runsAs` | string | no | | | metaobjects-systems-core | The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system). |
**Allowed children**
@@ -38,7 +38,7 @@ Code that runs on the user's device: a single-page web app, a static site, a mob
| Attribute | Type | Required | Default | Allowed values | Provider | Description |
| --- | --- | --- | --- | --- | --- | --- |
-| `@runsAs` | string | no | | | metaobjects-systems-core | The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND. |
+| `@runsAs` | string | no | | | metaobjects-systems-core | The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system). |
| `@shell` | string | no | | | metaobjects-systems-core | The UI frame (a nav.shell of a UI pack) this client presents, by name. Recorded by name only: no UI pack is required, so the name is not resolved here. |
**Allowed children**
@@ -57,7 +57,7 @@ Work that runs to completion and exits: a scheduled task, a migration, a one-off
| Attribute | Type | Required | Default | Allowed values | Provider | Description |
| --- | --- | --- | --- | --- | --- | --- |
-| `@runsAs` | string | no | | | metaobjects-systems-core | The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND. |
+| `@runsAs` | string | no | | | metaobjects-systems-core | The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system). |
| `@schedule` | string | no | | | metaobjects-systems-core | When the job runs, as a five-field cron expression in UTC (`0 3 * * *`). Absent means it runs only when triggered. |
**Allowed children**
@@ -77,7 +77,7 @@ A long-running process that answers requests: a web server, an API, a socket ser
| Attribute | Type | Required | Default | Allowed values | Provider | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `@public` | boolean | no | | | metaobjects-systems-core | The service is meant to be reached from outside every system: from browsers or from parties holding no role in the model. Absent means it is reached only by the apps and roles the model names. |
-| `@runsAs` | string | no | | | metaobjects-systems-core | The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND. |
+| `@runsAs` | string | no | | | metaobjects-systems-core | The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system). |
**Allowed children**
diff --git a/fixtures/metamodel-docs/expected/types/grant.md b/fixtures/metamodel-docs/expected/types/grant.md
new file mode 100644
index 0000000000..460ceeb076
--- /dev/null
+++ b/fixtures/metamodel-docs/expected/types/grant.md
@@ -0,0 +1,199 @@
+
+
+# Metamodel — `grant` types
+
+Each section below is one `grant.`. The **Attributes** table lists
+the subtype's own + concern-contributed attributes (provider-tagged); universal
+documentation attributes are omitted here (see [providers.md](../providers.md)).
+**Allowed children** lists the structural child rules with their cardinality
+(`min..max`, `*` = unbounded).
+
+### grant.api
+
+The role may call an API, in any system: this is how one system reaches another's data. The access it implies on whatever carries the API is derived, never written.
+
+**Owning provider:** metaobjects-systems-core
+
+**When to use:** A role whose app calls another system's API, or an outside party's token that consumes one of ours.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@api` | string | yes | | | metaobjects-systems-core | The API, by name (`pkg::ShipmentApi`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND. |
+| `@credential` | string | no | | | metaobjects-systems-core | The name of an existing key this grant uses (`keys/LARKSPUR_API_KEY`). Never a value. Written only for a key the model cannot create, such as one an outside party issued; otherwise the credential is implied, with a derived name. |
+| `@operations` | string[] | no | | | metaobjects-systems-core | The operations of the API the role may call, by name. Absent: all of them. |
+
+**Allowed children**
+
+_No structural children._
+
+### grant.base
+
+Abstract grant base: what a role may do to one resource of its own system, or to one API. A grant is a child of a role. Its kind is the kind of thing it is on, so a grant.rdb names a resource.rdb. Not authored directly: a `grant.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).
+
+**Owning provider:** metaobjects-systems-core
+
+**Attributes**
+
+_No subtype-specific attributes._
+
+**Allowed children**
+
+_No structural children._
+
+### grant.document
+
+Access to a document store of the role's own system (`resource.document`), optionally limited to one collection.
+
+**Owning provider:** metaobjects-systems-core
+
+**Rules:** @resource names a resource.document of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
+**When to use:** A role that reads or writes documents.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@access` | string | yes | | `readWrite`, `read` | metaobjects-systems-core | readWrite: reads and writes documents. read: reads documents. |
+| `@collection` | string | no | | | metaobjects-systems-core | The one collection the grant covers. Absent: every collection. |
+| `@resource` | string | yes | | | metaobjects-systems-core | The document store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api). |
+
+**Allowed children**
+
+_No structural children._
+
+### grant.keyValue
+
+Access to a key-value store of the role's own system (`resource.keyValue`), optionally limited to keys with one prefix.
+
+**Owning provider:** metaobjects-systems-core
+
+**Rules:** @resource names a resource.keyValue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
+**When to use:** A role that reads or writes a cache or a key-value store.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@access` | string | yes | | `readWrite`, `read` | metaobjects-systems-core | readWrite: reads and writes values. read: reads values. |
+| `@keyPrefix` | string | no | | | metaobjects-systems-core | The key prefix the grant covers. Absent: every key. |
+| `@resource` | string | yes | | | metaobjects-systems-core | The key-value store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api). |
+
+**Allowed children**
+
+_No structural children._
+
+### grant.objectStore
+
+Access to an object store of the role's own system (`resource.objectStore`), optionally limited to objects under one prefix.
+
+**Owning provider:** metaobjects-systems-core
+
+**Rules:** @resource names a resource.objectStore of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
+**When to use:** A role that uploads, downloads or manages files and blobs.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@access` | string | yes | | `read`, `write`, `readWrite`, `manage` | metaobjects-systems-core | read: reads objects. write: writes objects and cannot read them. readWrite: both. manage: also deletes objects and changes the store's settings. |
+| `@prefix` | string | no | | | metaobjects-systems-core | The object key prefix the grant covers. Absent: every object. |
+| `@resource` | string | yes | | | metaobjects-systems-core | The object store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api). |
+
+**Allowed children**
+
+_No structural children._
+
+### grant.queue
+
+Access to a message queue of the role's own system (`resource.queue`).
+
+**Owning provider:** metaobjects-systems-core
+
+**Rules:** @resource names a resource.queue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
+**When to use:** A role that sends work to a queue or takes work from it.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@access` | string | yes | | `publish`, `consume` | metaobjects-systems-core | publish: sends messages. consume: receives and acknowledges them. |
+| `@resource` | string | yes | | | metaobjects-systems-core | The queue this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a queue of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api). |
+
+**Allowed children**
+
+_No structural children._
+
+### grant.rdb
+
+Access to a relational database of the role's own system (`resource.rdb`), optionally limited to one schema.
+
+**Owning provider:** metaobjects-systems-core
+
+**Rules:** @resource names a resource.rdb of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
+**When to use:** A role that connects to the database: the app's service role, a reporting job, the role migrations run as (`access: owner`).
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@access` | string | yes | | `owner`, `readWrite`, `read` | metaobjects-systems-core | owner: creates and changes the schema's tables (the role migrations run as). readWrite: reads and writes rows. read: reads rows. |
+| `@maintain` | boolean | no | | | metaobjects-systems-core | The role may also refresh materialized views and run maintenance on the tables it covers (PostgreSQL's MAINTAIN privilege). Absent means it may not. |
+| `@resource` | string | yes | | | metaobjects-systems-core | The relational database this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a database of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api). |
+| `@schema` | string | no | | | metaobjects-systems-core | The one schema the grant covers. Absent: every schema of the database. |
+
+**Allowed children**
+
+_No structural children._
+
+### grant.search
+
+Access to a search index of the role's own system (`resource.search`), optionally limited to one index.
+
+**Owning provider:** metaobjects-systems-core
+
+**Rules:** @resource names a resource.search of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
+**When to use:** A role that queries an index or keeps it up to date.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@access` | string | yes | | `read`, `write`, `manage` | metaobjects-systems-core | read: queries. write: adds, changes and removes documents. manage: also creates and drops indexes. |
+| `@index` | string | no | | | metaobjects-systems-core | The one index the grant covers. Absent: every index. |
+| `@resource` | string | yes | | | metaobjects-systems-core | The search index this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; an index of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api). |
+
+**Allowed children**
+
+_No structural children._
+
+### grant.stream
+
+Access to a stream of the role's own system (`resource.stream`).
+
+**Owning provider:** metaobjects-systems-core
+
+**Rules:** @resource names a resource.stream of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
+**When to use:** A role that appends to a stream or reads it.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@access` | string | yes | | `publish`, `consume` | metaobjects-systems-core | publish: appends messages. consume: reads them, in a consumer group of its own. |
+| `@resource` | string | yes | | | metaobjects-systems-core | The stream this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a stream of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api). |
+
+**Allowed children**
+
+_No structural children._
+
diff --git a/fixtures/metamodel-docs/expected/types/role.md b/fixtures/metamodel-docs/expected/types/role.md
index 1a9f1f90cc..3125c99c3d 100644
--- a/fixtures/metamodel-docs/expected/types/role.md
+++ b/fixtures/metamodel-docs/expected/types/role.md
@@ -25,7 +25,7 @@ Abstract role base: an identity that can act in its system. Not authored directl
**Allowed children**
-_No structural children._
+- `grant.*` — 0..*
### role.group
@@ -44,7 +44,7 @@ Nobody directly: a group exists to carry what its members share (@memberOf), and
**Allowed children**
-_No structural children._
+- `grant.*` — 0..*
### role.service
@@ -63,7 +63,7 @@ A running app or job. A generator creates a login for it and delivers the creden
**Allowed children**
-_No structural children._
+- `grant.*` — 0..*
### role.token
@@ -83,7 +83,7 @@ Automation outside the system's own apps, given a scoped token: a deploy pipelin
**Allowed children**
-_No structural children._
+- `grant.*` — 0..*
### role.user
@@ -102,5 +102,5 @@ A named person, or an agent acting for one. No shared secret is generated or sto
**Allowed children**
-_No structural children._
+- `grant.*` — 0..*
diff --git a/fixtures/metamodel-docs/expected/types/source.md b/fixtures/metamodel-docs/expected/types/source.md
index a2295d3922..963e09d21a 100644
--- a/fixtures/metamodel-docs/expected/types/source.md
+++ b/fixtures/metamodel-docs/expected/types/source.md
@@ -24,9 +24,28 @@ _No subtype-specific attributes._
_No structural children._
+### source.document
+
+The document-store paradigm source (ADR-0007's `document`): the object's records are kept as documents in a collection, in the document store @resource names. Registered by the systems provider, not by core-types. No generator writes from it yet.
+
+**Owning provider:** metaobjects-systems-core
+
+**When to use:** An object kept as documents in a document store.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@collection` | string | no | | | metaobjects-systems-core | The collection that holds the documents. Absent: derived from the object's name. |
+| `@resource` | string | no | | | metaobjects-systems-core | The document store, by name (`Parcels.docs`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a document store, is ERR_REF_WRONG_KIND. |
+
+**Allowed children**
+
+_No structural children._
+
### source.rdb
-The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, not by core-types.
+The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, and @resource by the systems provider (metaobjects-systems-core), not by core-types.
**Owning provider:** metaobjects-core-types
@@ -43,6 +62,7 @@ The relational-database paradigm source (ADR-0007): binds an object to a physica
| `@materializedView` | string | no | | | metaobjects-db | Physical SQL materialized-view name for source.rdb @kind: "materializedView". Same internal slot as @table. |
| `@parameterRef` | string | no | | | metaobjects-db | FR-015: name or FQN of an object.value describing the input shape of this source's callable interface. Permitted on @kind: "storedProc" / "tableFunction"; rejected on non-callable kinds (table / view / materializedView). Field children of the referenced object.value become the call-site parameter list in declaration order. Symmetric with template.@payloadRef in FR-004 — the typed-input pattern reuses object.value rather than minting a new parameter.* node type. |
| `@proc` | string | no | | | metaobjects-db | Physical SQL stored-procedure name for source.rdb @kind: "storedProc". Same internal slot as @table. |
+| `@resource` | string | no | | | metaobjects-systems-core | The relational database this source's table or view lives in: a `resource.rdb`, by name (`Parcels.db`, or `pkg::Parcels.db` from another package). Optional: a model that declares no systems names none. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a relational database, is ERR_REF_WRONG_KIND. |
| `@role` | string | no | | `primary`, `replica` | metaobjects-db | Role this source plays when an object has multiple sources: primary (default, system of record) or replica. The former members index, cache, publish and mirror are reserved-not-registered (ADR-0007 Amendment 2): a role member enters the registry only when a shipping consumer dispatches on it. |
| `@schema` | string | no | | | metaobjects-db | Optional database schema name (e.g. 'catalog', 'public'). Postgres defaults to 'public'; SQLite rejects any non-default value. |
| `@sql` | string | no | | | metaobjects-db | FR-024/#208 escape valve — a hand-written SQL body the tool REGISTERS + fingerprints + drift-checks but never authors or parses. The body goes INSIDE `CREATE AS …` (never the CREATE wrapper, never the object name). Legal only on a read-only kind (not @kind: table); migrate lowers it on @kind: view (matview/proc/tableFunction: registered but not yet migrate-managed). Mutually exclusive with @unmanaged; forbids origin.* children (two sources of truth). |
@@ -54,3 +74,22 @@ The relational-database paradigm source (ADR-0007): binds an object to a physica
_No structural children._
+### source.search
+
+The search-index paradigm source (ADR-0007's `search`): the object's records are kept in a search index, usually as a copy of data kept elsewhere. Registered by the systems provider, not by core-types. No generator writes from it yet.
+
+**Owning provider:** metaobjects-systems-core
+
+**When to use:** An object searched by text and filters.
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@index` | string | no | | | metaobjects-systems-core | The index that holds the documents. Absent: derived from the object's name. |
+| `@resource` | string | no | | | metaobjects-systems-core | The search index resource, by name (`Parcels.search`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a search index, is ERR_REF_WRONG_KIND. |
+
+**Allowed children**
+
+_No structural children._
+
diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json
index 9fe5e46633..5706cbd3a3 100644
--- a/fixtures/registry-conformance/expected-registry.json
+++ b/fixtures/registry-conformance/expected-registry.json
@@ -39,9 +39,11 @@
"targetType": "role",
"targetSubTypes": [
"service"
- ]
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_RUNSAS_OTHER_SYSTEM"
},
- "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND."
+ "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system)."
}
],
"children": [
@@ -69,9 +71,11 @@
"targetType": "role",
"targetSubTypes": [
"service"
- ]
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_RUNSAS_OTHER_SYSTEM"
},
- "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND."
+ "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system)."
},
{
"name": "shell",
@@ -106,9 +110,11 @@
"targetType": "role",
"targetSubTypes": [
"service"
- ]
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_RUNSAS_OTHER_SYSTEM"
},
- "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND."
+ "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system)."
},
{
"name": "schedule",
@@ -150,9 +156,11 @@
"targetType": "role",
"targetSubTypes": [
"service"
- ]
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_RUNSAS_OTHER_SYSTEM"
},
- "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND."
+ "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system)."
}
],
"children": [
@@ -3217,6 +3225,344 @@
}
]
},
+ {
+ "type": "grant",
+ "subType": "api",
+ "description": "The role may call an API, in any system: this is how one system reaches another's data. The access it implies on whatever carries the API is derived, never written.",
+ "whenToUse": "A role whose app calls another system's API, or an outside party's token that consumes one of ours.",
+ "attrs": [
+ {
+ "name": "api",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "ref": {
+ "targetType": "api"
+ },
+ "description": "The API, by name (`pkg::ShipmentApi`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND."
+ },
+ {
+ "name": "credential",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "description": "The name of an existing key this grant uses (`keys/LARKSPUR_API_KEY`). Never a value. Written only for a key the model cannot create, such as one an outside party issued; otherwise the credential is implied, with a derived name."
+ },
+ {
+ "name": "operations",
+ "valueType": "string",
+ "isArray": true,
+ "required": false,
+ "description": "The operations of the API the role may call, by name. Absent: all of them."
+ }
+ ],
+ "children": []
+ },
+ {
+ "type": "grant",
+ "subType": "base",
+ "description": "Abstract grant base: what a role may do to one resource of its own system, or to one API. A grant is a child of a role. Its kind is the kind of thing it is on, so a grant.rdb names a resource.rdb. Not authored directly: a `grant.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).",
+ "attrs": [],
+ "children": []
+ },
+ {
+ "type": "grant",
+ "subType": "document",
+ "description": "Access to a document store of the role's own system (`resource.document`), optionally limited to one collection.",
+ "rules": "@resource names a resource.document of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "whenToUse": "A role that reads or writes documents.",
+ "attrs": [
+ {
+ "name": "access",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "allowedValues": [
+ "readWrite",
+ "read"
+ ],
+ "description": "readWrite: reads and writes documents. read: reads documents."
+ },
+ {
+ "name": "collection",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "description": "The one collection the grant covers. Absent: every collection."
+ },
+ {
+ "name": "resource",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "document"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ },
+ "description": "The document store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ }
+ ],
+ "children": []
+ },
+ {
+ "type": "grant",
+ "subType": "keyValue",
+ "description": "Access to a key-value store of the role's own system (`resource.keyValue`), optionally limited to keys with one prefix.",
+ "rules": "@resource names a resource.keyValue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "whenToUse": "A role that reads or writes a cache or a key-value store.",
+ "attrs": [
+ {
+ "name": "access",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "allowedValues": [
+ "readWrite",
+ "read"
+ ],
+ "description": "readWrite: reads and writes values. read: reads values."
+ },
+ {
+ "name": "keyPrefix",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "description": "The key prefix the grant covers. Absent: every key."
+ },
+ {
+ "name": "resource",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "keyValue"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ },
+ "description": "The key-value store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ }
+ ],
+ "children": []
+ },
+ {
+ "type": "grant",
+ "subType": "objectStore",
+ "description": "Access to an object store of the role's own system (`resource.objectStore`), optionally limited to objects under one prefix.",
+ "rules": "@resource names a resource.objectStore of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "whenToUse": "A role that uploads, downloads or manages files and blobs.",
+ "attrs": [
+ {
+ "name": "access",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "allowedValues": [
+ "read",
+ "write",
+ "readWrite",
+ "manage"
+ ],
+ "description": "read: reads objects. write: writes objects and cannot read them. readWrite: both. manage: also deletes objects and changes the store's settings."
+ },
+ {
+ "name": "prefix",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "description": "The object key prefix the grant covers. Absent: every object."
+ },
+ {
+ "name": "resource",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "objectStore"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ },
+ "description": "The object store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ }
+ ],
+ "children": []
+ },
+ {
+ "type": "grant",
+ "subType": "queue",
+ "description": "Access to a message queue of the role's own system (`resource.queue`).",
+ "rules": "@resource names a resource.queue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "whenToUse": "A role that sends work to a queue or takes work from it.",
+ "attrs": [
+ {
+ "name": "access",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "allowedValues": [
+ "publish",
+ "consume"
+ ],
+ "description": "publish: sends messages. consume: receives and acknowledges them."
+ },
+ {
+ "name": "resource",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "queue"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ },
+ "description": "The queue this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a queue of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ }
+ ],
+ "children": []
+ },
+ {
+ "type": "grant",
+ "subType": "rdb",
+ "description": "Access to a relational database of the role's own system (`resource.rdb`), optionally limited to one schema.",
+ "rules": "@resource names a resource.rdb of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "whenToUse": "A role that connects to the database: the app's service role, a reporting job, the role migrations run as (`access: owner`).",
+ "attrs": [
+ {
+ "name": "access",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "allowedValues": [
+ "owner",
+ "readWrite",
+ "read"
+ ],
+ "description": "owner: creates and changes the schema's tables (the role migrations run as). readWrite: reads and writes rows. read: reads rows."
+ },
+ {
+ "name": "maintain",
+ "valueType": "boolean",
+ "isArray": false,
+ "required": false,
+ "description": "The role may also refresh materialized views and run maintenance on the tables it covers (PostgreSQL's MAINTAIN privilege). Absent means it may not."
+ },
+ {
+ "name": "resource",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "rdb"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ },
+ "description": "The relational database this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a database of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ },
+ {
+ "name": "schema",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "description": "The one schema the grant covers. Absent: every schema of the database."
+ }
+ ],
+ "children": []
+ },
+ {
+ "type": "grant",
+ "subType": "search",
+ "description": "Access to a search index of the role's own system (`resource.search`), optionally limited to one index.",
+ "rules": "@resource names a resource.search of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "whenToUse": "A role that queries an index or keeps it up to date.",
+ "attrs": [
+ {
+ "name": "access",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "allowedValues": [
+ "read",
+ "write",
+ "manage"
+ ],
+ "description": "read: queries. write: adds, changes and removes documents. manage: also creates and drops indexes."
+ },
+ {
+ "name": "index",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "description": "The one index the grant covers. Absent: every index."
+ },
+ {
+ "name": "resource",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "search"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ },
+ "description": "The search index this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; an index of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ }
+ ],
+ "children": []
+ },
+ {
+ "type": "grant",
+ "subType": "stream",
+ "description": "Access to a stream of the role's own system (`resource.stream`).",
+ "rules": "@resource names a resource.stream of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "whenToUse": "A role that appends to a stream or reads it.",
+ "attrs": [
+ {
+ "name": "access",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "allowedValues": [
+ "publish",
+ "consume"
+ ],
+ "description": "publish: appends messages. consume: reads them, in a consumer group of its own."
+ },
+ {
+ "name": "resource",
+ "valueType": "string",
+ "isArray": false,
+ "required": true,
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "stream"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ },
+ "description": "The stream this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a stream of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api)."
+ }
+ ],
+ "children": []
+ },
{
"type": "identity",
"subType": "primary",
@@ -5341,7 +5687,15 @@
"description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND."
}
],
- "children": []
+ "children": [
+ {
+ "childType": "grant",
+ "childSubType": "*",
+ "childName": "*",
+ "min": 0,
+ "max": null
+ }
+ ]
},
{
"type": "role",
@@ -5370,7 +5724,15 @@
"description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND."
}
],
- "children": []
+ "children": [
+ {
+ "childType": "grant",
+ "childSubType": "*",
+ "childName": "*",
+ "min": 0,
+ "max": null
+ }
+ ]
},
{
"type": "role",
@@ -5399,7 +5761,15 @@
"description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND."
}
],
- "children": []
+ "children": [
+ {
+ "childType": "grant",
+ "childSubType": "*",
+ "childName": "*",
+ "min": 0,
+ "max": null
+ }
+ ]
},
{
"type": "role",
@@ -5441,7 +5811,15 @@
"description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND."
}
],
- "children": []
+ "children": [
+ {
+ "childType": "grant",
+ "childSubType": "*",
+ "childName": "*",
+ "min": 0,
+ "max": null
+ }
+ ]
},
{
"type": "role",
@@ -5470,7 +5848,15 @@
"description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND."
}
],
- "children": []
+ "children": [
+ {
+ "childType": "grant",
+ "childSubType": "*",
+ "childName": "*",
+ "min": 0,
+ "max": null
+ }
+ ]
},
{
"type": "segment",
@@ -5495,10 +5881,39 @@
"attrs": [],
"children": []
},
+ {
+ "type": "source",
+ "subType": "document",
+ "description": "The document-store paradigm source (ADR-0007's `document`): the object's records are kept as documents in a collection, in the document store @resource names. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "whenToUse": "An object kept as documents in a document store.",
+ "attrs": [
+ {
+ "name": "collection",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "description": "The collection that holds the documents. Absent: derived from the object's name."
+ },
+ {
+ "name": "resource",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "document"
+ ]
+ },
+ "description": "The document store, by name (`Parcels.docs`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a document store, is ERR_REF_WRONG_KIND."
+ }
+ ],
+ "children": []
+ },
{
"type": "source",
"subType": "rdb",
- "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, not by core-types.",
+ "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, and @resource by the systems provider (metaobjects-systems-core), not by core-types.",
"rules": "ADR-0007: source declares where an object's data lives; rdb is the relational paradigm subtype. An object may declare multiple sources, distinguished by @role, with exactly ONE @role: \"primary\" per object (write-through CQRS: a writable table for writes plus a read-only view for reads). The physical name is the @table attr (or the @kind-matching alias), never the structural `name`. Read-only-ness is derived from @kind (table → writable; view / materializedView / storedProc / tableFunction → read-only). The pre-v2 dbTable / dbView subtypes are retired.",
"whenToUse": "The entity is backed by a relational table or view. Set @table/@kind — the default persistence source for any entity.",
"attrs": [
@@ -5544,6 +5959,19 @@
"required": false,
"description": "Physical SQL stored-procedure name for source.rdb @kind: \"storedProc\". Same internal slot as @table."
},
+ {
+ "name": "resource",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "rdb"
+ ]
+ },
+ "description": "The relational database this source's table or view lives in: a `resource.rdb`, by name (`Parcels.db`, or `pkg::Parcels.db` from another package). Optional: a model that declares no systems names none. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a relational database, is ERR_REF_WRONG_KIND."
+ },
{
"name": "role",
"valueType": "string",
@@ -5593,6 +6021,35 @@
],
"children": []
},
+ {
+ "type": "source",
+ "subType": "search",
+ "description": "The search-index paradigm source (ADR-0007's `search`): the object's records are kept in a search index, usually as a copy of data kept elsewhere. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "whenToUse": "An object searched by text and filters.",
+ "attrs": [
+ {
+ "name": "index",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "description": "The index that holds the documents. Absent: derived from the object's name."
+ },
+ {
+ "name": "resource",
+ "valueType": "string",
+ "isArray": false,
+ "required": false,
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "search"
+ ]
+ },
+ "description": "The search index resource, by name (`Parcels.search`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a search index, is ERR_REF_WRONG_KIND."
+ }
+ ],
+ "children": []
+ },
{
"type": "system",
"subType": "base",
diff --git a/fixtures/registry-conformance/providers.json b/fixtures/registry-conformance/providers.json
index 4199b7c224..76a884e8e1 100644
--- a/fixtures/registry-conformance/providers.json
+++ b/fixtures/registry-conformance/providers.json
@@ -80,7 +80,8 @@
"metaobjects-systems-core": {
"declaresTypes": true,
"projectsOnto": [
- "metadata.root"
+ "metadata.root",
+ "source.rdb"
]
},
"metaobjects-ui": {
diff --git a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs
index b64d472065..96381f0178 100644
--- a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs
+++ b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs
@@ -1,6 +1,6 @@
// @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
//
-// One slot per authored promise in metaobjects/meta.requirements.yaml (143 of them).
+// One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them).
// Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
// claim that nothing is verified — the conformance corpora already check many of
// these. To FILL one, move it into C#'s own suite and write the assertion the
@@ -256,6 +256,10 @@ public void declare_persistenceMapping_indexLookup() { /* metaobjects.declare.pe
[Fact(Skip = "unfilled slot — write an assertion that fails when: An index declaring both a field list and an expression, where half of it is quietly discarded and the index built is not the index described.")]
public void declare_persistenceMapping_indexLookup_expr() { /* metaobjects.declare.persistenceMapping.indexLookup.expr */ }
+ // Document source — A document source places an object in a collection of a declared document store, and its resource must name a document store.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: An object said to live in a document store whose name, on inspection, belongs to a queue.")]
+ public void declare_persistenceMapping_sourceDocument() { /* metaobjects.declare.persistenceMapping.sourceDocument */ }
+
// Relational source — A relational source says where an object's data lives, in what kind of place, and in what role, without naming a database engine.
[Fact(Skip = "unfilled slot — write an assertion that fails when: A model that only reveals which engine it assumed when a migration fails against a different one.")]
public void declare_persistenceMapping_sourceRdb() { /* metaobjects.declare.persistenceMapping.sourceRdb */ }
@@ -276,6 +280,10 @@ public void declare_persistenceMapping_sourceRdb_sql() { /* metaobjects.declare.
[Fact(Skip = "unfilled slot — write an assertion that fails when: A hand-maintained view rewritten by a migration that assumed it owned it.")]
public void declare_persistenceMapping_sourceRdb_unmanaged() { /* metaobjects.declare.persistenceMapping.sourceRdb.unmanaged */ }
+ // Search source — A search source places an object in an index of a declared search store, and its resource must name a search store.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: A search index fed from an object whose model says nothing of the index, so it is missed in a rename.")]
+ public void declare_persistenceMapping_sourceSearch() { /* metaobjects.declare.persistenceMapping.sourceSearch */ }
+
// Data grid — A data grid declares which of an object's fields a tabular view shows, in what order, and how it is sorted and paged before anyone touches it.
[Fact(Skip = "unfilled slot — write an assertion that fails when: A table that gains a column every time the model does, including the ones nobody meant to show.")]
public void declare_presentation_layoutDataGrid() { /* metaobjects.declare.presentation.layoutDataGrid */ }
@@ -404,6 +412,38 @@ public void declare_systemsAndRoles_appService() { /* metaobjects.declare.system
[Fact(Skip = "unfilled slot — write an assertion that fails when: An app with no recorded build, deployed from whichever image tag someone last pushed.")]
public void declare_systemsAndRoles_buildImage() { /* metaobjects.declare.systemsAndRoles.buildImage */ }
+ // API grant — An API grant says which operations of an API, in any system, a role may call, and with which credential.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: A caller whose access to another team's API is recorded only in that team's gateway configuration.")]
+ public void declare_systemsAndRoles_grantApi() { /* metaobjects.declare.systemsAndRoles.grantApi */ }
+
+ // Document grant — A document grant says what a role may do with a document store of its own system, optionally in one collection.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: A reporting job with write access to the collection it only reads.")]
+ public void declare_systemsAndRoles_grantDocument() { /* metaobjects.declare.systemsAndRoles.grantDocument */ }
+
+ // Key-value grant — A key-value grant says what a role may do with a key-value resource of its own system, optionally under one key prefix.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: A cache shared by two services, each free to overwrite the other's keys.")]
+ public void declare_systemsAndRoles_grantKeyValue() { /* metaobjects.declare.systemsAndRoles.grantKeyValue */ }
+
+ // Object-store grant — An object-store grant says what a role may do with an object store of its own system, optionally under one prefix.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: A bucket every service can write to, found when one of them deleted another's uploads.")]
+ public void declare_systemsAndRoles_grantObjectStore() { /* metaobjects.declare.systemsAndRoles.grantObjectStore */ }
+
+ // Queue grant — A queue grant says whether a role sends to or receives from a queue of its own system.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: A consumer that also publishes to its own queue, so a retry loop feeds itself.")]
+ public void declare_systemsAndRoles_grantQueue() { /* metaobjects.declare.systemsAndRoles.grantQueue */ }
+
+ // Database grant — A database grant says what a role may do in one schema of a relational resource of its own system, down to owning it or only reading it.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: A service that can drop tables because its credentials were copied from the migration job.")]
+ public void declare_systemsAndRoles_grantRdb() { /* metaobjects.declare.systemsAndRoles.grantRdb */ }
+
+ // Search grant — A search grant says what a role may do with a search store of its own system, optionally in one index.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: An index rebuilt by a service nobody remembered had write access to it.")]
+ public void declare_systemsAndRoles_grantSearch() { /* metaobjects.declare.systemsAndRoles.grantSearch */ }
+
+ // Stream grant — A stream grant says whether a role writes to or reads from a stream of its own system, and naming another system's stream is refused.
+ [Fact(Skip = "unfilled slot — write an assertion that fails when: A service reading another team's stream directly, so a schema change there breaks it without warning.")]
+ public void declare_systemsAndRoles_grantStream() { /* metaobjects.declare.systemsAndRoles.grantStream */ }
+
// Company — A company is the top of an ownership tree, so a system names who answers for it.
[Fact(Skip = "unfilled slot — write an assertion that fails when: A system whose owner is a free-text team name nobody can check.")]
public void declare_systemsAndRoles_organizationCompany() { /* metaobjects.declare.systemsAndRoles.organizationCompany */ }
diff --git a/fixtures/requirement-harness/java/RequirementHarnessTest.java b/fixtures/requirement-harness/java/RequirementHarnessTest.java
index ceb001128b..d00ac8bd42 100644
--- a/fixtures/requirement-harness/java/RequirementHarnessTest.java
+++ b/fixtures/requirement-harness/java/RequirementHarnessTest.java
@@ -1,6 +1,6 @@
// @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
//
-// One slot per authored promise in metaobjects/meta.requirements.yaml (143 of them).
+// One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them).
// Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
// claim that nothing is verified — the conformance corpora already check many of
// these. To FILL one, move it into Java's own suite and write the assertion the
@@ -317,6 +317,11 @@ void declare_persistenceMapping_indexLookup() { /* metaobjects.declare.persisten
@Disabled("unfilled slot — write an assertion that fails when: An index declaring both a field list and an expression, where half of it is quietly discarded and the index built is not the index described.")
void declare_persistenceMapping_indexLookup_expr() { /* metaobjects.declare.persistenceMapping.indexLookup.expr */ }
+ // Document source — A document source places an object in a collection of a declared document store, and its resource must name a document store.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: An object said to live in a document store whose name, on inspection, belongs to a queue.")
+ void declare_persistenceMapping_sourceDocument() { /* metaobjects.declare.persistenceMapping.sourceDocument */ }
+
// Relational source — A relational source says where an object's data lives, in what kind of place, and in what role, without naming a database engine.
@Test
@Disabled("unfilled slot — write an assertion that fails when: A model that only reveals which engine it assumed when a migration fails against a different one.")
@@ -342,6 +347,11 @@ void declare_persistenceMapping_sourceRdb_sql() { /* metaobjects.declare.persist
@Disabled("unfilled slot — write an assertion that fails when: A hand-maintained view rewritten by a migration that assumed it owned it.")
void declare_persistenceMapping_sourceRdb_unmanaged() { /* metaobjects.declare.persistenceMapping.sourceRdb.unmanaged */ }
+ // Search source — A search source places an object in an index of a declared search store, and its resource must name a search store.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A search index fed from an object whose model says nothing of the index, so it is missed in a rename.")
+ void declare_persistenceMapping_sourceSearch() { /* metaobjects.declare.persistenceMapping.sourceSearch */ }
+
// Data grid — A data grid declares which of an object's fields a tabular view shows, in what order, and how it is sorted and paged before anyone touches it.
@Test
@Disabled("unfilled slot — write an assertion that fails when: A table that gains a column every time the model does, including the ones nobody meant to show.")
@@ -502,6 +512,46 @@ void declare_systemsAndRoles_appService() { /* metaobjects.declare.systemsAndRol
@Disabled("unfilled slot — write an assertion that fails when: An app with no recorded build, deployed from whichever image tag someone last pushed.")
void declare_systemsAndRoles_buildImage() { /* metaobjects.declare.systemsAndRoles.buildImage */ }
+ // API grant — An API grant says which operations of an API, in any system, a role may call, and with which credential.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A caller whose access to another team's API is recorded only in that team's gateway configuration.")
+ void declare_systemsAndRoles_grantApi() { /* metaobjects.declare.systemsAndRoles.grantApi */ }
+
+ // Document grant — A document grant says what a role may do with a document store of its own system, optionally in one collection.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A reporting job with write access to the collection it only reads.")
+ void declare_systemsAndRoles_grantDocument() { /* metaobjects.declare.systemsAndRoles.grantDocument */ }
+
+ // Key-value grant — A key-value grant says what a role may do with a key-value resource of its own system, optionally under one key prefix.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A cache shared by two services, each free to overwrite the other's keys.")
+ void declare_systemsAndRoles_grantKeyValue() { /* metaobjects.declare.systemsAndRoles.grantKeyValue */ }
+
+ // Object-store grant — An object-store grant says what a role may do with an object store of its own system, optionally under one prefix.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A bucket every service can write to, found when one of them deleted another's uploads.")
+ void declare_systemsAndRoles_grantObjectStore() { /* metaobjects.declare.systemsAndRoles.grantObjectStore */ }
+
+ // Queue grant — A queue grant says whether a role sends to or receives from a queue of its own system.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A consumer that also publishes to its own queue, so a retry loop feeds itself.")
+ void declare_systemsAndRoles_grantQueue() { /* metaobjects.declare.systemsAndRoles.grantQueue */ }
+
+ // Database grant — A database grant says what a role may do in one schema of a relational resource of its own system, down to owning it or only reading it.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A service that can drop tables because its credentials were copied from the migration job.")
+ void declare_systemsAndRoles_grantRdb() { /* metaobjects.declare.systemsAndRoles.grantRdb */ }
+
+ // Search grant — A search grant says what a role may do with a search store of its own system, optionally in one index.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: An index rebuilt by a service nobody remembered had write access to it.")
+ void declare_systemsAndRoles_grantSearch() { /* metaobjects.declare.systemsAndRoles.grantSearch */ }
+
+ // Stream grant — A stream grant says whether a role writes to or reads from a stream of its own system, and naming another system's stream is refused.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A service reading another team's stream directly, so a schema change there breaks it without warning.")
+ void declare_systemsAndRoles_grantStream() { /* metaobjects.declare.systemsAndRoles.grantStream */ }
+
// Company — A company is the top of an ownership tree, so a system names who answers for it.
@Test
@Disabled("unfilled slot — write an assertion that fails when: A system whose owner is a free-text team name nobody can check.")
diff --git a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt
index 1ec1c8e1fd..b298440758 100644
--- a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt
+++ b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt
@@ -1,6 +1,6 @@
// @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
//
-// One slot per authored promise in metaobjects/meta.requirements.yaml (143 of them).
+// One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them).
// Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
// claim that nothing is verified — the conformance corpora already check many of
// these. To FILL one, move it into Kotlin's own suite and write the assertion the
@@ -317,6 +317,11 @@ class RequirementHarnessTest {
@Disabled("unfilled slot — write an assertion that fails when: An index declaring both a field list and an expression, where half of it is quietly discarded and the index built is not the index described.")
fun declare_persistenceMapping_indexLookup_expr() { /* metaobjects.declare.persistenceMapping.indexLookup.expr */ }
+ // Document source — A document source places an object in a collection of a declared document store, and its resource must name a document store.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: An object said to live in a document store whose name, on inspection, belongs to a queue.")
+ fun declare_persistenceMapping_sourceDocument() { /* metaobjects.declare.persistenceMapping.sourceDocument */ }
+
// Relational source — A relational source says where an object's data lives, in what kind of place, and in what role, without naming a database engine.
@Test
@Disabled("unfilled slot — write an assertion that fails when: A model that only reveals which engine it assumed when a migration fails against a different one.")
@@ -342,6 +347,11 @@ class RequirementHarnessTest {
@Disabled("unfilled slot — write an assertion that fails when: A hand-maintained view rewritten by a migration that assumed it owned it.")
fun declare_persistenceMapping_sourceRdb_unmanaged() { /* metaobjects.declare.persistenceMapping.sourceRdb.unmanaged */ }
+ // Search source — A search source places an object in an index of a declared search store, and its resource must name a search store.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A search index fed from an object whose model says nothing of the index, so it is missed in a rename.")
+ fun declare_persistenceMapping_sourceSearch() { /* metaobjects.declare.persistenceMapping.sourceSearch */ }
+
// Data grid — A data grid declares which of an object's fields a tabular view shows, in what order, and how it is sorted and paged before anyone touches it.
@Test
@Disabled("unfilled slot — write an assertion that fails when: A table that gains a column every time the model does, including the ones nobody meant to show.")
@@ -502,6 +512,46 @@ class RequirementHarnessTest {
@Disabled("unfilled slot — write an assertion that fails when: An app with no recorded build, deployed from whichever image tag someone last pushed.")
fun declare_systemsAndRoles_buildImage() { /* metaobjects.declare.systemsAndRoles.buildImage */ }
+ // API grant — An API grant says which operations of an API, in any system, a role may call, and with which credential.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A caller whose access to another team's API is recorded only in that team's gateway configuration.")
+ fun declare_systemsAndRoles_grantApi() { /* metaobjects.declare.systemsAndRoles.grantApi */ }
+
+ // Document grant — A document grant says what a role may do with a document store of its own system, optionally in one collection.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A reporting job with write access to the collection it only reads.")
+ fun declare_systemsAndRoles_grantDocument() { /* metaobjects.declare.systemsAndRoles.grantDocument */ }
+
+ // Key-value grant — A key-value grant says what a role may do with a key-value resource of its own system, optionally under one key prefix.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A cache shared by two services, each free to overwrite the other's keys.")
+ fun declare_systemsAndRoles_grantKeyValue() { /* metaobjects.declare.systemsAndRoles.grantKeyValue */ }
+
+ // Object-store grant — An object-store grant says what a role may do with an object store of its own system, optionally under one prefix.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A bucket every service can write to, found when one of them deleted another's uploads.")
+ fun declare_systemsAndRoles_grantObjectStore() { /* metaobjects.declare.systemsAndRoles.grantObjectStore */ }
+
+ // Queue grant — A queue grant says whether a role sends to or receives from a queue of its own system.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A consumer that also publishes to its own queue, so a retry loop feeds itself.")
+ fun declare_systemsAndRoles_grantQueue() { /* metaobjects.declare.systemsAndRoles.grantQueue */ }
+
+ // Database grant — A database grant says what a role may do in one schema of a relational resource of its own system, down to owning it or only reading it.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A service that can drop tables because its credentials were copied from the migration job.")
+ fun declare_systemsAndRoles_grantRdb() { /* metaobjects.declare.systemsAndRoles.grantRdb */ }
+
+ // Search grant — A search grant says what a role may do with a search store of its own system, optionally in one index.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: An index rebuilt by a service nobody remembered had write access to it.")
+ fun declare_systemsAndRoles_grantSearch() { /* metaobjects.declare.systemsAndRoles.grantSearch */ }
+
+ // Stream grant — A stream grant says whether a role writes to or reads from a stream of its own system, and naming another system's stream is refused.
+ @Test
+ @Disabled("unfilled slot — write an assertion that fails when: A service reading another team's stream directly, so a schema change there breaks it without warning.")
+ fun declare_systemsAndRoles_grantStream() { /* metaobjects.declare.systemsAndRoles.grantStream */ }
+
// Company — A company is the top of an ownership tree, so a system names who answers for it.
@Test
@Disabled("unfilled slot — write an assertion that fails when: A system whose owner is a free-text team name nobody can check.")
diff --git a/fixtures/requirement-harness/python/test_requirement_harness.py b/fixtures/requirement-harness/python/test_requirement_harness.py
index 956fbe96e3..b72aed7396 100644
--- a/fixtures/requirement-harness/python/test_requirement_harness.py
+++ b/fixtures/requirement-harness/python/test_requirement_harness.py
@@ -1,6 +1,6 @@
# @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
#
-# One slot per authored promise in metaobjects/meta.requirements.yaml (143 of them).
+# One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them).
# Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
# claim that nothing is verified — the conformance corpora already check many of
# these. To FILL one, move it into Python's own suite and write the assertion the
@@ -312,6 +312,11 @@ def test_declare_persistenceMapping_indexLookup():
def test_declare_persistenceMapping_indexLookup_expr():
"""metaobjects.declare.persistenceMapping.indexLookup.expr"""
+# Document source — A document source places an object in a collection of a declared document store, and its resource must name a document store.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: An object said to live in a document store whose name, on inspection, belongs to a queue.")
+def test_declare_persistenceMapping_sourceDocument():
+ """metaobjects.declare.persistenceMapping.sourceDocument"""
+
# Relational source — A relational source says where an object's data lives, in what kind of place, and in what role, without naming a database engine.
@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A model that only reveals which engine it assumed when a migration fails against a different one.")
def test_declare_persistenceMapping_sourceRdb():
@@ -337,6 +342,11 @@ def test_declare_persistenceMapping_sourceRdb_sql():
def test_declare_persistenceMapping_sourceRdb_unmanaged():
"""metaobjects.declare.persistenceMapping.sourceRdb.unmanaged"""
+# Search source — A search source places an object in an index of a declared search store, and its resource must name a search store.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A search index fed from an object whose model says nothing of the index, so it is missed in a rename.")
+def test_declare_persistenceMapping_sourceSearch():
+ """metaobjects.declare.persistenceMapping.sourceSearch"""
+
# Data grid — A data grid declares which of an object's fields a tabular view shows, in what order, and how it is sorted and paged before anyone touches it.
@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A table that gains a column every time the model does, including the ones nobody meant to show.")
def test_declare_presentation_layoutDataGrid():
@@ -497,6 +507,46 @@ def test_declare_systemsAndRoles_appService():
def test_declare_systemsAndRoles_buildImage():
"""metaobjects.declare.systemsAndRoles.buildImage"""
+# API grant — An API grant says which operations of an API, in any system, a role may call, and with which credential.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A caller whose access to another team's API is recorded only in that team's gateway configuration.")
+def test_declare_systemsAndRoles_grantApi():
+ """metaobjects.declare.systemsAndRoles.grantApi"""
+
+# Document grant — A document grant says what a role may do with a document store of its own system, optionally in one collection.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A reporting job with write access to the collection it only reads.")
+def test_declare_systemsAndRoles_grantDocument():
+ """metaobjects.declare.systemsAndRoles.grantDocument"""
+
+# Key-value grant — A key-value grant says what a role may do with a key-value resource of its own system, optionally under one key prefix.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A cache shared by two services, each free to overwrite the other's keys.")
+def test_declare_systemsAndRoles_grantKeyValue():
+ """metaobjects.declare.systemsAndRoles.grantKeyValue"""
+
+# Object-store grant — An object-store grant says what a role may do with an object store of its own system, optionally under one prefix.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A bucket every service can write to, found when one of them deleted another's uploads.")
+def test_declare_systemsAndRoles_grantObjectStore():
+ """metaobjects.declare.systemsAndRoles.grantObjectStore"""
+
+# Queue grant — A queue grant says whether a role sends to or receives from a queue of its own system.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A consumer that also publishes to its own queue, so a retry loop feeds itself.")
+def test_declare_systemsAndRoles_grantQueue():
+ """metaobjects.declare.systemsAndRoles.grantQueue"""
+
+# Database grant — A database grant says what a role may do in one schema of a relational resource of its own system, down to owning it or only reading it.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A service that can drop tables because its credentials were copied from the migration job.")
+def test_declare_systemsAndRoles_grantRdb():
+ """metaobjects.declare.systemsAndRoles.grantRdb"""
+
+# Search grant — A search grant says what a role may do with a search store of its own system, optionally in one index.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: An index rebuilt by a service nobody remembered had write access to it.")
+def test_declare_systemsAndRoles_grantSearch():
+ """metaobjects.declare.systemsAndRoles.grantSearch"""
+
+# Stream grant — A stream grant says whether a role writes to or reads from a stream of its own system, and naming another system's stream is refused.
+@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A service reading another team's stream directly, so a schema change there breaks it without warning.")
+def test_declare_systemsAndRoles_grantStream():
+ """metaobjects.declare.systemsAndRoles.grantStream"""
+
# Company — A company is the top of an ownership tree, so a system names who answers for it.
@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A system whose owner is a free-text team name nobody can check.")
def test_declare_systemsAndRoles_organizationCompany():
diff --git a/fixtures/requirement-harness/typescript/requirement-harness.test.ts b/fixtures/requirement-harness/typescript/requirement-harness.test.ts
index eb772c11dc..f5c2733810 100644
--- a/fixtures/requirement-harness/typescript/requirement-harness.test.ts
+++ b/fixtures/requirement-harness/typescript/requirement-harness.test.ts
@@ -1,6 +1,6 @@
// @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
//
-// One slot per authored promise in metaobjects/meta.requirements.yaml (143 of them).
+// One slot per authored promise in metaobjects/meta.requirements.yaml (153 of them).
// Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
// claim that nothing is verified — the conformance corpora already check many of
// these. To FILL one, move it into TypeScript's own suite and write the assertion the
@@ -312,6 +312,11 @@ test.skip("metaobjects.declare.persistenceMapping.indexLookup.expr", () => {
// unfilled slot — write an assertion that fails when: An index declaring both a field list and an expression, where half of it is quietly discarded and the index built is not the index described.
});
+// Document source — A document source places an object in a collection of a declared document store, and its resource must name a document store.
+test.skip("metaobjects.declare.persistenceMapping.sourceDocument", () => {
+ // unfilled slot — write an assertion that fails when: An object said to live in a document store whose name, on inspection, belongs to a queue.
+});
+
// Relational source — A relational source says where an object's data lives, in what kind of place, and in what role, without naming a database engine.
test.skip("metaobjects.declare.persistenceMapping.sourceRdb", () => {
// unfilled slot — write an assertion that fails when: A model that only reveals which engine it assumed when a migration fails against a different one.
@@ -337,6 +342,11 @@ test.skip("metaobjects.declare.persistenceMapping.sourceRdb.unmanaged", () => {
// unfilled slot — write an assertion that fails when: A hand-maintained view rewritten by a migration that assumed it owned it.
});
+// Search source — A search source places an object in an index of a declared search store, and its resource must name a search store.
+test.skip("metaobjects.declare.persistenceMapping.sourceSearch", () => {
+ // unfilled slot — write an assertion that fails when: A search index fed from an object whose model says nothing of the index, so it is missed in a rename.
+});
+
// Data grid — A data grid declares which of an object's fields a tabular view shows, in what order, and how it is sorted and paged before anyone touches it.
test.skip("metaobjects.declare.presentation.layoutDataGrid", () => {
// unfilled slot — write an assertion that fails when: A table that gains a column every time the model does, including the ones nobody meant to show.
@@ -497,6 +507,46 @@ test.skip("metaobjects.declare.systemsAndRoles.buildImage", () => {
// unfilled slot — write an assertion that fails when: An app with no recorded build, deployed from whichever image tag someone last pushed.
});
+// API grant — An API grant says which operations of an API, in any system, a role may call, and with which credential.
+test.skip("metaobjects.declare.systemsAndRoles.grantApi", () => {
+ // unfilled slot — write an assertion that fails when: A caller whose access to another team's API is recorded only in that team's gateway configuration.
+});
+
+// Document grant — A document grant says what a role may do with a document store of its own system, optionally in one collection.
+test.skip("metaobjects.declare.systemsAndRoles.grantDocument", () => {
+ // unfilled slot — write an assertion that fails when: A reporting job with write access to the collection it only reads.
+});
+
+// Key-value grant — A key-value grant says what a role may do with a key-value resource of its own system, optionally under one key prefix.
+test.skip("metaobjects.declare.systemsAndRoles.grantKeyValue", () => {
+ // unfilled slot — write an assertion that fails when: A cache shared by two services, each free to overwrite the other's keys.
+});
+
+// Object-store grant — An object-store grant says what a role may do with an object store of its own system, optionally under one prefix.
+test.skip("metaobjects.declare.systemsAndRoles.grantObjectStore", () => {
+ // unfilled slot — write an assertion that fails when: A bucket every service can write to, found when one of them deleted another's uploads.
+});
+
+// Queue grant — A queue grant says whether a role sends to or receives from a queue of its own system.
+test.skip("metaobjects.declare.systemsAndRoles.grantQueue", () => {
+ // unfilled slot — write an assertion that fails when: A consumer that also publishes to its own queue, so a retry loop feeds itself.
+});
+
+// Database grant — A database grant says what a role may do in one schema of a relational resource of its own system, down to owning it or only reading it.
+test.skip("metaobjects.declare.systemsAndRoles.grantRdb", () => {
+ // unfilled slot — write an assertion that fails when: A service that can drop tables because its credentials were copied from the migration job.
+});
+
+// Search grant — A search grant says what a role may do with a search store of its own system, optionally in one index.
+test.skip("metaobjects.declare.systemsAndRoles.grantSearch", () => {
+ // unfilled slot — write an assertion that fails when: An index rebuilt by a service nobody remembered had write access to it.
+});
+
+// Stream grant — A stream grant says whether a role writes to or reads from a stream of its own system, and naming another system's stream is refused.
+test.skip("metaobjects.declare.systemsAndRoles.grantStream", () => {
+ // unfilled slot — write an assertion that fails when: A service reading another team's stream directly, so a schema change there breaks it without warning.
+});
+
// Company — A company is the top of an ownership tree, so a system names who answers for it.
test.skip("metaobjects.declare.systemsAndRoles.organizationCompany", () => {
// unfilled slot — write an assertion that fails when: A system whose owner is a free-text team name nobody can check.
diff --git a/metaobjects/meta.requirements.yaml b/metaobjects/meta.requirements.yaml
index 6cd9e4f590..49a9767153 100644
--- a/metaobjects/meta.requirements.yaml
+++ b/metaobjects/meta.requirements.yaml
@@ -786,6 +786,24 @@ metadata.root:
match the projection naming it, with every
generated artifact still built from the
projection.
+ - requirement.functional:
+ name: sourceDocument
+ title: Document source
+ level: 4
+ status: live
+ statement: >-
+ A document source places an object in a collection of a declared document store, and its resource must name a document store.
+ counterexample: >-
+ An object said to live in a document store whose name, on inspection, belongs to a queue.
+ - requirement.functional:
+ name: sourceSearch
+ title: Search source
+ level: 4
+ status: live
+ statement: >-
+ A search source places an object in an index of a declared search store, and its resource must name a search store.
+ counterexample: >-
+ A search index fed from an object whose model says nothing of the index, so it is missed in a rename.
- requirement.functional:
name: identityPrimary
title: Primary key
@@ -1282,9 +1300,9 @@ metadata.root:
An inventory of services kept in a spreadsheet beside the code,
true on the day it was written.
description: >-
- Covers organizations, systems, apps, builds, resources and roles,
- and the references between them. Where each app is deployed and
- what it may do to a resource are separate concerns.
+ Covers organizations, systems, apps, builds, resources, roles and
+ what each role may do to a resource, and the references between
+ them. Where each app is deployed is a separate concern.
children:
- requirement.functional:
name: organizationCompany
@@ -1457,6 +1475,78 @@ metadata.root:
A token role is a credential held by an organization, recorded by where the secret lives rather than by its value.
counterexample: >-
A shared API token whose holder is unknown when it has to be rotated.
+ - requirement.functional:
+ name: grantRdb
+ title: Database grant
+ level: 4
+ status: live
+ statement: >-
+ A database grant says what a role may do in one schema of a relational resource of its own system, down to owning it or only reading it.
+ counterexample: >-
+ A service that can drop tables because its credentials were copied from the migration job.
+ - requirement.functional:
+ name: grantKeyValue
+ title: Key-value grant
+ level: 4
+ status: live
+ statement: >-
+ A key-value grant says what a role may do with a key-value resource of its own system, optionally under one key prefix.
+ counterexample: >-
+ A cache shared by two services, each free to overwrite the other's keys.
+ - requirement.functional:
+ name: grantObjectStore
+ title: Object-store grant
+ level: 4
+ status: live
+ statement: >-
+ An object-store grant says what a role may do with an object store of its own system, optionally under one prefix.
+ counterexample: >-
+ A bucket every service can write to, found when one of them deleted another's uploads.
+ - requirement.functional:
+ name: grantDocument
+ title: Document grant
+ level: 4
+ status: live
+ statement: >-
+ A document grant says what a role may do with a document store of its own system, optionally in one collection.
+ counterexample: >-
+ A reporting job with write access to the collection it only reads.
+ - requirement.functional:
+ name: grantSearch
+ title: Search grant
+ level: 4
+ status: live
+ statement: >-
+ A search grant says what a role may do with a search store of its own system, optionally in one index.
+ counterexample: >-
+ An index rebuilt by a service nobody remembered had write access to it.
+ - requirement.functional:
+ name: grantQueue
+ title: Queue grant
+ level: 4
+ status: live
+ statement: >-
+ A queue grant says whether a role sends to or receives from a queue of its own system.
+ counterexample: >-
+ A consumer that also publishes to its own queue, so a retry loop feeds itself.
+ - requirement.functional:
+ name: grantStream
+ title: Stream grant
+ level: 4
+ status: live
+ statement: >-
+ A stream grant says whether a role writes to or reads from a stream of its own system, and naming another system's stream is refused.
+ counterexample: >-
+ A service reading another team's stream directly, so a schema change there breaks it without warning.
+ - requirement.functional:
+ name: grantApi
+ title: API grant
+ level: 4
+ status: live
+ statement: >-
+ An API grant says which operations of an API, in any system, a role may call, and with which credential.
+ counterexample: >-
+ A caller whose access to another team's API is recorded only in that team's gateway configuration.
- requirement.functional:
name: businessRules
diff --git a/scripts/check-requirements-ledger.ts b/scripts/check-requirements-ledger.ts
index b31a529208..463535a3d3 100644
--- a/scripts/check-requirements-ledger.ts
+++ b/scripts/check-requirements-ledger.ts
@@ -48,7 +48,7 @@ const EXPECTED_WARNING = "WARN_REQUIREMENT_NOTHING_IMPLEMENTS";
* the neighbour — became `Number("metaobjects")`, i.e. NaN. Every comparison against
* NaN is unequal, so the gate failed reporting "expected NaN" and a remedy paragraph
* about updating the pin. */
-const DEFAULT_EXPECTED_WARNING_COUNT = 177;
+const DEFAULT_EXPECTED_WARNING_COUNT = 187;
function expectedWarnings(argv: readonly string[]): number {
const flag = argv.find((a) => a.startsWith("--expect-warnings="));
diff --git a/scripts/site/reference.test.ts b/scripts/site/reference.test.ts
index 37c7bfb1c2..a3f087436f 100644
--- a/scripts/site/reference.test.ts
+++ b/scripts/site/reference.test.ts
@@ -50,7 +50,7 @@ describe("renderReference", () => {
test("renders every metamodel markdown page", () => {
expect(existsSync(MD_DIR)).toBe(true);
const p = pages();
- expect(Object.keys(p).length).toBe(29);
+ expect(Object.keys(p).length).toBe(30);
expect(Object.keys(p)).toContain("index.html");
expect(Object.keys(p)).toContain("types/field.html");
});
@@ -153,7 +153,7 @@ describe("build-site-reference --check", () => {
test("a freshly rendered tree checks clean", () => {
const r = run("--check", "--out", rendered());
- expect(r.out).toContain("is fresh (29 page(s))");
+ expect(r.out).toContain("is fresh (30 page(s))");
expect(r.code).toBe(0);
});
diff --git a/server/csharp/MetaObjects.Codegen.Tests/MetamodelDocsTests.cs b/server/csharp/MetaObjects.Codegen.Tests/MetamodelDocsTests.cs
index e6e0680a73..f77198fd0d 100644
--- a/server/csharp/MetaObjects.Codegen.Tests/MetamodelDocsTests.cs
+++ b/server/csharp/MetaObjects.Codegen.Tests/MetamodelDocsTests.cs
@@ -65,7 +65,7 @@ public void Default_sub_directory_is_metamodel()
{
Entities = load.Root.Objects(), Root = load.Root, Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme" },
}).ToList();
- Assert.Equal(29, files.Count);
+ Assert.Equal(30, files.Count);
Assert.All(files, f => Assert.StartsWith("metamodel/", f.Path));
}
}
diff --git a/server/csharp/MetaObjects.Codegen/Templates/metamodel/provider-descriptions.json b/server/csharp/MetaObjects.Codegen/Templates/metamodel/provider-descriptions.json
index a4241a7a6a..94ffafc94e 100644
--- a/server/csharp/MetaObjects.Codegen/Templates/metamodel/provider-descriptions.json
+++ b/server/csharp/MetaObjects.Codegen/Templates/metamodel/provider-descriptions.json
@@ -6,7 +6,7 @@
"metaobjects-reporting": "Reporting (FR-044): object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first.",
"metaobjects-requirements": "Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by meta verify.",
"metaobjects-rules": "Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum).",
- "metaobjects-systems-core": "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource and role.",
+ "metaobjects-systems-core": "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource, role and grant, and the resource reference on source.rdb, source.document and source.search.",
"metaobjects-ui": "UI/query-surface domain — @filterable / @sortable / @sortableDefaultOrder field markers driving generated CRUD filter + sort allowlists (Project D).",
"metaobjects-ui-web": "Web presentation view attrs — @rows (view.textarea) and the view.image control attrs. Every port applies this provider and loads them strictly; only TypeScript acts on them so far.",
"metaobjects-view-expressions": "View expressions (rc.21): origin.function plus the projection @union / @unionAll / @grain / @grainOrdinal attributes."
diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs
index 1079b71ba5..892cb79ce8 100644
--- a/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs
+++ b/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs
@@ -100,17 +100,18 @@ void Type(string type, string subType)
}
///
- /// Only `grant.rdb`, on top of the shipped systems vocabulary: a shared-model build composes
- /// its provider over the default bundle, which already registers the system types.
+ /// Only `permit.rdb`, on top of the shipped systems vocabulary: a shared-model build composes
+ /// its provider over the default bundle, which already registers the system types (and the
+ /// shipped `grant.rdb`, whose code is built in; this one carries a provider's own code).
///
private const string GrantDefinition = """
{
"provider": "test-reference-facet-grant",
"extends": [
- { "type": "grant", "subType": "rdb", "children": [
+ { "type": "permit", "subType": "rdb", "children": [
{ "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "Test.",
"ref": { "targetType": "resource", "targetSubTypes": ["rdb"], "sameSystem": true,
- "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } }
+ "wrongSystemCode": "ERR_TEST_PERMIT_CROSSES_SYSTEM" } }
] }
]
}
@@ -124,12 +125,12 @@ private sealed class GrantProvider : IMetaDataTypeProvider
public void RegisterTypes(TypeRegistry registry)
{
registry.Register(new TypeDefinition(
- typeId: new TypeId("grant", "rdb"),
- description: "A test grant.",
+ typeId: new TypeId("permit", "rdb"),
+ description: "A test permit.",
childRules: [new ChildRule(TYPE_ATTR, CHILD_RULE_WILDCARD, CHILD_RULE_WILDCARD)],
factory: (typeId, name) => new SystemTestNode(typeId, name),
attributes: []));
- registry.Extend("role", "service", childRules: [new ChildRule("grant", CHILD_RULE_WILDCARD, CHILD_RULE_WILDCARD)]);
+ registry.Extend("role", "service", childRules: [new ChildRule("permit", CHILD_RULE_WILDCARD, CHILD_RULE_WILDCARD)]);
registry.ApplyProviderExtends(SpecMetamodelReader.FromJson(GrantDefinition), "test-reference-facet-grant");
}
}
@@ -276,20 +277,31 @@ public void The_reader_carries_a_facet_on_a_types_entry_attr()
// The attributes that carry a facet in the shipped definitions: core's four older
// references (spec/metamodel-definitions.md, "Existing references keep their codes"),
- // each naming its existing code, and the systems vocabulary's four (ADR-0070), each
+ // each naming its existing code, and the systems vocabulary's (ADR-0070), each
// written on every subtype that inherits it. Checked on the bundled registry below.
private static readonly string[] SystemsFacets =
[
- "app.base @runsAs role False ",
- "app.client @runsAs role False ",
- "app.job @runsAs role False ",
- "app.service @runsAs role False ",
- "role.base @memberOf role False ",
- "role.group @memberOf role False ",
- "role.service @memberOf role False ",
+ "app.base @runsAs role/service False sameSystem ERR_RUNSAS_OTHER_SYSTEM",
+ "app.client @runsAs role/service False sameSystem ERR_RUNSAS_OTHER_SYSTEM",
+ "app.job @runsAs role/service False sameSystem ERR_RUNSAS_OTHER_SYSTEM",
+ "app.service @runsAs role/service False sameSystem ERR_RUNSAS_OTHER_SYSTEM",
+ "grant.api @api api False ",
+ "grant.rdb @resource resource/rdb False sameSystem ERR_GRANT_CROSSES_SYSTEM",
+ "grant.keyValue @resource resource/keyValue False sameSystem ERR_GRANT_CROSSES_SYSTEM",
+ "grant.objectStore @resource resource/objectStore False sameSystem ERR_GRANT_CROSSES_SYSTEM",
+ "grant.document @resource resource/document False sameSystem ERR_GRANT_CROSSES_SYSTEM",
+ "grant.search @resource resource/search False sameSystem ERR_GRANT_CROSSES_SYSTEM",
+ "grant.queue @resource resource/queue False sameSystem ERR_GRANT_CROSSES_SYSTEM",
+ "grant.stream @resource resource/stream False sameSystem ERR_GRANT_CROSSES_SYSTEM",
+ "role.base @memberOf role/group False ",
+ "role.group @memberOf role/group False ",
+ "role.service @memberOf role/group False ",
"role.token @heldBy organization|system False ",
- "role.token @memberOf role False ",
- "role.user @memberOf role False ",
+ "role.token @memberOf role/group False ",
+ "role.user @memberOf role/group False ",
+ "source.document @resource resource/document False ",
+ "source.rdb @resource resource/rdb False ",
+ "source.search @resource resource/search False ",
"system.base @owner organization False ",
"system.software @owner organization False ",
];
@@ -315,11 +327,13 @@ public void The_core_definitions_declare_exactly_the_four_core_references()
foreach (var a in registry.AttrsOf(id.Type, id.SubType))
{
if (a.Ref is not { } f) continue;
- if (id.Type is "app" or "role" or "system")
+ if (id.Type is "app" or "role" or "system" or "grant" or "source")
{
- // The systems vocabulary: no sameSystem, no custom codes.
- Assert.False(f.SameSystem);
- found.Add($"{id.Type}.{id.SubType} @{a.Name} {string.Join("|", f.TargetTypes)} {f.FieldPath} {f.ErrorCode}");
+ // The systems vocabulary: the grants and @runsAs stay inside their system,
+ // each with its own wrong-system code; the other references do not.
+ found.Add($"{id.Type}.{id.SubType} @{a.Name} {string.Join("|", f.TargetTypes)}"
+ + $"{(f.TargetSubTypes is { } ts ? "/" + string.Join("|", ts) : "")} {f.FieldPath} {f.ErrorCode}"
+ + $"{(f.SameSystem ? " sameSystem " + f.WrongSystemCode : "")}");
continue;
}
Assert.Null(f.TargetSubTypes);
@@ -416,9 +430,8 @@ public void Crosses_system_raises_the_facet_wrongSystemCode()
- grant.rdb: { name: g3, resource: Ledger.books }
"""));
Assert.Equal(["ERR_GRANT_CROSSES_SYSTEM"], Codes(r));
- // A provider's own code is not a built-in member: Code is ERR_UNKNOWN, the spelling is kept.
- Assert.Equal(ErrorCode.ERR_UNKNOWN, r.Errors[0].Code);
- Assert.Equal("ERR_GRANT_CROSSES_SYSTEM", r.Errors[0].ProviderCode);
+ // The systems vocabulary's wrong-system code is a built-in member (ADR-0070).
+ Assert.Equal(ErrorCode.ERR_GRANT_CROSSES_SYSTEM, r.Errors[0].Code);
Assert.Contains("system \"acme::Ledger\"", r.Errors[0].Message);
}
@@ -430,13 +443,15 @@ public void A_shared_model_refusal_keeps_the_provider_code()
- role.service:
name: auditor
children:
- - grant.rdb: { name: g3, resource: Ledger.books }
- """));
+ - permit.rdb: { name: g3, resource: Ledger.books }
+ """)
+ // The default bundle ships grant.rdb, which requires @access.
+ .Replace("grant.rdb: { name: g1, resource: db }", "grant.rdb: { name: g1, resource: db, access: owner }"));
try
{
var ex = Assert.Throws(() => MetaObjects.Config.SharedModel.Build(
new MetaObjects.Config.SharedModelInput("acme", [file], Providers: [new GrantProvider()])));
- Assert.StartsWith("ERR_GRANT_CROSSES_SYSTEM: ", ex.Message);
+ Assert.StartsWith("ERR_TEST_PERMIT_CROSSES_SYSTEM: ", ex.Message);
}
finally
{
diff --git a/server/csharp/MetaObjects/Core/Systems/SystemsMetaDataProvider.cs b/server/csharp/MetaObjects/Core/Systems/SystemsMetaDataProvider.cs
index 59137b6df1..8d99e21f55 100644
--- a/server/csharp/MetaObjects/Core/Systems/SystemsMetaDataProvider.cs
+++ b/server/csharp/MetaObjects/Core/Systems/SystemsMetaDataProvider.cs
@@ -1,5 +1,5 @@
-// The metaobjects-systems-core pack (ADR-0070): organization, system, app, build, resource
-// and role. Its own provider, in the default bundle so every port loads it. The whole
+// The metaobjects-systems-core pack (ADR-0070): organization, system, app, build, resource,
+// role and grant, the document and search sources, and @resource on source.rdb. Its own provider, in the default bundle so every port loads it. The whole
// vocabulary is declared in the embedded systems.json (attrs, child cardinality, the
// reference facets on @owner / @runsAs / @memberOf / @heldBy, and the `extends` that admits
// organization.company and system.software under metadata.root); this provider only
@@ -30,7 +30,7 @@ public sealed class SystemsMetaDataProvider : IMetaDataTypeProvider
public string Id => ProviderId;
public string? Description =>
- "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource and role.";
+ "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource, role and grant, and the resource reference on source.rdb, source.document and source.search.";
public IReadOnlyList Dependencies => ["metaobjects-core-types"];
@@ -57,7 +57,11 @@ public void RegisterTypes(TypeRegistry registry)
typeId: new TypeId(type, subType),
description: $"{type}.{subType}",
childRules: rules,
- factory: (tid, n) => new MetaSystemsNode(tid, n),
+ // source.document and source.search are sources: MetaSource backs them, as
+ // it backs core's source subtypes.
+ factory: type == TYPE_SOURCE
+ ? (Func)((tid, n) => new MetaSource(tid, n))
+ : (tid, n) => new MetaSystemsNode(tid, n),
attributes: attrs));
}
diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs
index 98386e9f55..017e28f396 100644
--- a/server/csharp/MetaObjects/Errors.cs
+++ b/server/csharp/MetaObjects/Errors.cs
@@ -348,6 +348,10 @@ public enum ErrorCode
// names no node, and a value that names a node of the wrong type or subtype.
ERR_REF_UNRESOLVED,
ERR_REF_WRONG_KIND,
+ // ADR-0070 — the systems vocabulary's wrong-system codes: a grant on another system's
+ // resource, an app running as another system's role.
+ ERR_GRANT_CROSSES_SYSTEM,
+ ERR_RUNSAS_OTHER_SYSTEM,
}
///
diff --git a/server/csharp/MetaObjects/Parser.cs b/server/csharp/MetaObjects/Parser.cs
index b758846d0c..6b0b57a320 100644
--- a/server/csharp/MetaObjects/Parser.cs
+++ b/server/csharp/MetaObjects/Parser.cs
@@ -1125,6 +1125,21 @@ private static string FormatAttrForMsg(object? v)
return existing;
}
+ // Inside a system a name is used once per type (ADR-0070,
+ // spec/metamodel-definitions.md): a same-subtype redeclaration merges, but a sibling
+ // of another subtype with the same name would be merged into the first one silently.
+ // Outside a system (two fields of one name) the field lint reports it instead.
+ if (existing is not null && existing.SubType != subType && parent.Type == TYPE_SYSTEM)
+ {
+ st.Errors.Add(new MetaError(
+ $"{type}.{subType} \"{name}\" shares its name with {existing.Type}.{existing.SubType} \"{name}\" "
+ + "under the same parent: names are unique per type within one parent, so rename one of them.",
+ ErrorCode.ERR_DUPLICATE_NAME,
+ st.Source,
+ Envelope: st.CurrentSource()));
+ return null;
+ }
+
// Default: no operator → silently reuse existing or create new.
if (existing is not null)
{
diff --git a/server/csharp/MetaObjects/Persistence/Source/SourceConstants.cs b/server/csharp/MetaObjects/Persistence/Source/SourceConstants.cs
index 8b2e71c993..8b3c3c9369 100644
--- a/server/csharp/MetaObjects/Persistence/Source/SourceConstants.cs
+++ b/server/csharp/MetaObjects/Persistence/Source/SourceConstants.cs
@@ -25,6 +25,16 @@ public static class SourceConstants
/// Relational-database paradigm subtype.
public const string SOURCE_SUBTYPE_RDB = "rdb";
+ ///
+ /// Document-store paradigm subtype (ADR-0007's document). Registered by the systems
+ /// provider (ADR-0070), not core, so it is not in .
+ ///
+ public const string SOURCE_SUBTYPE_DOCUMENT = "document";
+
+ /// Search-index paradigm subtype (ADR-0007's search). Registered by the systems provider.
+ public const string SOURCE_SUBTYPE_SEARCH = "search";
+
+ /// The source subtypes core registers.
public static readonly string[] SOURCE_SUBTYPES =
[
BaseTypes.SUBTYPE_BASE,
diff --git a/server/csharp/MetaObjects/Shared/BaseTypes.cs b/server/csharp/MetaObjects/Shared/BaseTypes.cs
index c6fd87db0d..bb29706468 100644
--- a/server/csharp/MetaObjects/Shared/BaseTypes.cs
+++ b/server/csharp/MetaObjects/Shared/BaseTypes.cs
@@ -66,6 +66,7 @@ public static class BaseTypes
public const string TYPE_BUILD = "build";
public const string TYPE_RESOURCE = "resource";
public const string TYPE_ROLE = "role";
+ public const string TYPE_GRANT = "grant";
public static readonly string[] BASE_TYPES =
[
@@ -96,6 +97,7 @@ public static class BaseTypes
TYPE_BUILD,
TYPE_RESOURCE,
TYPE_ROLE,
+ TYPE_GRANT,
];
// -----------------------------------------------------------------------
diff --git a/server/csharp/MetaObjects/SpecMetamodel/source.json b/server/csharp/MetaObjects/SpecMetamodel/source.json
index 5ea328a387..f985538d93 100644
--- a/server/csharp/MetaObjects/SpecMetamodel/source.json
+++ b/server/csharp/MetaObjects/SpecMetamodel/source.json
@@ -9,7 +9,7 @@
{
"type": "source",
"subType": "rdb",
- "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, not by core-types.",
+ "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, and @resource by the systems provider (metaobjects-systems-core), not by core-types.",
"whenToUse": "The entity is backed by a relational table or view. Set @table/@kind — the default persistence source for any entity.",
"rules": "ADR-0007: source declares where an object's data lives; rdb is the relational paradigm subtype. An object may declare multiple sources, distinguished by @role, with exactly ONE @role: \"primary\" per object (write-through CQRS: a writable table for writes plus a read-only view for reads). The physical name is the @table attr (or the @kind-matching alias), never the structural `name`. Read-only-ness is derived from @kind (table → writable; view / materializedView / storedProc / tableFunction → read-only). The pre-v2 dbTable / dbView subtypes are retired."
}
diff --git a/server/csharp/MetaObjects/SpecMetamodel/systems.json b/server/csharp/MetaObjects/SpecMetamodel/systems.json
index 8515c412d0..cb6b7da4ed 100644
--- a/server/csharp/MetaObjects/SpecMetamodel/systems.json
+++ b/server/csharp/MetaObjects/SpecMetamodel/systems.json
@@ -53,7 +53,7 @@
"subType": "base",
"description": "Abstract app base: the attributes every app.* shares. Not authored directly: an `app.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).",
"children": [
- { "type": "attr", "subType": "string", "name": "runsAs", "min": 0, "max": 1, "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "role", "targetSubTypes": ["service"] } },
+ { "type": "attr", "subType": "string", "name": "runsAs", "min": 0, "max": 1, "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system).", "ref": { "targetType": "role", "targetSubTypes": ["service"], "sameSystem": true, "wrongSystemCode": "ERR_RUNSAS_OTHER_SYSTEM" } },
{ "type": "build", "subType": "*", "name": "*", "min": 0, "max": 1, "description": "How the app's deployable is made. At most one, of any kind." }
]
},
@@ -185,7 +185,8 @@
"description": "Abstract role base: an identity that can act in its system. Not authored directly: a `role.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).",
"children": [
{ "type": "attr", "subType": "string", "name": "memberOf", "isArray": true, "min": 0, "max": 1, "description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "role", "targetSubTypes": ["group"] } },
- { "type": "attr", "subType": "string", "name": "credential", "min": 0, "max": 1, "description": "The name of an existing key this role adopts (`keys/ANTHROPIC_API_KEY`). Never a value. Written only for a key the model cannot create: a role's credential is otherwise implied, with a derived name." }
+ { "type": "attr", "subType": "string", "name": "credential", "min": 0, "max": 1, "description": "The name of an existing key this role adopts (`keys/ANTHROPIC_API_KEY`). Never a value. Written only for a key the model cannot create: a role's credential is otherwise implied, with a derived name." },
+ { "type": "grant", "subType": "*", "name": "*", "min": 0, "max": null, "description": "What the role may do: one grant per resource or API it uses." }
]
},
{
@@ -218,6 +219,135 @@
"children": [
{ "type": "attr", "subType": "string", "name": "heldBy", "min": 0, "max": 1, "description": "Who was handed the token: an organization or a system node, by name (`tidewell::Tidewell`, `tidewell::Feeds`). Optional. A name that resolves to nothing, or to an organization and a system that share it, is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": ["organization", "system"] } }
]
+ },
+ {
+ "type": "grant",
+ "subType": "base",
+ "description": "Abstract grant base: what a role may do to one resource of its own system, or to one API. A grant is a child of a role. Its kind is the kind of thing it is on, so a grant.rdb names a resource.rdb. Not authored directly: a `grant.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED)."
+ },
+ {
+ "type": "grant",
+ "subType": "rdb",
+ "extendsBase": true,
+ "description": "Access to a relational database of the role's own system (`resource.rdb`), optionally limited to one schema.",
+ "whenToUse": "A role that connects to the database: the app's service role, a reporting job, the role migrations run as (`access: owner`).",
+ "rules": "@resource names a resource.rdb of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The relational database this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a database of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["rdb"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The one schema the grant covers. Absent: every schema of the database." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["owner", "readWrite", "read"], "description": "owner: creates and changes the schema's tables (the role migrations run as). readWrite: reads and writes rows. read: reads rows." },
+ { "type": "attr", "subType": "boolean", "name": "maintain", "min": 0, "max": 1, "description": "The role may also refresh materialized views and run maintenance on the tables it covers (PostgreSQL's MAINTAIN privilege). Absent means it may not." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "keyValue",
+ "extendsBase": true,
+ "description": "Access to a key-value store of the role's own system (`resource.keyValue`), optionally limited to keys with one prefix.",
+ "whenToUse": "A role that reads or writes a cache or a key-value store.",
+ "rules": "@resource names a resource.keyValue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The key-value store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["keyValue"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "keyPrefix", "min": 0, "max": 1, "description": "The key prefix the grant covers. Absent: every key." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["readWrite", "read"], "description": "readWrite: reads and writes values. read: reads values." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "objectStore",
+ "extendsBase": true,
+ "description": "Access to an object store of the role's own system (`resource.objectStore`), optionally limited to objects under one prefix.",
+ "whenToUse": "A role that uploads, downloads or manages files and blobs.",
+ "rules": "@resource names a resource.objectStore of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The object store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["objectStore"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "prefix", "min": 0, "max": 1, "description": "The object key prefix the grant covers. Absent: every object." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["read", "write", "readWrite", "manage"], "description": "read: reads objects. write: writes objects and cannot read them. readWrite: both. manage: also deletes objects and changes the store's settings." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "document",
+ "extendsBase": true,
+ "description": "Access to a document store of the role's own system (`resource.document`), optionally limited to one collection.",
+ "whenToUse": "A role that reads or writes documents.",
+ "rules": "@resource names a resource.document of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The document store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["document"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "collection", "min": 0, "max": 1, "description": "The one collection the grant covers. Absent: every collection." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["readWrite", "read"], "description": "readWrite: reads and writes documents. read: reads documents." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "search",
+ "extendsBase": true,
+ "description": "Access to a search index of the role's own system (`resource.search`), optionally limited to one index.",
+ "whenToUse": "A role that queries an index or keeps it up to date.",
+ "rules": "@resource names a resource.search of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The search index this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; an index of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["search"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "index", "min": 0, "max": 1, "description": "The one index the grant covers. Absent: every index." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["read", "write", "manage"], "description": "read: queries. write: adds, changes and removes documents. manage: also creates and drops indexes." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "queue",
+ "extendsBase": true,
+ "description": "Access to a message queue of the role's own system (`resource.queue`).",
+ "whenToUse": "A role that sends work to a queue or takes work from it.",
+ "rules": "@resource names a resource.queue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The queue this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a queue of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["queue"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["publish", "consume"], "description": "publish: sends messages. consume: receives and acknowledges them." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "stream",
+ "extendsBase": true,
+ "description": "Access to a stream of the role's own system (`resource.stream`).",
+ "whenToUse": "A role that appends to a stream or reads it.",
+ "rules": "@resource names a resource.stream of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The stream this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a stream of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["stream"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["publish", "consume"], "description": "publish: appends messages. consume: reads them, in a consumer group of its own." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "api",
+ "extendsBase": true,
+ "description": "The role may call an API, in any system: this is how one system reaches another's data. The access it implies on whatever carries the API is derived, never written.",
+ "whenToUse": "A role whose app calls another system's API, or an outside party's token that consumes one of ours.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "api", "min": 1, "max": 1, "description": "The API, by name (`pkg::ShipmentApi`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } },
+ { "type": "attr", "subType": "string", "name": "operations", "isArray": true, "min": 0, "max": 1, "description": "The operations of the API the role may call, by name. Absent: all of them." },
+ { "type": "attr", "subType": "string", "name": "credential", "min": 0, "max": 1, "description": "The name of an existing key this grant uses (`keys/LARKSPUR_API_KEY`). Never a value. Written only for a key the model cannot create, such as one an outside party issued; otherwise the credential is implied, with a derived name." }
+ ]
+ },
+ {
+ "type": "source",
+ "subType": "document",
+ "extendsBase": true,
+ "description": "The document-store paradigm source (ADR-0007's `document`): the object's records are kept as documents in a collection, in the document store @resource names. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "whenToUse": "An object kept as documents in a document store.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "The document store, by name (`Parcels.docs`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a document store, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "resource", "targetSubTypes": ["document"] } },
+ { "type": "attr", "subType": "string", "name": "collection", "min": 0, "max": 1, "description": "The collection that holds the documents. Absent: derived from the object's name." }
+ ]
+ },
+ {
+ "type": "source",
+ "subType": "search",
+ "extendsBase": true,
+ "description": "The search-index paradigm source (ADR-0007's `search`): the object's records are kept in a search index, usually as a copy of data kept elsewhere. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "whenToUse": "An object searched by text and filters.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "The search index resource, by name (`Parcels.search`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a search index, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "resource", "targetSubTypes": ["search"] } },
+ { "type": "attr", "subType": "string", "name": "index", "min": 0, "max": 1, "description": "The index that holds the documents. Absent: derived from the object's name." }
+ ]
}
],
"extends": [
@@ -228,6 +358,13 @@
{ "type": "organization", "subType": "company", "name": "*", "min": 0, "max": null, "description": "An organization: a top-level, packaged node." },
{ "type": "system", "subType": "software", "name": "*", "min": 0, "max": null, "description": "A system: a top-level, packaged node." }
]
+ },
+ {
+ "type": "source",
+ "subType": "rdb",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "The relational database this source's table or view lives in: a `resource.rdb`, by name (`Parcels.db`, or `pkg::Parcels.db` from another package). Optional: a model that declares no systems names none. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a relational database, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "resource", "targetSubTypes": ["rdb"] } }
+ ]
}
]
}
diff --git a/server/java/codegen-base/src/main/resources/metaobjects/templates/metamodel/provider-descriptions.json b/server/java/codegen-base/src/main/resources/metaobjects/templates/metamodel/provider-descriptions.json
index a4241a7a6a..94ffafc94e 100644
--- a/server/java/codegen-base/src/main/resources/metaobjects/templates/metamodel/provider-descriptions.json
+++ b/server/java/codegen-base/src/main/resources/metaobjects/templates/metamodel/provider-descriptions.json
@@ -6,7 +6,7 @@
"metaobjects-reporting": "Reporting (FR-044): object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first.",
"metaobjects-requirements": "Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by meta verify.",
"metaobjects-rules": "Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum).",
- "metaobjects-systems-core": "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource and role.",
+ "metaobjects-systems-core": "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource, role and grant, and the resource reference on source.rdb, source.document and source.search.",
"metaobjects-ui": "UI/query-surface domain — @filterable / @sortable / @sortableDefaultOrder field markers driving generated CRUD filter + sort allowlists (Project D).",
"metaobjects-ui-web": "Web presentation view attrs — @rows (view.textarea) and the view.image control attrs. Every port applies this provider and loads them strictly; only TypeScript acts on them so far.",
"metaobjects-view-expressions": "View expressions (rc.21): origin.function plus the projection @union / @unionAll / @grain / @grainOrdinal attributes."
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 7ddc67af00..a215deee04 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java
@@ -346,6 +346,12 @@ public enum ErrorCode {
*/
ERR_REF_WRONG_KIND,
+ /** ADR-0070: a grant names a resource of another system than its role's. */
+ ERR_GRANT_CROSSES_SYSTEM,
+
+ /** ADR-0070: an app's {@code @runsAs} names a role of another system than its own. */
+ ERR_RUNSAS_OTHER_SYSTEM,
+
/** An object declares source nodes but none has role=primary. */
ERR_SOURCE_NO_PRIMARY,
diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/parser/BaseMetaDataParser.java b/server/java/metadata/src/main/java/com/metaobjects/loader/parser/BaseMetaDataParser.java
index 39674f3a2e..a5b119d44c 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/loader/parser/BaseMetaDataParser.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/loader/parser/BaseMetaDataParser.java
@@ -380,6 +380,20 @@ protected MetaData createOrOverlayMetaData( boolean isRoot,
// If not overlay, continue to create new metadata below
}
+ // ADR-0070: inside a system, a name is used once per type. A same-subtype
+ // redeclaration merges, but a sibling of another subtype with the same name would be
+ // folded into the first one silently. Outside a system (two fields of one name) the
+ // field lint reports it instead. Mirrors the TS parser's createOrFindMetaData.
+ if (md != null && !Boolean.TRUE.equals(isOverlay)
+ && com.metaobjects.systems.SystemsNode.TYPE_SYSTEM.equals(parent.getType())
+ && subTypeName != null && !subTypeName.equals(md.getSubType())) {
+ throw new MetaDataException(
+ typeName + "." + subTypeName + " \"" + name + "\" shares its name with "
+ + md.getType() + "." + md.getSubType() + " \"" + name + "\" under the same parent: "
+ + "names are unique per type within one parent, so rename one of them.",
+ ErrorCode.ERR_DUPLICATE_NAME);
+ }
+
// If this MetaData doesn't exist yet, then we need to create it
if (md == null) {
@@ -945,7 +959,9 @@ public static boolean isAutoNamingType(String typeName) {
|| MetaIdentity.TYPE_IDENTITY.equals(typeName)
|| MetaOrigin.TYPE_ORIGIN.equals(typeName)
// ADR-0030: a binding names no one; it is addressed through its operation.
- || com.metaobjects.api.ApiConstants.TYPE_BINDING.equals(typeName);
+ || com.metaobjects.api.ApiConstants.TYPE_BINDING.equals(typeName)
+ // ADR-0070: a grant names no one either; it is addressed through its resource.
+ || com.metaobjects.systems.SystemsNode.TYPE_GRANT.equals(typeName);
}
diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java
index 57a05e844e..c0a40af7f4 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/loader/validation/RegisteredValidation.java
@@ -41,7 +41,7 @@ private RegisteredValidation() {}
* reference facet's {@code sameSystem} check reads it to find a node's system, its nearest
* ancestor of this type.
*/
- private static final String TYPE_SYSTEM = "system";
+ private static final String TYPE_SYSTEM = com.metaobjects.systems.SystemsNode.TYPE_SYSTEM;
/** Run validation derived from {@code registry} over the tree, COLLECTING all findings. */
public static List run(MetaRoot root, MetaDataRegistry registry) {
diff --git a/server/java/metadata/src/main/java/com/metaobjects/source/DocumentSource.java b/server/java/metadata/src/main/java/com/metaobjects/source/DocumentSource.java
new file mode 100644
index 0000000000..f9bc6aa4fb
--- /dev/null
+++ b/server/java/metadata/src/main/java/com/metaobjects/source/DocumentSource.java
@@ -0,0 +1,30 @@
+package com.metaobjects.source;
+
+import com.metaobjects.attr.StringAttribute;
+import com.metaobjects.registry.MetaDataRegistry;
+
+/**
+ * Document-store source metadata ({@code source.document}), ADR-0007's {@code document} paradigm.
+ *
+ *
Registered by the systems provider ({@code metaobjects-systems-core}, ADR-0070), not
+ * core: {@code @resource} names the store, the second attr the store-side name. No generator
+ * writes from it yet.
+ */
+public class DocumentSource extends MetaSource {
+
+ /** Document-store source subtype constant. */
+ public static final String SUBTYPE_DOCUMENT = "document";
+
+ public DocumentSource(String name) {
+ super(SUBTYPE_DOCUMENT, name);
+ }
+
+ /** Register the concrete {@code source.document} subtype. */
+ public static void registerTypes(MetaDataRegistry registry) {
+ registry.registerType(DocumentSource.class, def -> def.type(TYPE_SOURCE).subType(SUBTYPE_DOCUMENT)
+ .description("Document-store source — records kept as documents in a collection")
+ .inheritsFrom(TYPE_SOURCE, SUBTYPE_BASE)
+ .optionalAttributeWithConstraints("resource").ofType(StringAttribute.SUBTYPE_STRING).asSingle()
+ .optionalAttributeWithConstraints("collection").ofType(StringAttribute.SUBTYPE_STRING).asSingle());
+ }
+}
diff --git a/server/java/metadata/src/main/java/com/metaobjects/source/SearchSource.java b/server/java/metadata/src/main/java/com/metaobjects/source/SearchSource.java
new file mode 100644
index 0000000000..87f992a417
--- /dev/null
+++ b/server/java/metadata/src/main/java/com/metaobjects/source/SearchSource.java
@@ -0,0 +1,30 @@
+package com.metaobjects.source;
+
+import com.metaobjects.attr.StringAttribute;
+import com.metaobjects.registry.MetaDataRegistry;
+
+/**
+ * Search-index source metadata ({@code source.search}), ADR-0007's {@code search} paradigm.
+ *
+ *
Registered by the systems provider ({@code metaobjects-systems-core}, ADR-0070), not
+ * core: {@code @resource} names the store, the second attr the store-side name. No generator
+ * writes from it yet.
+ */
+public class SearchSource extends MetaSource {
+
+ /** Search-index source subtype constant. */
+ public static final String SUBTYPE_SEARCH = "search";
+
+ public SearchSource(String name) {
+ super(SUBTYPE_SEARCH, name);
+ }
+
+ /** Register the concrete {@code source.search} subtype. */
+ public static void registerTypes(MetaDataRegistry registry) {
+ registry.registerType(SearchSource.class, def -> def.type(TYPE_SOURCE).subType(SUBTYPE_SEARCH)
+ .description("Search-index source — records kept in a search index")
+ .inheritsFrom(TYPE_SOURCE, SUBTYPE_BASE)
+ .optionalAttributeWithConstraints("resource").ofType(StringAttribute.SUBTYPE_STRING).asSingle()
+ .optionalAttributeWithConstraints("index").ofType(StringAttribute.SUBTYPE_STRING).asSingle());
+ }
+}
diff --git a/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsNode.java b/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsNode.java
index 6bcd2b27fc..d90c2bf27a 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsNode.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsNode.java
@@ -32,6 +32,12 @@ public class SystemsNode extends MetaData {
/** The type every resource kind shares. */
public static final String TYPE_RESOURCE = "resource";
+ /** The system type: inside one, a name is used once per type (ERR_DUPLICATE_NAME). */
+ public static final String TYPE_SYSTEM = "system";
+
+ /** The grant type: what a role may do on one resource or API. Unnamed, like a binding. */
+ public static final String TYPE_GRANT = "grant";
+
/** The concrete resource kinds; {@code resource.base} is abstract and never authored. */
public static final Set RESOURCE_KINDS = Set.of(
"rdb", "keyValue", "objectStore", "document", "search", "queue", "stream", "volume");
diff --git a/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsTypesMetaDataProvider.java
index cfbf3a12eb..7ff113668c 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsTypesMetaDataProvider.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/systems/SystemsTypesMetaDataProvider.java
@@ -91,6 +91,7 @@ public void registerTypes(MetaDataRegistry registry) {
base(registry, "role", d -> {
d.optionalAttributeWithConstraints("memberOf").ofType(StringAttribute.SUBTYPE_STRING).asArray();
str(d, "credential");
+ d.optionalChild("grant", "*", "*");
});
sub(registry, "role", "service", d -> { });
sub(registry, "role", "user", d -> { });
@@ -109,6 +110,54 @@ public void registerTypes(MetaDataRegistry registry) {
"Array constraint validation"));
}
+ // What a role may do: one grant per resource or API it uses. A grant on a resource
+ // names it in @resource; the reference facets (kind, same system) come from
+ // systems.json.
+ base(registry, "grant", d -> { });
+ sub(registry, "grant", "rdb", d -> {
+ required(d, "resource");
+ str(d, "schema");
+ access(d, "owner", "readWrite", "read");
+ bool(d, "maintain");
+ });
+ sub(registry, "grant", "keyValue", d -> {
+ required(d, "resource");
+ str(d, "keyPrefix");
+ access(d, "readWrite", "read");
+ });
+ sub(registry, "grant", "objectStore", d -> {
+ required(d, "resource");
+ str(d, "prefix");
+ access(d, "read", "write", "readWrite", "manage");
+ });
+ sub(registry, "grant", "document", d -> {
+ required(d, "resource");
+ str(d, "collection");
+ access(d, "readWrite", "read");
+ });
+ sub(registry, "grant", "search", d -> {
+ required(d, "resource");
+ str(d, "index");
+ access(d, "read", "write", "manage");
+ });
+ sub(registry, "grant", "queue", d -> {
+ required(d, "resource");
+ access(d, "publish", "consume");
+ });
+ sub(registry, "grant", "stream", d -> {
+ required(d, "resource");
+ access(d, "publish", "consume");
+ });
+ sub(registry, "grant", "api", d -> {
+ required(d, "api");
+ d.optionalAttributeWithConstraints("operations").ofType(StringAttribute.SUBTYPE_STRING).asArray();
+ str(d, "credential");
+ });
+
+ // The document and search sources (ADR-0007's paradigms): sources, backed by their
+ // MetaSource subclasses, registered here because they are systems vocabulary.
+ com.metaobjects.source.DocumentSource.registerTypes(registry);
+ com.metaobjects.source.SearchSource.registerTypes(registry);
registry.applyProviderExtends(SpecMetamodelReader.load(), LOGICAL_ID, Map.of());
}
@@ -116,6 +165,14 @@ private static void str(TypeDefinitionBuilder d, String name) {
d.optionalAttributeWithConstraints(name).ofType(StringAttribute.SUBTYPE_STRING).asSingle();
}
+ private static void required(TypeDefinitionBuilder d, String name) {
+ d.requiredAttributeWithConstraints(name).ofType(StringAttribute.SUBTYPE_STRING).asSingle();
+ }
+
+ private static void access(TypeDefinitionBuilder d, String... values) {
+ d.requiredAttributeWithConstraints("access").ofType(StringAttribute.SUBTYPE_STRING).withEnum(values);
+ }
+
private static void bool(TypeDefinitionBuilder d, String name) {
d.optionalAttributeWithConstraints(name).ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle();
}
@@ -151,6 +208,6 @@ public String[] getDependencies() {
@Override
public String getDescription() {
- return "Systems Types (organization, system, app, build, resource, role) — ADR-0070";
+ return "Systems Types (organization, system, app, build, resource, role, grant) — ADR-0070";
}
}
diff --git a/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java b/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java
index 4031c2d993..f2bdf4a0b2 100644
--- a/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java
+++ b/server/java/metadata/src/test/java/com/metaobjects/validation/ReferenceFacetTest.java
@@ -78,10 +78,10 @@ public SystemTestNode(String type, String subType, String name) {
{ "type": "attr", "subType": "string", "name": "uses", "min": 0, "max": 1, "description": "Test.",
"ref": { "targetType": ["role", "resource"] } }
] },
- { "type": "grant", "subType": "rdb", "children": [
+ { "type": "permit", "subType": "rdb", "children": [
{ "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "Test.",
"ref": { "targetType": "resource", "targetSubTypes": ["pg"], "sameSystem": true,
- "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } }
+ "wrongSystemCode": "ERR_TEST_PERMIT_CROSSES_SYSTEM" } }
] },
{ "type": "deployment", "subType": "test", "children": [
{ "type": "attr", "subType": "string", "name": "app", "min": 0, "max": 1, "description": "Test.",
@@ -106,8 +106,8 @@ public SystemTestNode(String type, String subType, String name) {
@Override public void registerTypes(MetaDataRegistry registry) {
type(registry, "system", "test", "app", "role", "resource");
type(registry, "app", "web");
- type(registry, "role", "agent", "grant", "resource");
- type(registry, "grant", "rdb");
+ type(registry, "role", "agent", "permit", "resource");
+ type(registry, "permit", "rdb");
type(registry, "resource", "pg");
type(registry, "resource", "mq");
type(registry, "deployment", "test");
@@ -183,7 +183,7 @@ private static String model(String parcelsExtra, String outside) {
- role.agent:
name: api
children:
- - grant.rdb: { name: g1, resource: db }
+ - permit.rdb: { name: g1, resource: db }
- app.web:
name: api
actsAs: api
@@ -235,7 +235,7 @@ private static Object value(MetaData node, String attr) {
@Test
public void theReaderLowersRefOntoTheAttributeRequirement() {
- ChildRequirement req = registry().getTypeDefinition("grant", "rdb").getChildRequirement("resource");
+ ChildRequirement req = registry().getTypeDefinition("permit", "rdb").getChildRequirement("resource");
ReferenceFacet ref = req.getRef();
assertNotNull(ref);
assertEquals(List.of("resource"), ref.targetTypes());
@@ -243,7 +243,7 @@ public void theReaderLowersRefOntoTheAttributeRequirement() {
assertTrue(ref.sameSystem());
assertFalse(ref.fieldPath());
assertNull(ref.errorCode());
- assertEquals("ERR_GRANT_CROSSES_SYSTEM", ref.wrongSystemCode());
+ assertEquals("ERR_TEST_PERMIT_CROSSES_SYSTEM", ref.wrongSystemCode());
}
private static String withRef(String reference, String subType) {
@@ -327,12 +327,16 @@ public void theReaderCarriesATargetTypeListAsWritten() {
* inherits it. They name a target subtype or a system boundary, which core's four do not. */
private static final List SYSTEMS_FACETS = List.of(
"app.base @runsAs", "app.client @runsAs", "app.job @runsAs", "app.service @runsAs",
+ "grant.api @api", "grant.document @resource", "grant.keyValue @resource",
+ "grant.objectStore @resource", "grant.queue @resource", "grant.rdb @resource",
+ "grant.search @resource", "grant.stream @resource",
"role.base @memberOf", "role.group @memberOf", "role.service @memberOf",
"role.token @heldBy", "role.token @memberOf", "role.user @memberOf",
+ "source.document @resource", "source.rdb @resource", "source.search @resource",
"system.base @owner", "system.software @owner");
private static final java.util.Set SYSTEMS_TYPES =
- java.util.Set.of("app", "build", "organization", "resource", "role", "system");
+ java.util.Set.of("app", "build", "grant", "organization", "resource", "role", "system");
@Test
public void theCoreDefinitionsDeclareExactlyTheFourCoreReferences() {
@@ -344,7 +348,9 @@ public void theCoreDefinitionsDeclareExactlyTheFourCoreReferences() {
for (ChildRequirement req : def.getChildRequirements()) {
ReferenceFacet f = req.getRef();
if (f == null) continue;
- if (SYSTEMS_TYPES.contains(id.type())) {
+ // The systems vocabulary, and the @resource it adds to the sources.
+ if (SYSTEMS_TYPES.contains(id.type())
+ || ("source".equals(id.type()) && "resource".equals(req.getName()))) {
systems.add(id.type() + "." + id.subType() + " @" + req.getName());
continue;
}
@@ -492,7 +498,7 @@ public void wrongSubtypeAGrantRdbNamingAResourceQueue() {
- role.agent:
name: mover
children:
- - grant.rdb: { name: g2, resource: jobs }
+ - permit.rdb: { name: g2, resource: jobs }
"""));
assertEquals(List.of("ERR_REF_WRONG_KIND"), codes(r));
assertTrue(message(r, 0), message(r, 0).contains("resource.mq"));
@@ -503,16 +509,16 @@ public void wrongSubtypeAGrantRdbNamingAResourceQueue() {
- role.agent:
name: auditor
children:
- - grant.rdb: { name: g3, resource: Ledger.books }
+ - permit.rdb: { name: g3, resource: Ledger.books }
""";
@Test
public void crossesSystemRaisesTheFacetWrongSystemCode() {
Result r = load(model(CROSSES));
- assertEquals(List.of("ERR_GRANT_CROSSES_SYSTEM"), codes(r));
+ assertEquals(List.of("ERR_TEST_PERMIT_CROSSES_SYSTEM"), codes(r));
// A provider's own code is not an ErrorCode member: getCode() is ERR_UNKNOWN, the spelling is kept.
assertEquals(ErrorCode.ERR_UNKNOWN, r.errors().get(0).getCode().orElseThrow());
- assertEquals("ERR_GRANT_CROSSES_SYSTEM", r.errors().get(0).getProviderCode().orElseThrow());
+ assertEquals("ERR_TEST_PERMIT_CROSSES_SYSTEM", r.errors().get(0).getProviderCode().orElseThrow());
assertTrue(message(r, 0), message(r, 0).contains("system \"acme::Ledger\""));
}
@@ -524,7 +530,7 @@ public void aSharedModelRefusalKeepsTheProviderCode() throws Exception {
Files.writeString(file, model(CROSSES));
MetaDataException ex = assertThrows(MetaDataException.class, () -> SharedModel.build(
new SharedModel.Input("acme", List.of(file), List.of(), List.of(), List.of(PROVIDER))));
- assertEquals("ERR_GRANT_CROSSES_SYSTEM", ex.getCodeName().orElseThrow());
+ assertEquals("ERR_TEST_PERMIT_CROSSES_SYSTEM", ex.getCodeName().orElseThrow());
} finally {
Files.deleteIfExists(file);
Files.deleteIfExists(dir);
@@ -681,7 +687,7 @@ public void aPathThroughASharedIntermediateNameKeepsTheValueAsWritten() {
name: api
children:
- resource.pg: { name: local }
- - grant.rdb: { name: g1, resource: local }
+ - permit.rdb: { name: g1, resource: local }
""",
new String[]{"Parcels", "role:api", "g1"}, "resource", new String[]{"Parcels", "role:api", "local"});
assertEquals("local", written);
@@ -978,12 +984,12 @@ private static JsonObject manifestAttr(JsonObject manifest, String type, String
@Test
public void theManifestWritesRefOnlyOnAnAttributeThatHasOneInTheFixedKeyOrder() {
JsonObject manifest = JsonParser.parseString(RegistryManifest.emit(registry())).getAsJsonObject();
- JsonObject resource = manifestAttr(manifest, "grant", "rdb", "resource");
+ JsonObject resource = manifestAttr(manifest, "permit", "rdb", "resource");
assertEquals(List.of("name", "valueType", "isArray", "required", "ref", "description"),
new ArrayList<>(resource.keySet()));
Gson gson = new Gson();
assertEquals(
- "{\"targetType\":\"resource\",\"targetSubTypes\":[\"pg\"],\"sameSystem\":true,\"wrongSystemCode\":\"ERR_GRANT_CROSSES_SYSTEM\"}",
+ "{\"targetType\":\"resource\",\"targetSubTypes\":[\"pg\"],\"sameSystem\":true,\"wrongSystemCode\":\"ERR_TEST_PERMIT_CROSSES_SYSTEM\"}",
gson.toJson(resource.get("ref")));
assertEquals("{\"targetType\":\"role\",\"errorCode\":\"ERR_TEST_ROLE\"}",
gson.toJson(manifestAttr(manifest, "deployment", "test", "anyRole").get("ref")));
diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py
index 03a588d10a..cad42d6229 100644
--- a/server/python/src/metaobjects/core_types.py
+++ b/server/python/src/metaobjects/core_types.py
@@ -724,7 +724,6 @@ def _register_subtypes(
child_rules=[ChildRule(TYPE_ATTR, "*")],
)
)
-
# origin.base — no schema (pass-through container)
core_provider.add(
TypeDefinition(
@@ -1049,7 +1048,7 @@ def _register_subtypes(
# Reporting (FR-044) and requirements are their own packs too, in the default bundle.
reporting_provider,
requirements_provider,
- # Systems (ADR-0070): organization, system, app, build, resource, role -- appended last.
+ # Systems (ADR-0070): organization, system, app, build, resource, role, grant -- appended last.
systems_provider,
]
diff --git a/server/python/src/metaobjects/errors.py b/server/python/src/metaobjects/errors.py
index fd84572115..a1dd75b7ad 100644
--- a/server/python/src/metaobjects/errors.py
+++ b/server/python/src/metaobjects/errors.py
@@ -291,6 +291,10 @@ class ErrorCode(str, Enum):
# 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"
+ # ADR-0070 — the systems vocabulary's wrong-system codes: a grant on another
+ # system's resource, an app running as another system's role.
+ ERR_GRANT_CROSSES_SYSTEM = "ERR_GRANT_CROSSES_SYSTEM"
+ ERR_RUNSAS_OTHER_SYSTEM = "ERR_RUNSAS_OTHER_SYSTEM"
# 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/python/src/metaobjects/loader/merge.py b/server/python/src/metaobjects/loader/merge.py
index 5717c33f3c..9ab28cfb34 100644
--- a/server/python/src/metaobjects/loader/merge.py
+++ b/server/python/src/metaobjects/loader/merge.py
@@ -35,6 +35,7 @@
from ..meta.core.field.field_constants import FIELD_ATTR_FLATTENED_COLUMN_PREFIX
from ..meta.meta_data import MetaData
from ..serializer_json import canonical_serialize
+from ..shared.base_types import TYPE_SYSTEM
from ..shared.separators import PACKAGE_SEP
from ..source import (
Contributor,
@@ -191,6 +192,22 @@ def _merge_child_into(
return
tc = _find_merge_match(target, sc)
+ if tc is not None and sc.name and tc.sub_type != sc.sub_type and target.type == TYPE_SYSTEM:
+ # Inside a system a name is used once per type (ADR-0070,
+ # spec/metamodel-definitions.md): a same-subtype redeclaration merges, one of
+ # another subtype is refused rather than folded into the first silently.
+ # Mirrors the TS parser.
+ errors.append(
+ MetaError(
+ f'{sc.type}.{sc.sub_type} "{sc.name}" shares its name with '
+ f'{tc.type}.{tc.sub_type} "{sc.name}" under the same parent: names are '
+ "unique per type within one parent, so rename one of them.",
+ ErrorCode.ERR_DUPLICATE_NAME,
+ path=sc.fqn(),
+ envelope=sc.source,
+ )
+ )
+ return
if tc is not None:
_merge_into(tc, sc, errors, warnings, envelope_warnings, pending)
else:
diff --git a/server/python/src/metaobjects/meta/core/systems/systems_provider.py b/server/python/src/metaobjects/meta/core/systems/systems_provider.py
index 9206071c14..53c0a20390 100644
--- a/server/python/src/metaobjects/meta/core/systems/systems_provider.py
+++ b/server/python/src/metaobjects/meta/core/systems/systems_provider.py
@@ -1,6 +1,7 @@
"""systems_provider -- the systems vocabulary (cross-port ``metaobjects-systems-core``).
-ADR-0070, new in 1.4.0: organizations, systems, apps, builds, resources and roles, read
+ADR-0070, new in 1.4.0: organizations, systems, apps, builds, resources, roles and the
+roles' grants, plus ``@resource`` on ``source.rdb``/``.document``/``.search``, read
from ``spec/metamodel/systems.json`` so the types, their attrs, their structural children
and their reference facets (``system @owner``, ``app @runsAs``, ``role @memberOf``,
``role.token @heldBy``) are single-sourced from the shared definition. The references are
@@ -13,7 +14,8 @@
from ....provider import Provider
from ....registry import ChildRule, TypeDefinition, TypeRegistry
-from ....shared.base_types import TYPE_ATTR
+from ....shared.base_types import TYPE_ATTR, TYPE_SOURCE
+from ...persistence.source.meta_source import MetaSource
from ....spec_metamodel import load_provider_types
from ...provider_extends import attr_schema_from_entry, register_extends
from .meta_systems_node import MetaSystemsNode
@@ -28,7 +30,9 @@
TypeDefinition(
type=_t.type,
sub_type=_t.sub_type,
- factory=MetaSystemsNode,
+ # source.document and source.search are sources: MetaSource backs them, as
+ # it backs core's source subtypes.
+ factory=MetaSource if _t.type == TYPE_SOURCE else MetaSystemsNode,
extends_base=_t.extends_base,
attrs=[attr_schema_from_entry(a) for a in _t.attrs],
# Structural children are re-derived from systems.json by the strict
diff --git a/server/python/src/metaobjects/meta/persistence/source/source_constants.py b/server/python/src/metaobjects/meta/persistence/source/source_constants.py
index 166990df4f..dfd4aa6de3 100644
--- a/server/python/src/metaobjects/meta/persistence/source/source_constants.py
+++ b/server/python/src/metaobjects/meta/persistence/source/source_constants.py
@@ -16,7 +16,12 @@
# --- Source v2 paradigm subtype --------------------------------------------
SOURCE_SUBTYPE_RDB = "rdb"
+# ADR-0007's document-store and search-index paradigms. Registered by the systems
+# provider (ADR-0070), not core, so they are not in SOURCE_SUBTYPES.
+SOURCE_SUBTYPE_DOCUMENT = "document"
+SOURCE_SUBTYPE_SEARCH = "search"
+# The source subtypes core registers.
SOURCE_SUBTYPES = (SUBTYPE_BASE, SOURCE_SUBTYPE_RDB)
# --- Per-kind physical-name aliases (FR-016 / ADR-0018) --------------------
diff --git a/server/python/src/metaobjects/parser.py b/server/python/src/metaobjects/parser.py
index 6e5e7aecfd..f586ae2e79 100644
--- a/server/python/src/metaobjects/parser.py
+++ b/server/python/src/metaobjects/parser.py
@@ -16,6 +16,7 @@
TYPE_FIELD,
TYPE_METADATA,
TYPE_OBJECT,
+ TYPE_SYSTEM,
)
from .shared.separators import ATTR_PREFIX, FUSED_KEY_SEP, PACKAGE_SEP
from .shared.structural import (
@@ -493,7 +494,16 @@ def _build(
yaml_position=child_yaml_pos,
)
if child is not None:
- node.add_child(child)
+ clash = _same_name_other_subtype(node, child)
+ if clash is not None:
+ result.errors.append(MetaError(
+ _duplicate_name_message(child, clash),
+ ErrorCode.ERR_DUPLICATE_NAME,
+ source,
+ envelope=_current_envelope(source, builder, child_yaml_pos),
+ ))
+ else:
+ node.add_child(child)
builder.pop()
builder.pop()
builder.pop()
@@ -501,6 +511,32 @@ def _build(
return node
+def _same_name_other_subtype(parent: MetaData, child: MetaData) -> MetaData | None:
+ """The sibling *child* clashes with: same type and name, another subtype.
+
+ Inside a system a name is used once per type (ADR-0070,
+ spec/metamodel-definitions.md). A same-subtype redeclaration merges; one of another
+ subtype would be folded into the first silently. Unnamed nodes never clash, and
+ outside a system the field lint reports a duplicate instead. Mirrors the TS parser's
+ createOrFindMetaData.
+ """
+ if not child.name or parent.type != TYPE_SYSTEM:
+ return None
+ # ADR-0039 sanctioned own: the siblings declared in this node, before any merge.
+ for sibling in parent.own_children():
+ if sibling.type == child.type and sibling.name == child.name and sibling.sub_type != child.sub_type:
+ return sibling
+ return None
+
+
+def _duplicate_name_message(child: MetaData, clash: MetaData) -> str:
+ return (
+ f'{child.type}.{child.sub_type} "{child.name}" shares its name with '
+ f'{clash.type}.{clash.sub_type} "{child.name}" under the same parent: names are '
+ "unique per type within one parent, so rename one of them."
+ )
+
+
def _parse_attr_child(
parent: MetaData,
wrapper: str,
diff --git a/server/python/src/metaobjects/render/bundled_templates/metamodel/provider-descriptions.json b/server/python/src/metaobjects/render/bundled_templates/metamodel/provider-descriptions.json
index a4241a7a6a..94ffafc94e 100644
--- a/server/python/src/metaobjects/render/bundled_templates/metamodel/provider-descriptions.json
+++ b/server/python/src/metaobjects/render/bundled_templates/metamodel/provider-descriptions.json
@@ -6,7 +6,7 @@
"metaobjects-reporting": "Reporting (FR-044): object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first.",
"metaobjects-requirements": "Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by meta verify.",
"metaobjects-rules": "Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum).",
- "metaobjects-systems-core": "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource and role.",
+ "metaobjects-systems-core": "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource, role and grant, and the resource reference on source.rdb, source.document and source.search.",
"metaobjects-ui": "UI/query-surface domain — @filterable / @sortable / @sortableDefaultOrder field markers driving generated CRUD filter + sort allowlists (Project D).",
"metaobjects-ui-web": "Web presentation view attrs — @rows (view.textarea) and the view.image control attrs. Every port applies this provider and loads them strictly; only TypeScript acts on them so far.",
"metaobjects-view-expressions": "View expressions (rc.21): origin.function plus the projection @union / @unionAll / @grain / @grainOrdinal attributes."
diff --git a/server/python/src/metaobjects/spec_metamodel/source.json b/server/python/src/metaobjects/spec_metamodel/source.json
index 5ea328a387..f985538d93 100644
--- a/server/python/src/metaobjects/spec_metamodel/source.json
+++ b/server/python/src/metaobjects/spec_metamodel/source.json
@@ -9,7 +9,7 @@
{
"type": "source",
"subType": "rdb",
- "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, not by core-types.",
+ "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, and @resource by the systems provider (metaobjects-systems-core), not by core-types.",
"whenToUse": "The entity is backed by a relational table or view. Set @table/@kind — the default persistence source for any entity.",
"rules": "ADR-0007: source declares where an object's data lives; rdb is the relational paradigm subtype. An object may declare multiple sources, distinguished by @role, with exactly ONE @role: \"primary\" per object (write-through CQRS: a writable table for writes plus a read-only view for reads). The physical name is the @table attr (or the @kind-matching alias), never the structural `name`. Read-only-ness is derived from @kind (table → writable; view / materializedView / storedProc / tableFunction → read-only). The pre-v2 dbTable / dbView subtypes are retired."
}
diff --git a/server/python/src/metaobjects/spec_metamodel/systems.json b/server/python/src/metaobjects/spec_metamodel/systems.json
index 8515c412d0..cb6b7da4ed 100644
--- a/server/python/src/metaobjects/spec_metamodel/systems.json
+++ b/server/python/src/metaobjects/spec_metamodel/systems.json
@@ -53,7 +53,7 @@
"subType": "base",
"description": "Abstract app base: the attributes every app.* shares. Not authored directly: an `app.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).",
"children": [
- { "type": "attr", "subType": "string", "name": "runsAs", "min": 0, "max": 1, "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "role", "targetSubTypes": ["service"] } },
+ { "type": "attr", "subType": "string", "name": "runsAs", "min": 0, "max": 1, "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system).", "ref": { "targetType": "role", "targetSubTypes": ["service"], "sameSystem": true, "wrongSystemCode": "ERR_RUNSAS_OTHER_SYSTEM" } },
{ "type": "build", "subType": "*", "name": "*", "min": 0, "max": 1, "description": "How the app's deployable is made. At most one, of any kind." }
]
},
@@ -185,7 +185,8 @@
"description": "Abstract role base: an identity that can act in its system. Not authored directly: a `role.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).",
"children": [
{ "type": "attr", "subType": "string", "name": "memberOf", "isArray": true, "min": 0, "max": 1, "description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "role", "targetSubTypes": ["group"] } },
- { "type": "attr", "subType": "string", "name": "credential", "min": 0, "max": 1, "description": "The name of an existing key this role adopts (`keys/ANTHROPIC_API_KEY`). Never a value. Written only for a key the model cannot create: a role's credential is otherwise implied, with a derived name." }
+ { "type": "attr", "subType": "string", "name": "credential", "min": 0, "max": 1, "description": "The name of an existing key this role adopts (`keys/ANTHROPIC_API_KEY`). Never a value. Written only for a key the model cannot create: a role's credential is otherwise implied, with a derived name." },
+ { "type": "grant", "subType": "*", "name": "*", "min": 0, "max": null, "description": "What the role may do: one grant per resource or API it uses." }
]
},
{
@@ -218,6 +219,135 @@
"children": [
{ "type": "attr", "subType": "string", "name": "heldBy", "min": 0, "max": 1, "description": "Who was handed the token: an organization or a system node, by name (`tidewell::Tidewell`, `tidewell::Feeds`). Optional. A name that resolves to nothing, or to an organization and a system that share it, is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": ["organization", "system"] } }
]
+ },
+ {
+ "type": "grant",
+ "subType": "base",
+ "description": "Abstract grant base: what a role may do to one resource of its own system, or to one API. A grant is a child of a role. Its kind is the kind of thing it is on, so a grant.rdb names a resource.rdb. Not authored directly: a `grant.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED)."
+ },
+ {
+ "type": "grant",
+ "subType": "rdb",
+ "extendsBase": true,
+ "description": "Access to a relational database of the role's own system (`resource.rdb`), optionally limited to one schema.",
+ "whenToUse": "A role that connects to the database: the app's service role, a reporting job, the role migrations run as (`access: owner`).",
+ "rules": "@resource names a resource.rdb of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The relational database this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a database of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["rdb"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The one schema the grant covers. Absent: every schema of the database." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["owner", "readWrite", "read"], "description": "owner: creates and changes the schema's tables (the role migrations run as). readWrite: reads and writes rows. read: reads rows." },
+ { "type": "attr", "subType": "boolean", "name": "maintain", "min": 0, "max": 1, "description": "The role may also refresh materialized views and run maintenance on the tables it covers (PostgreSQL's MAINTAIN privilege). Absent means it may not." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "keyValue",
+ "extendsBase": true,
+ "description": "Access to a key-value store of the role's own system (`resource.keyValue`), optionally limited to keys with one prefix.",
+ "whenToUse": "A role that reads or writes a cache or a key-value store.",
+ "rules": "@resource names a resource.keyValue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The key-value store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["keyValue"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "keyPrefix", "min": 0, "max": 1, "description": "The key prefix the grant covers. Absent: every key." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["readWrite", "read"], "description": "readWrite: reads and writes values. read: reads values." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "objectStore",
+ "extendsBase": true,
+ "description": "Access to an object store of the role's own system (`resource.objectStore`), optionally limited to objects under one prefix.",
+ "whenToUse": "A role that uploads, downloads or manages files and blobs.",
+ "rules": "@resource names a resource.objectStore of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The object store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["objectStore"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "prefix", "min": 0, "max": 1, "description": "The object key prefix the grant covers. Absent: every object." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["read", "write", "readWrite", "manage"], "description": "read: reads objects. write: writes objects and cannot read them. readWrite: both. manage: also deletes objects and changes the store's settings." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "document",
+ "extendsBase": true,
+ "description": "Access to a document store of the role's own system (`resource.document`), optionally limited to one collection.",
+ "whenToUse": "A role that reads or writes documents.",
+ "rules": "@resource names a resource.document of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The document store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["document"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "collection", "min": 0, "max": 1, "description": "The one collection the grant covers. Absent: every collection." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["readWrite", "read"], "description": "readWrite: reads and writes documents. read: reads documents." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "search",
+ "extendsBase": true,
+ "description": "Access to a search index of the role's own system (`resource.search`), optionally limited to one index.",
+ "whenToUse": "A role that queries an index or keeps it up to date.",
+ "rules": "@resource names a resource.search of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The search index this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; an index of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["search"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "index", "min": 0, "max": 1, "description": "The one index the grant covers. Absent: every index." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["read", "write", "manage"], "description": "read: queries. write: adds, changes and removes documents. manage: also creates and drops indexes." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "queue",
+ "extendsBase": true,
+ "description": "Access to a message queue of the role's own system (`resource.queue`).",
+ "whenToUse": "A role that sends work to a queue or takes work from it.",
+ "rules": "@resource names a resource.queue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The queue this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a queue of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["queue"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["publish", "consume"], "description": "publish: sends messages. consume: receives and acknowledges them." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "stream",
+ "extendsBase": true,
+ "description": "Access to a stream of the role's own system (`resource.stream`).",
+ "whenToUse": "A role that appends to a stream or reads it.",
+ "rules": "@resource names a resource.stream of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The stream this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a stream of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["stream"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["publish", "consume"], "description": "publish: appends messages. consume: reads them, in a consumer group of its own." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "api",
+ "extendsBase": true,
+ "description": "The role may call an API, in any system: this is how one system reaches another's data. The access it implies on whatever carries the API is derived, never written.",
+ "whenToUse": "A role whose app calls another system's API, or an outside party's token that consumes one of ours.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "api", "min": 1, "max": 1, "description": "The API, by name (`pkg::ShipmentApi`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } },
+ { "type": "attr", "subType": "string", "name": "operations", "isArray": true, "min": 0, "max": 1, "description": "The operations of the API the role may call, by name. Absent: all of them." },
+ { "type": "attr", "subType": "string", "name": "credential", "min": 0, "max": 1, "description": "The name of an existing key this grant uses (`keys/LARKSPUR_API_KEY`). Never a value. Written only for a key the model cannot create, such as one an outside party issued; otherwise the credential is implied, with a derived name." }
+ ]
+ },
+ {
+ "type": "source",
+ "subType": "document",
+ "extendsBase": true,
+ "description": "The document-store paradigm source (ADR-0007's `document`): the object's records are kept as documents in a collection, in the document store @resource names. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "whenToUse": "An object kept as documents in a document store.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "The document store, by name (`Parcels.docs`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a document store, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "resource", "targetSubTypes": ["document"] } },
+ { "type": "attr", "subType": "string", "name": "collection", "min": 0, "max": 1, "description": "The collection that holds the documents. Absent: derived from the object's name." }
+ ]
+ },
+ {
+ "type": "source",
+ "subType": "search",
+ "extendsBase": true,
+ "description": "The search-index paradigm source (ADR-0007's `search`): the object's records are kept in a search index, usually as a copy of data kept elsewhere. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "whenToUse": "An object searched by text and filters.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "The search index resource, by name (`Parcels.search`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a search index, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "resource", "targetSubTypes": ["search"] } },
+ { "type": "attr", "subType": "string", "name": "index", "min": 0, "max": 1, "description": "The index that holds the documents. Absent: derived from the object's name." }
+ ]
}
],
"extends": [
@@ -228,6 +358,13 @@
{ "type": "organization", "subType": "company", "name": "*", "min": 0, "max": null, "description": "An organization: a top-level, packaged node." },
{ "type": "system", "subType": "software", "name": "*", "min": 0, "max": null, "description": "A system: a top-level, packaged node." }
]
+ },
+ {
+ "type": "source",
+ "subType": "rdb",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "The relational database this source's table or view lives in: a `resource.rdb`, by name (`Parcels.db`, or `pkg::Parcels.db` from another package). Optional: a model that declares no systems names none. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a relational database, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "resource", "targetSubTypes": ["rdb"] } }
+ ]
}
]
}
diff --git a/server/python/tests/unit/test_reference_facet.py b/server/python/tests/unit/test_reference_facet.py
index d70fad697c..971407925e 100644
--- a/server/python/tests/unit/test_reference_facet.py
+++ b/server/python/tests/unit/test_reference_facet.py
@@ -94,6 +94,7 @@ def type_(t: str, sub: str, *children: str) -> None:
type_("system", "software", "app", "role", "resource")
type_("app", "service")
+ type_("app", "job") # an app subtype no facet lists
type_("role", "service", "grant", "resource")
type_("grant", "rdb")
type_("resource", "rdb")
@@ -382,16 +383,15 @@ def test_wrong_subtype_a_grant_rdb_naming_a_resource_queue() -> None:
def test_crosses_system_raises_the_facet_wrong_system_code() -> None:
r = _load(_model(_CROSSES))
assert _codes(r) == ["ERR_GRANT_CROSSES_SYSTEM"]
- # A provider's own code is not a built-in member: code is ERR_UNKNOWN, the spelling is kept.
- assert r.errors[0].code is ErrorCode.ERR_UNKNOWN
- assert r.errors[0].provider_code == "ERR_GRANT_CROSSES_SYSTEM"
+ # The systems vocabulary's wrong-system code is a built-in member (ADR-0070).
+ assert r.errors[0].code is ErrorCode.ERR_GRANT_CROSSES_SYSTEM
assert 'system "acme::Ledger"' in r.errors[0].message
def test_a_provider_code_is_named_in_the_error_repr() -> None:
- err = MetaError("x", ErrorCode.ERR_UNKNOWN, provider_code="ERR_GRANT_CROSSES_SYSTEM")
- assert err.code_name == "ERR_GRANT_CROSSES_SYSTEM"
- assert "ERR_GRANT_CROSSES_SYSTEM" in repr(err)
+ err = MetaError("x", ErrorCode.ERR_UNKNOWN, provider_code="ERR_TEST_ROLE")
+ assert err.code_name == "ERR_TEST_ROLE"
+ assert "ERR_TEST_ROLE" in repr(err)
assert MetaError("y", ErrorCode.ERR_REF_UNRESOLVED).code_name == "ERR_REF_UNRESOLVED"
@@ -782,24 +782,13 @@ def test_a_node_of_an_unlisted_type_is_the_wrong_kind_and_the_message_lists_ever
def test_target_sub_types_narrows_whichever_listed_type_the_value_resolves_to() -> None:
- _clean(
- _load(
- """
-metadata.root:
- package: acme
- children:
- - system.software:
- name: Ledger
- children:
- - role.service: { name: clerk }
- - resource.rdb: { name: books }
- - resource.queue: { name: jobs }
- - app.service: { name: web, uses: clerk }
- - app.service: { name: worker, uses: books }
- - app.service: { name: pump, uses: jobs }
-"""
- )
- )
+ # ``holder`` lists app and system, narrowed to service and software. An app.service
+ # passes; an app.job is a listed type with an unlisted subtype, so it is the wrong kind.
+ jobs = " - app.job: { name: Jobs }"
+ _clean(_load(_deploy("Feeds", jobs)))
+ r = _load(_deploy("Jobs", jobs))
+ assert _codes(r) == ["ERR_REF_WRONG_KIND"]
+ assert "not a system or an app of subtype software or service" in r.errors[0].message
def test_two_listed_types_sharing_the_name_at_the_top_level_are_ambiguous() -> None:
diff --git a/server/rust/metaobjects-codegen/templates/metamodel/provider-descriptions.json b/server/rust/metaobjects-codegen/templates/metamodel/provider-descriptions.json
index a4241a7a6a..94ffafc94e 100644
--- a/server/rust/metaobjects-codegen/templates/metamodel/provider-descriptions.json
+++ b/server/rust/metaobjects-codegen/templates/metamodel/provider-descriptions.json
@@ -6,7 +6,7 @@
"metaobjects-reporting": "Reporting (FR-044): object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first.",
"metaobjects-requirements": "Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by meta verify.",
"metaobjects-rules": "Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum).",
- "metaobjects-systems-core": "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource and role.",
+ "metaobjects-systems-core": "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource, role and grant, and the resource reference on source.rdb, source.document and source.search.",
"metaobjects-ui": "UI/query-surface domain — @filterable / @sortable / @sortableDefaultOrder field markers driving generated CRUD filter + sort allowlists (Project D).",
"metaobjects-ui-web": "Web presentation view attrs — @rows (view.textarea) and the view.image control attrs. Every port applies this provider and loads them strictly; only TypeScript acts on them so far.",
"metaobjects-view-expressions": "View expressions (rc.21): origin.function plus the projection @union / @unionAll / @grain / @grainOrdinal attributes."
diff --git a/server/rust/metaobjects/data/ERROR-CODES.json b/server/rust/metaobjects/data/ERROR-CODES.json
index cdf78765f9..2d644faa6e 100644
--- a/server/rust/metaobjects/data/ERROR-CODES.json
+++ b/server/rust/metaobjects/data/ERROR-CODES.json
@@ -8,7 +8,7 @@
"ERR_UNKNOWN_SUBTYPE": "A node uses a subType not valid for its type.",
"ERR_ABSTRACT_SUBTYPE_AUTHORED": "A document authors a `.base` node. Every registered `base` subtype is an abstract registry anchor that concrete subtypes inherit from — it has no runtime semantics and is never authored directly. Declare a concrete subtype instead.",
"ERR_MISSING_SUBTYPE": "A node omits subType and the type has no default subType.",
- "ERR_DUPLICATE_NAME": "Two sibling nodes share the same name.",
+ "ERR_DUPLICATE_NAME": "Two children of one system share a type and a name but not a subtype (a role.service and a role.user both named api). Inside a system a name is used once per type (ADR-0070); a same-subtype redeclaration still merges.",
"ERR_UNRESOLVED_SUPER": "An extends/super reference names a node that does not exist.",
"ERR_EXTENDS_TARGET_MISMATCH": "FR-024: a dotted extends ref resolved to a node whose type or subtype does not match the extending node (a field may only extend a field of the same subtype; an identity only an identity).",
"ERR_IDENTITY_NAME_REQUIRED": "FR-024: an identity.* node has no name. Identities are named, author-chosen (e.g. \"id\"), so the dotted by-name extends form can address them.",
@@ -66,6 +66,8 @@
"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, or names nodes of two of the facet's listed target types that share the name (ambiguous). 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 than every type in it, when it is a list), or a subtype outside its `targetSubTypes`. The default code when the facet names no `errorCode`.",
+ "ERR_GRANT_CROSSES_SYSTEM": "ADR-0070, call 9: a grant on a resource (grant.rdb, .keyValue, .objectStore, .document, .search, .queue, .stream) names a resource of another system than the role that holds it. Another system's data is reached through an API that system provides (grant.api). Raised by the reference facet's sameSystem check (spec/metamodel-definitions.md).",
+ "ERR_RUNSAS_OTHER_SYSTEM": "ADR-0070: an app's @runsAs names a service role of another system. An app acts only as a role of its own system. Raised by the reference facet's sameSystem check (spec/metamodel-definitions.md).",
"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/rust/metaobjects/data/metamodel/source.json b/server/rust/metaobjects/data/metamodel/source.json
index 5ea328a387..f985538d93 100644
--- a/server/rust/metaobjects/data/metamodel/source.json
+++ b/server/rust/metaobjects/data/metamodel/source.json
@@ -9,7 +9,7 @@
{
"type": "source",
"subType": "rdb",
- "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, not by core-types.",
+ "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, and @resource by the systems provider (metaobjects-systems-core), not by core-types.",
"whenToUse": "The entity is backed by a relational table or view. Set @table/@kind — the default persistence source for any entity.",
"rules": "ADR-0007: source declares where an object's data lives; rdb is the relational paradigm subtype. An object may declare multiple sources, distinguished by @role, with exactly ONE @role: \"primary\" per object (write-through CQRS: a writable table for writes plus a read-only view for reads). The physical name is the @table attr (or the @kind-matching alias), never the structural `name`. Read-only-ness is derived from @kind (table → writable; view / materializedView / storedProc / tableFunction → read-only). The pre-v2 dbTable / dbView subtypes are retired."
}
diff --git a/server/rust/metaobjects/data/metamodel/systems.json b/server/rust/metaobjects/data/metamodel/systems.json
index 8515c412d0..cb6b7da4ed 100644
--- a/server/rust/metaobjects/data/metamodel/systems.json
+++ b/server/rust/metaobjects/data/metamodel/systems.json
@@ -53,7 +53,7 @@
"subType": "base",
"description": "Abstract app base: the attributes every app.* shares. Not authored directly: an `app.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).",
"children": [
- { "type": "attr", "subType": "string", "name": "runsAs", "min": 0, "max": 1, "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "role", "targetSubTypes": ["service"] } },
+ { "type": "attr", "subType": "string", "name": "runsAs", "min": 0, "max": 1, "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system).", "ref": { "targetType": "role", "targetSubTypes": ["service"], "sameSystem": true, "wrongSystemCode": "ERR_RUNSAS_OTHER_SYSTEM" } },
{ "type": "build", "subType": "*", "name": "*", "min": 0, "max": 1, "description": "How the app's deployable is made. At most one, of any kind." }
]
},
@@ -185,7 +185,8 @@
"description": "Abstract role base: an identity that can act in its system. Not authored directly: a `role.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).",
"children": [
{ "type": "attr", "subType": "string", "name": "memberOf", "isArray": true, "min": 0, "max": 1, "description": "The groups this role belongs to: `role.group` nodes, by name. A bare name is a role of the same system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a group, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "role", "targetSubTypes": ["group"] } },
- { "type": "attr", "subType": "string", "name": "credential", "min": 0, "max": 1, "description": "The name of an existing key this role adopts (`keys/ANTHROPIC_API_KEY`). Never a value. Written only for a key the model cannot create: a role's credential is otherwise implied, with a derived name." }
+ { "type": "attr", "subType": "string", "name": "credential", "min": 0, "max": 1, "description": "The name of an existing key this role adopts (`keys/ANTHROPIC_API_KEY`). Never a value. Written only for a key the model cannot create: a role's credential is otherwise implied, with a derived name." },
+ { "type": "grant", "subType": "*", "name": "*", "min": 0, "max": null, "description": "What the role may do: one grant per resource or API it uses." }
]
},
{
@@ -218,6 +219,135 @@
"children": [
{ "type": "attr", "subType": "string", "name": "heldBy", "min": 0, "max": 1, "description": "Who was handed the token: an organization or a system node, by name (`tidewell::Tidewell`, `tidewell::Feeds`). Optional. A name that resolves to nothing, or to an organization and a system that share it, is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": ["organization", "system"] } }
]
+ },
+ {
+ "type": "grant",
+ "subType": "base",
+ "description": "Abstract grant base: what a role may do to one resource of its own system, or to one API. A grant is a child of a role. Its kind is the kind of thing it is on, so a grant.rdb names a resource.rdb. Not authored directly: a `grant.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED)."
+ },
+ {
+ "type": "grant",
+ "subType": "rdb",
+ "extendsBase": true,
+ "description": "Access to a relational database of the role's own system (`resource.rdb`), optionally limited to one schema.",
+ "whenToUse": "A role that connects to the database: the app's service role, a reporting job, the role migrations run as (`access: owner`).",
+ "rules": "@resource names a resource.rdb of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The relational database this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a database of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["rdb"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The one schema the grant covers. Absent: every schema of the database." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["owner", "readWrite", "read"], "description": "owner: creates and changes the schema's tables (the role migrations run as). readWrite: reads and writes rows. read: reads rows." },
+ { "type": "attr", "subType": "boolean", "name": "maintain", "min": 0, "max": 1, "description": "The role may also refresh materialized views and run maintenance on the tables it covers (PostgreSQL's MAINTAIN privilege). Absent means it may not." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "keyValue",
+ "extendsBase": true,
+ "description": "Access to a key-value store of the role's own system (`resource.keyValue`), optionally limited to keys with one prefix.",
+ "whenToUse": "A role that reads or writes a cache or a key-value store.",
+ "rules": "@resource names a resource.keyValue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The key-value store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["keyValue"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "keyPrefix", "min": 0, "max": 1, "description": "The key prefix the grant covers. Absent: every key." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["readWrite", "read"], "description": "readWrite: reads and writes values. read: reads values." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "objectStore",
+ "extendsBase": true,
+ "description": "Access to an object store of the role's own system (`resource.objectStore`), optionally limited to objects under one prefix.",
+ "whenToUse": "A role that uploads, downloads or manages files and blobs.",
+ "rules": "@resource names a resource.objectStore of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The object store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["objectStore"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "prefix", "min": 0, "max": 1, "description": "The object key prefix the grant covers. Absent: every object." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["read", "write", "readWrite", "manage"], "description": "read: reads objects. write: writes objects and cannot read them. readWrite: both. manage: also deletes objects and changes the store's settings." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "document",
+ "extendsBase": true,
+ "description": "Access to a document store of the role's own system (`resource.document`), optionally limited to one collection.",
+ "whenToUse": "A role that reads or writes documents.",
+ "rules": "@resource names a resource.document of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The document store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["document"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "collection", "min": 0, "max": 1, "description": "The one collection the grant covers. Absent: every collection." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["readWrite", "read"], "description": "readWrite: reads and writes documents. read: reads documents." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "search",
+ "extendsBase": true,
+ "description": "Access to a search index of the role's own system (`resource.search`), optionally limited to one index.",
+ "whenToUse": "A role that queries an index or keeps it up to date.",
+ "rules": "@resource names a resource.search of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The search index this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; an index of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["search"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "index", "min": 0, "max": 1, "description": "The one index the grant covers. Absent: every index." },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["read", "write", "manage"], "description": "read: queries. write: adds, changes and removes documents. manage: also creates and drops indexes." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "queue",
+ "extendsBase": true,
+ "description": "Access to a message queue of the role's own system (`resource.queue`).",
+ "whenToUse": "A role that sends work to a queue or takes work from it.",
+ "rules": "@resource names a resource.queue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The queue this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a queue of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["queue"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["publish", "consume"], "description": "publish: sends messages. consume: receives and acknowledges them." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "stream",
+ "extendsBase": true,
+ "description": "Access to a stream of the role's own system (`resource.stream`).",
+ "whenToUse": "A role that appends to a stream or reads it.",
+ "rules": "@resource names a resource.stream of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 1, "max": 1, "description": "The stream this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a stream of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).", "ref": { "targetType": "resource", "targetSubTypes": ["stream"], "sameSystem": true, "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } },
+ { "type": "attr", "subType": "string", "name": "access", "min": 1, "max": 1, "allowedValues": ["publish", "consume"], "description": "publish: appends messages. consume: reads them, in a consumer group of its own." }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "api",
+ "extendsBase": true,
+ "description": "The role may call an API, in any system: this is how one system reaches another's data. The access it implies on whatever carries the API is derived, never written.",
+ "whenToUse": "A role whose app calls another system's API, or an outside party's token that consumes one of ours.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "api", "min": 1, "max": 1, "description": "The API, by name (`pkg::ShipmentApi`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.", "ref": { "targetType": "api" } },
+ { "type": "attr", "subType": "string", "name": "operations", "isArray": true, "min": 0, "max": 1, "description": "The operations of the API the role may call, by name. Absent: all of them." },
+ { "type": "attr", "subType": "string", "name": "credential", "min": 0, "max": 1, "description": "The name of an existing key this grant uses (`keys/LARKSPUR_API_KEY`). Never a value. Written only for a key the model cannot create, such as one an outside party issued; otherwise the credential is implied, with a derived name." }
+ ]
+ },
+ {
+ "type": "source",
+ "subType": "document",
+ "extendsBase": true,
+ "description": "The document-store paradigm source (ADR-0007's `document`): the object's records are kept as documents in a collection, in the document store @resource names. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "whenToUse": "An object kept as documents in a document store.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "The document store, by name (`Parcels.docs`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a document store, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "resource", "targetSubTypes": ["document"] } },
+ { "type": "attr", "subType": "string", "name": "collection", "min": 0, "max": 1, "description": "The collection that holds the documents. Absent: derived from the object's name." }
+ ]
+ },
+ {
+ "type": "source",
+ "subType": "search",
+ "extendsBase": true,
+ "description": "The search-index paradigm source (ADR-0007's `search`): the object's records are kept in a search index, usually as a copy of data kept elsewhere. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "whenToUse": "An object searched by text and filters.",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "The search index resource, by name (`Parcels.search`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a search index, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "resource", "targetSubTypes": ["search"] } },
+ { "type": "attr", "subType": "string", "name": "index", "min": 0, "max": 1, "description": "The index that holds the documents. Absent: derived from the object's name." }
+ ]
}
],
"extends": [
@@ -228,6 +358,13 @@
{ "type": "organization", "subType": "company", "name": "*", "min": 0, "max": null, "description": "An organization: a top-level, packaged node." },
{ "type": "system", "subType": "software", "name": "*", "min": 0, "max": null, "description": "A system: a top-level, packaged node." }
]
+ },
+ {
+ "type": "source",
+ "subType": "rdb",
+ "children": [
+ { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "The relational database this source's table or view lives in: a `resource.rdb`, by name (`Parcels.db`, or `pkg::Parcels.db` from another package). Optional: a model that declares no systems names none. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a relational database, is ERR_REF_WRONG_KIND.", "ref": { "targetType": "resource", "targetSubTypes": ["rdb"] } }
+ ]
}
]
}
diff --git a/server/rust/metaobjects/src/errors.rs b/server/rust/metaobjects/src/errors.rs
index 3a22ddbe07..113f5d7c34 100644
--- a/server/rust/metaobjects/src/errors.rs
+++ b/server/rust/metaobjects/src/errors.rs
@@ -68,6 +68,12 @@ pub const ERR_REF_UNRESOLVED: &str = "ERR_REF_UNRESOLVED";
/// The reference facet's default code for a value that names a node of the wrong type
/// or subtype.
pub const ERR_REF_WRONG_KIND: &str = "ERR_REF_WRONG_KIND";
+/// ADR-0070: two children of one system share a type and a name but not a subtype.
+pub const ERR_DUPLICATE_NAME: &str = "ERR_DUPLICATE_NAME";
+/// ADR-0070: a grant names a resource of another system than its role's.
+pub const ERR_GRANT_CROSSES_SYSTEM: &str = "ERR_GRANT_CROSSES_SYSTEM";
+/// ADR-0070: an app's `@runsAs` names a role of another system than its own.
+pub const ERR_RUNSAS_OTHER_SYSTEM: &str = "ERR_RUNSAS_OTHER_SYSTEM";
/// The code reported for a failure that carries none (a programming error in a
/// provider definition, say).
@@ -114,6 +120,9 @@ pub const ALL_CODES: &[&str] = &[
ERR_REFERENCE_SOURCE_TEMPLATE,
ERR_REF_UNRESOLVED,
ERR_REF_WRONG_KIND,
+ ERR_DUPLICATE_NAME,
+ ERR_GRANT_CROSSES_SYSTEM,
+ ERR_RUNSAS_OTHER_SYSTEM,
ERR_UNKNOWN,
];
diff --git a/server/rust/metaobjects/src/loader.rs b/server/rust/metaobjects/src/loader.rs
index 126da5b2ee..0dae4a3b61 100644
--- a/server/rust/metaobjects/src/loader.rs
+++ b/server/rust/metaobjects/src/loader.rs
@@ -15,8 +15,8 @@ use std::path::{Path, PathBuf};
use serde_json::Value;
use crate::errors::{
- ERR_BAD_ATTR_VALUE, ERR_EXTENDS_TARGET_MISMATCH, ERR_MALFORMED_JSON, ERR_MERGE_CONFLICT,
- ERR_OVERLAY_NO_TARGET, ERR_UNKNOWN, ERR_UNKNOWN_SUBTYPE, ERR_UNKNOWN_TYPE,
+ ERR_BAD_ATTR_VALUE, ERR_DUPLICATE_NAME, ERR_EXTENDS_TARGET_MISMATCH, ERR_MALFORMED_JSON,
+ ERR_MERGE_CONFLICT, ERR_OVERLAY_NO_TARGET, ERR_UNKNOWN, ERR_UNKNOWN_SUBTYPE, ERR_UNKNOWN_TYPE,
ERR_UNRESOLVED_SUPER, MetaError, WARN_DUPLICATE_DECLARATION,
};
use crate::naming::{NamingCtx, NamingRegistry, PhysicalNaming};
@@ -424,6 +424,12 @@ fn merge_child_into(
None => apply_overlay(tree, target, sc, out),
};
}
+ if let Some(message) = crate::parser::duplicate_name_clash(tree, target, sc) {
+ let source = tree.node(sc).source.clone();
+ out.errors
+ .push(MetaError::at(ERR_DUPLICATE_NAME, message, source));
+ return false;
+ }
match find_merge_match(tree, target, sc) {
Some(tc) => merge_into(tree, tc, sc, out, pending),
None => {
diff --git a/server/rust/metaobjects/src/parser.rs b/server/rust/metaobjects/src/parser.rs
index a78d66698b..e3e903f945 100644
--- a/server/rust/metaobjects/src/parser.rs
+++ b/server/rust/metaobjects/src/parser.rs
@@ -9,7 +9,7 @@
use serde_json::{Map, Value};
use crate::errors::{
- ERR_ABSTRACT_SUBTYPE_AUTHORED, ERR_BAD_ATTR_VALUE, ERR_CHILD_NOT_OBJECT,
+ ERR_ABSTRACT_SUBTYPE_AUTHORED, ERR_BAD_ATTR_VALUE, ERR_CHILD_NOT_OBJECT, ERR_DUPLICATE_NAME,
ERR_MISSING_REQUIRED_ATTR, ERR_MISSING_SUBTYPE, ERR_RESERVED_ATTR, ERR_TOP_LEVEL_NOT_OBJECT,
ERR_UNKNOWN_SUBTYPE, ERR_UNKNOWN_TYPE, ERR_UNRESOLVED_SUPER, MetaError,
};
@@ -457,7 +457,11 @@ fn build(
is_root: false,
};
if let Some(child) = build(ctx, cw, cbody, &cpath, &child_scope) {
- add_or_merge_child(ctx.tree, id, child);
+ if let Some(message) = duplicate_name_clash(ctx.tree, id, child) {
+ ctx.error(ERR_DUPLICATE_NAME, message, &cpath);
+ } else {
+ add_or_merge_child(ctx.tree, id, child);
+ }
}
}
}
@@ -550,6 +554,32 @@ fn structural_bool(
}
}
+/// The type whose children use a name once per type (ADR-0070).
+pub(crate) const TYPE_SYSTEM: &str = "system";
+
+/// Inside a system a name is used once per type (ADR-0070, spec/metamodel-definitions.md):
+/// a same-subtype redeclaration merges, but a sibling of another subtype with the same
+/// name would be folded into the first one silently. Outside a system (two fields of one
+/// name) the field lint reports it instead. The message for the refusal, when `child`
+/// clashes with a sibling under `parent`. Mirrors the TS parser's createOrFindMetaData.
+pub(crate) fn duplicate_name_clash(tree: &Tree, parent: NodeId, child: NodeId) -> Option {
+ let c = tree.node(child);
+ if c.name.is_empty() || c.is_overlay || tree.node(parent).type_name != TYPE_SYSTEM {
+ return None;
+ }
+ // ADR-0039: own — the siblings declared under this parent, before super resolution.
+ let clash = tree.own_children(parent).iter().copied().find(|&s| {
+ let n = tree.node(s);
+ !n.is_overlay && n.type_name == c.type_name && n.name == c.name && n.sub_type != c.sub_type
+ })?;
+ let n = tree.node(clash);
+ Some(format!(
+ "{}.{} \"{}\" shares its name with {}.{} \"{}\" under the same parent: names are \
+ unique per type within one parent, so rename one of them.",
+ c.type_name, c.sub_type, c.name, n.type_name, n.sub_type, c.name
+ ))
+}
+
/// Add `child` under `parent`, or fold it into a same-type, same-name sibling the
/// same document already declared (every port merges those during the parse).
/// Unnamed nodes are always distinct, and overlays stay as written for the
diff --git a/server/rust/metaobjects/src/validate/refs_tests.rs b/server/rust/metaobjects/src/validate/refs_tests.rs
index d7e8f303cf..8654c678cf 100644
--- a/server/rust/metaobjects/src/validate/refs_tests.rs
+++ b/server/rust/metaobjects/src/validate/refs_tests.rs
@@ -33,10 +33,10 @@ fn definition() -> Value {
{ "type": "attr", "subType": "string", "name": "reads", "min": 0, "max": 1, "description": "Test.",
"ref": { "targetType": "resource", "fieldPath": true } }
] },
- { "type": "grant", "subType": "rdb", "children": [
+ { "type": "permit", "subType": "rdb", "children": [
{ "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "Test.",
"ref": { "targetType": "resource", "targetSubTypes": ["rdb"], "sameSystem": true,
- "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } }
+ "wrongSystemCode": "ERR_TEST_PERMIT_CROSSES_SYSTEM" } }
] },
{ "type": "deployment", "subType": "test", "children": [
{ "type": "attr", "subType": "string", "name": "app", "min": 0, "max": 1, "description": "Test.",
@@ -60,8 +60,8 @@ fn register_test_types(r: &mut TypeRegistry) -> Result<(), MetaError> {
let types: &[(&str, &str, &[&str])] = &[
("system", "software", &["app", "role", "resource"]),
("app", "service", &[]),
- ("role", "service", &["grant", "resource"]),
- ("grant", "rdb", &[]),
+ ("role", "service", &["permit", "resource"]),
+ ("permit", "rdb", &[]),
("resource", "rdb", &[]),
("resource", "queue", &[]),
("deployment", "test", &[]),
@@ -145,7 +145,7 @@ fn model(parcels_extra: &str, outside: &str) -> String {
- role.service:
name: api
children:
- - grant.rdb: {{ name: g1, resource: db }}
+ - permit.rdb: {{ name: g1, resource: db }}
- app.service:
name: api
runsAs: api
@@ -212,7 +212,7 @@ fn type_of(r: &LoadResult, id: Option) -> Option {
#[test]
fn the_reader_lowers_ref_onto_the_attribute_schema() {
let r = registry();
- let facet = facet_of(&r, "grant", "rdb", "resource").expect("a facet");
+ let facet = facet_of(&r, "permit", "rdb", "resource").expect("a facet");
assert_eq!(facet.target_types, ["resource"]);
assert_eq!(facet.target_sub_types, Some(vec!["rdb".to_string()]));
assert!(facet.same_system);
@@ -220,7 +220,7 @@ fn the_reader_lowers_ref_onto_the_attribute_schema() {
assert_eq!(facet.error_code, None);
assert_eq!(
facet.wrong_system_code.as_deref(),
- Some("ERR_GRANT_CROSSES_SYSTEM")
+ Some("ERR_TEST_PERMIT_CROSSES_SYSTEM")
);
}
@@ -508,12 +508,12 @@ fn wrong_kind_when_two_top_level_nodes_of_other_types_share_the_name() {
const MOVER: &str = " - role.service:
name: mover
children:
- - grant.rdb: { name: g2, resource: jobs }";
+ - permit.rdb: { name: g2, resource: jobs }";
const AUDITOR: &str = " - role.service:
name: auditor
children:
- - grant.rdb: { name: g3, resource: Ledger.books }";
+ - permit.rdb: { name: g3, resource: Ledger.books }";
#[test]
fn wrong_subtype_a_grant_rdb_naming_a_resource_queue() {
@@ -527,14 +527,18 @@ fn wrong_subtype_a_grant_rdb_naming_a_resource_queue() {
#[test]
fn crosses_system_raises_the_facet_wrong_system_code() {
let (_, r) = load(&model(AUDITOR, ""));
- assert_eq!(codes(&r), ["ERR_GRANT_CROSSES_SYSTEM"]);
+ assert_eq!(codes(&r), ["ERR_TEST_PERMIT_CROSSES_SYSTEM"]);
// A provider's own code is not one this crate knows: `code` is ERR_UNKNOWN, the
// spelling is kept, and the error prints under it.
let e = &r.errors[0];
assert_eq!(e.code, ERR_UNKNOWN);
- assert_eq!(e.provider_code.as_deref(), Some("ERR_GRANT_CROSSES_SYSTEM"));
+ assert_eq!(
+ e.provider_code.as_deref(),
+ Some("ERR_TEST_PERMIT_CROSSES_SYSTEM")
+ );
assert!(
- e.to_string().starts_with("ERR_GRANT_CROSSES_SYSTEM: "),
+ e.to_string()
+ .starts_with("ERR_TEST_PERMIT_CROSSES_SYSTEM: "),
"{e}"
);
assert!(
@@ -772,7 +776,7 @@ fn a_path_through_a_shared_intermediate_name_keeps_the_value_as_written() {
name: api
children:
- resource.rdb: { name: local }
- - grant.rdb: { name: g1, resource: local }
+ - permit.rdb: { name: g1, resource: local }
",
&["Parcels", "role:api", "g1"],
"resource",
@@ -947,7 +951,7 @@ fn manifest_attr(manifest: &Value, type_name: &str, sub_type: &str, name: &str)
#[test]
fn the_manifest_writes_ref_only_on_an_attribute_that_has_one_in_the_fixed_key_order() {
let manifest = build_manifest(®istry());
- let resource = manifest_attr(&manifest, "grant", "rdb", "resource");
+ let resource = manifest_attr(&manifest, "permit", "rdb", "resource");
let keys: Vec<&str> = resource
.as_object()
.unwrap()
@@ -967,7 +971,7 @@ fn the_manifest_writes_ref_only_on_an_attribute_that_has_one_in_the_fixed_key_or
);
assert_eq!(
resource["ref"].to_string(),
- r#"{"targetType":"resource","targetSubTypes":["rdb"],"sameSystem":true,"wrongSystemCode":"ERR_GRANT_CROSSES_SYSTEM"}"#
+ r#"{"targetType":"resource","targetSubTypes":["rdb"],"sameSystem":true,"wrongSystemCode":"ERR_TEST_PERMIT_CROSSES_SYSTEM"}"#
);
assert_eq!(
manifest_attr(&manifest, "deployment", "test", "anyRole")["ref"].to_string(),
diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json
index 1930e6185a..759fd63065 100644
--- a/server/rust/metaobjects/tests/conformance-expected-failures.json
+++ b/server/rust/metaobjects/tests/conformance-expected-failures.json
@@ -1,6 +1,6 @@
{
"language": "rust",
"notes": "The Rust port passes every fixture of the shared metamodel corpus, so the ledger is empty. The ledger may only shrink and is kept for the day a new fixture lands that Rust does not pass yet: list it here with the reason, and it leaves when the work that covers it lands. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.",
- "minPassing": 599,
+ "minPassing": 608,
"fixtures": []
}
diff --git a/server/typescript/packages/codegen-ts/templates/metamodel/provider-descriptions.json b/server/typescript/packages/codegen-ts/templates/metamodel/provider-descriptions.json
index a4241a7a6a..94ffafc94e 100644
--- a/server/typescript/packages/codegen-ts/templates/metamodel/provider-descriptions.json
+++ b/server/typescript/packages/codegen-ts/templates/metamodel/provider-descriptions.json
@@ -6,7 +6,7 @@
"metaobjects-reporting": "Reporting (FR-044): object.report, dimension / measure / segment on an entity, and @segment on origin.aggregate and origin.first.",
"metaobjects-requirements": "Requirements: requirement.functional and requirement.architectural, declared at the document root and checked by meta verify.",
"metaobjects-rules": "Business rules (ADR-0066, experimental): the declared API surface (api / operation / binding) and lifecycle moves (transition on a field.enum).",
- "metaobjects-systems-core": "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource and role.",
+ "metaobjects-systems-core": "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource, role and grant, and the resource reference on source.rdb, source.document and source.search.",
"metaobjects-ui": "UI/query-surface domain — @filterable / @sortable / @sortableDefaultOrder field markers driving generated CRUD filter + sort allowlists (Project D).",
"metaobjects-ui-web": "Web presentation view attrs — @rows (view.textarea) and the view.image control attrs. Every port applies this provider and loads them strictly; only TypeScript acts on them so far.",
"metaobjects-view-expressions": "View expressions (rc.21): origin.function plus the projection @union / @unionAll / @grain / @grainOrdinal attributes."
diff --git a/server/typescript/packages/metadata/src/core/systems/systems-constants.ts b/server/typescript/packages/metadata/src/core/systems/systems-constants.ts
index 1eddd686ba..97243bd83d 100644
--- a/server/typescript/packages/metadata/src/core/systems/systems-constants.ts
+++ b/server/typescript/packages/metadata/src/core/systems/systems-constants.ts
@@ -1,5 +1,5 @@
// Systems vocabulary constants (ADR-0070) — subtypes and attribute keys for
-// `organization.*`, `system.*`, `app.*`, `build.*`, `resource.*` and `role.*`.
+// `organization.*`, `system.*`, `app.*`, `build.*`, `resource.*`, `role.*` and `grant.*`.
//
// The type-name constants live in shared/base-types.ts beside every other base type
// and are re-exported here so a consumer has one import site.
@@ -7,13 +7,14 @@
import {
TYPE_APP,
TYPE_BUILD,
+ TYPE_GRANT,
TYPE_ORGANIZATION,
TYPE_RESOURCE,
TYPE_ROLE,
TYPE_SYSTEM,
} from "../../shared/base-types.js";
-export { TYPE_APP, TYPE_BUILD, TYPE_ORGANIZATION, TYPE_RESOURCE, TYPE_ROLE, TYPE_SYSTEM };
+export { TYPE_APP, TYPE_BUILD, TYPE_GRANT, TYPE_ORGANIZATION, TYPE_RESOURCE, TYPE_ROLE, TYPE_SYSTEM };
// ---------------------------------------------------------------------------
// Subtypes
@@ -66,6 +67,28 @@ export const ROLE_SUBTYPE_TOKEN = "token";
export const ROLE_SUBTYPES = [ROLE_SUBTYPE_SERVICE, ROLE_SUBTYPE_USER, ROLE_SUBTYPE_GROUP, ROLE_SUBTYPE_TOKEN] as const;
export type RoleSubType = (typeof ROLE_SUBTYPES)[number];
+/** A grant's kind is the kind of thing it is on (ADR-0070, call 7): one per resource kind
+ * that has access levels, and `api` for another system's API. */
+export const GRANT_SUBTYPE_RDB = "rdb";
+export const GRANT_SUBTYPE_KEY_VALUE = "keyValue";
+export const GRANT_SUBTYPE_OBJECT_STORE = "objectStore";
+export const GRANT_SUBTYPE_DOCUMENT = "document";
+export const GRANT_SUBTYPE_SEARCH = "search";
+export const GRANT_SUBTYPE_QUEUE = "queue";
+export const GRANT_SUBTYPE_STREAM = "stream";
+export const GRANT_SUBTYPE_API = "api";
+export const GRANT_SUBTYPES = [
+ GRANT_SUBTYPE_RDB,
+ GRANT_SUBTYPE_KEY_VALUE,
+ GRANT_SUBTYPE_OBJECT_STORE,
+ GRANT_SUBTYPE_DOCUMENT,
+ GRANT_SUBTYPE_SEARCH,
+ GRANT_SUBTYPE_QUEUE,
+ GRANT_SUBTYPE_STREAM,
+ GRANT_SUBTYPE_API,
+] as const;
+export type GrantSubType = (typeof GRANT_SUBTYPES)[number];
+
// ---------------------------------------------------------------------------
// Attributes
// ---------------------------------------------------------------------------
@@ -104,3 +127,25 @@ export const ROLE_ATTR_MEMBER_OF = "memberOf";
export const ROLE_ATTR_CREDENTIAL = "credential";
/** `role.token @heldBy` — an organization, by name. */
export const ROLE_ATTR_HELD_BY = "heldBy";
+/** `grant @resource` (every grant but `grant.api`) — a resource of the role's own system, by name. */
+export const GRANT_ATTR_RESOURCE = "resource";
+/** `grant @access` — the access level; each grant kind has its own closed list. */
+export const GRANT_ATTR_ACCESS = "access";
+/** `grant.rdb @schema` — the one schema the grant covers. */
+export const GRANT_ATTR_SCHEMA = "schema";
+/** `grant.rdb @maintain` — PostgreSQL's MAINTAIN privilege (refresh materialized views). */
+export const GRANT_ATTR_MAINTAIN = "maintain";
+/** `grant.keyValue @keyPrefix`. */
+export const GRANT_ATTR_KEY_PREFIX = "keyPrefix";
+/** `grant.objectStore @prefix`. */
+export const GRANT_ATTR_PREFIX = "prefix";
+/** `grant.document @collection`. */
+export const GRANT_ATTR_COLLECTION = "collection";
+/** `grant.search @index`. */
+export const GRANT_ATTR_INDEX = "index";
+/** `grant.api @api` — an API, by name. */
+export const GRANT_ATTR_API = "api";
+/** `grant.api @operations` — the API's operations the role may call; absent means all. */
+export const GRANT_ATTR_OPERATIONS = "operations";
+/** `grant.api @credential` — the name of an adopted key, never a value. */
+export const GRANT_ATTR_CREDENTIAL = "credential";
diff --git a/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts b/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts
index cbd37cda4e..bab4c24f86 100644
--- a/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts
+++ b/server/typescript/packages/metadata/src/core/systems/systems-definition.embedded.ts
@@ -112,12 +112,14 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = {
"name": "runsAs",
"min": 0,
"max": 1,
- "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND.",
+ "description": "The service role this app acts as: a `role.service`, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system).",
"ref": {
"targetType": "role",
"targetSubTypes": [
"service"
- ]
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_RUNSAS_OTHER_SYSTEM"
}
},
{
@@ -355,6 +357,14 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = {
"min": 0,
"max": 1,
"description": "The name of an existing key this role adopts (`keys/ANTHROPIC_API_KEY`). Never a value. Written only for a key the model cannot create: a role's credential is otherwise implied, with a derived name."
+ },
+ {
+ "type": "grant",
+ "subType": "*",
+ "name": "*",
+ "min": 0,
+ "max": null,
+ "description": "What the role may do: one grant per resource or API it uses."
}
]
},
@@ -401,6 +411,428 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = {
}
}
]
+ },
+ {
+ "type": "grant",
+ "subType": "base",
+ "description": "Abstract grant base: what a role may do to one resource of its own system, or to one API. A grant is a child of a role. Its kind is the kind of thing it is on, so a grant.rdb names a resource.rdb. Not authored directly: a `grant.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED)."
+ },
+ {
+ "type": "grant",
+ "subType": "rdb",
+ "extendsBase": true,
+ "description": "Access to a relational database of the role's own system (`resource.rdb`), optionally limited to one schema.",
+ "whenToUse": "A role that connects to the database: the app's service role, a reporting job, the role migrations run as (`access: owner`).",
+ "rules": "@resource names a resource.rdb of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "resource",
+ "min": 1,
+ "max": 1,
+ "description": "The relational database this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a database of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).",
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "rdb"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ }
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "schema",
+ "min": 0,
+ "max": 1,
+ "description": "The one schema the grant covers. Absent: every schema of the database."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "access",
+ "min": 1,
+ "max": 1,
+ "allowedValues": [
+ "owner",
+ "readWrite",
+ "read"
+ ],
+ "description": "owner: creates and changes the schema's tables (the role migrations run as). readWrite: reads and writes rows. read: reads rows."
+ },
+ {
+ "type": "attr",
+ "subType": "boolean",
+ "name": "maintain",
+ "min": 0,
+ "max": 1,
+ "description": "The role may also refresh materialized views and run maintenance on the tables it covers (PostgreSQL's MAINTAIN privilege). Absent means it may not."
+ }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "keyValue",
+ "extendsBase": true,
+ "description": "Access to a key-value store of the role's own system (`resource.keyValue`), optionally limited to keys with one prefix.",
+ "whenToUse": "A role that reads or writes a cache or a key-value store.",
+ "rules": "@resource names a resource.keyValue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "resource",
+ "min": 1,
+ "max": 1,
+ "description": "The key-value store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).",
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "keyValue"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ }
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "keyPrefix",
+ "min": 0,
+ "max": 1,
+ "description": "The key prefix the grant covers. Absent: every key."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "access",
+ "min": 1,
+ "max": 1,
+ "allowedValues": [
+ "readWrite",
+ "read"
+ ],
+ "description": "readWrite: reads and writes values. read: reads values."
+ }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "objectStore",
+ "extendsBase": true,
+ "description": "Access to an object store of the role's own system (`resource.objectStore`), optionally limited to objects under one prefix.",
+ "whenToUse": "A role that uploads, downloads or manages files and blobs.",
+ "rules": "@resource names a resource.objectStore of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "resource",
+ "min": 1,
+ "max": 1,
+ "description": "The object store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).",
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "objectStore"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ }
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "prefix",
+ "min": 0,
+ "max": 1,
+ "description": "The object key prefix the grant covers. Absent: every object."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "access",
+ "min": 1,
+ "max": 1,
+ "allowedValues": [
+ "read",
+ "write",
+ "readWrite",
+ "manage"
+ ],
+ "description": "read: reads objects. write: writes objects and cannot read them. readWrite: both. manage: also deletes objects and changes the store's settings."
+ }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "document",
+ "extendsBase": true,
+ "description": "Access to a document store of the role's own system (`resource.document`), optionally limited to one collection.",
+ "whenToUse": "A role that reads or writes documents.",
+ "rules": "@resource names a resource.document of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "resource",
+ "min": 1,
+ "max": 1,
+ "description": "The document store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).",
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "document"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ }
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "collection",
+ "min": 0,
+ "max": 1,
+ "description": "The one collection the grant covers. Absent: every collection."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "access",
+ "min": 1,
+ "max": 1,
+ "allowedValues": [
+ "readWrite",
+ "read"
+ ],
+ "description": "readWrite: reads and writes documents. read: reads documents."
+ }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "search",
+ "extendsBase": true,
+ "description": "Access to a search index of the role's own system (`resource.search`), optionally limited to one index.",
+ "whenToUse": "A role that queries an index or keeps it up to date.",
+ "rules": "@resource names a resource.search of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "resource",
+ "min": 1,
+ "max": 1,
+ "description": "The search index this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; an index of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).",
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "search"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ }
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "index",
+ "min": 0,
+ "max": 1,
+ "description": "The one index the grant covers. Absent: every index."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "access",
+ "min": 1,
+ "max": 1,
+ "allowedValues": [
+ "read",
+ "write",
+ "manage"
+ ],
+ "description": "read: queries. write: adds, changes and removes documents. manage: also creates and drops indexes."
+ }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "queue",
+ "extendsBase": true,
+ "description": "Access to a message queue of the role's own system (`resource.queue`).",
+ "whenToUse": "A role that sends work to a queue or takes work from it.",
+ "rules": "@resource names a resource.queue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "resource",
+ "min": 1,
+ "max": 1,
+ "description": "The queue this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a queue of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).",
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "queue"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ }
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "access",
+ "min": 1,
+ "max": 1,
+ "allowedValues": [
+ "publish",
+ "consume"
+ ],
+ "description": "publish: sends messages. consume: receives and acknowledges them."
+ }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "stream",
+ "extendsBase": true,
+ "description": "Access to a stream of the role's own system (`resource.stream`).",
+ "whenToUse": "A role that appends to a stream or reads it.",
+ "rules": "@resource names a resource.stream of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "resource",
+ "min": 1,
+ "max": 1,
+ "description": "The stream this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a stream of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).",
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "stream"
+ ],
+ "sameSystem": true,
+ "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM"
+ }
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "access",
+ "min": 1,
+ "max": 1,
+ "allowedValues": [
+ "publish",
+ "consume"
+ ],
+ "description": "publish: appends messages. consume: reads them, in a consumer group of its own."
+ }
+ ]
+ },
+ {
+ "type": "grant",
+ "subType": "api",
+ "extendsBase": true,
+ "description": "The role may call an API, in any system: this is how one system reaches another's data. The access it implies on whatever carries the API is derived, never written.",
+ "whenToUse": "A role whose app calls another system's API, or an outside party's token that consumes one of ours.",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "api",
+ "min": 1,
+ "max": 1,
+ "description": "The API, by name (`pkg::ShipmentApi`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.",
+ "ref": {
+ "targetType": "api"
+ }
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "operations",
+ "isArray": true,
+ "min": 0,
+ "max": 1,
+ "description": "The operations of the API the role may call, by name. Absent: all of them."
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "credential",
+ "min": 0,
+ "max": 1,
+ "description": "The name of an existing key this grant uses (`keys/LARKSPUR_API_KEY`). Never a value. Written only for a key the model cannot create, such as one an outside party issued; otherwise the credential is implied, with a derived name."
+ }
+ ]
+ },
+ {
+ "type": "source",
+ "subType": "document",
+ "extendsBase": true,
+ "description": "The document-store paradigm source (ADR-0007's `document`): the object's records are kept as documents in a collection, in the document store @resource names. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "whenToUse": "An object kept as documents in a document store.",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "resource",
+ "min": 0,
+ "max": 1,
+ "description": "The document store, by name (`Parcels.docs`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a document store, is ERR_REF_WRONG_KIND.",
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "document"
+ ]
+ }
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "collection",
+ "min": 0,
+ "max": 1,
+ "description": "The collection that holds the documents. Absent: derived from the object's name."
+ }
+ ]
+ },
+ {
+ "type": "source",
+ "subType": "search",
+ "extendsBase": true,
+ "description": "The search-index paradigm source (ADR-0007's `search`): the object's records are kept in a search index, usually as a copy of data kept elsewhere. Registered by the systems provider, not by core-types. No generator writes from it yet.",
+ "whenToUse": "An object searched by text and filters.",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "resource",
+ "min": 0,
+ "max": 1,
+ "description": "The search index resource, by name (`Parcels.search`). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a search index, is ERR_REF_WRONG_KIND.",
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "search"
+ ]
+ }
+ },
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "index",
+ "min": 0,
+ "max": 1,
+ "description": "The index that holds the documents. Absent: derived from the object's name."
+ }
+ ]
}
],
"extends": [
@@ -425,6 +857,26 @@ export const SYSTEMS_DEFINITION: ProviderDefinition = {
"description": "A system: a top-level, packaged node."
}
]
+ },
+ {
+ "type": "source",
+ "subType": "rdb",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "string",
+ "name": "resource",
+ "min": 0,
+ "max": 1,
+ "description": "The relational database this source's table or view lives in: a `resource.rdb`, by name (`Parcels.db`, or `pkg::Parcels.db` from another package). Optional: a model that declares no systems names none. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a resource that is not a relational database, is ERR_REF_WRONG_KIND.",
+ "ref": {
+ "targetType": "resource",
+ "targetSubTypes": [
+ "rdb"
+ ]
+ }
+ }
+ ]
}
]
};
diff --git a/server/typescript/packages/metadata/src/core/systems/systems-provider.ts b/server/typescript/packages/metadata/src/core/systems/systems-provider.ts
index 77e674df7e..e6b230ccd9 100644
--- a/server/typescript/packages/metadata/src/core/systems/systems-provider.ts
+++ b/server/typescript/packages/metadata/src/core/systems/systems-provider.ts
@@ -1,5 +1,6 @@
// systemsCoreProvider — the systems vocabulary (ADR-0070, new in 1.4.0): organizations,
-// systems, apps, builds, resources and roles, from spec/metamodel/systems.json.
+// systems, apps, builds, resources, roles and their grants, the document and search
+// sources, and @resource on source.rdb, from spec/metamodel/systems.json.
//
// It is its OWN provider rather than part of metaobjects-core-types (GOVERNANCE.md,
// "Extension packs and the core metamodel"), and it is in the default bundle
@@ -11,6 +12,8 @@ import type { MetaDataTypeProvider } from "../../provider.js";
import type { TypeRegistry, TypeId } from "../../registry.js";
import { applyProviderDefinition, type FactoryMap } from "../../provider-data.js";
import { MetaSystemsNode } from "./meta-system-node.js";
+import { MetaSource } from "../../persistence/source/meta-source.js";
+import { TYPE_SOURCE } from "../../shared/base-types.js";
import { SYSTEMS_DEFINITION } from "./systems-definition.embedded.js";
/** The systems provider's id (a logical id, shared by every port). */
@@ -20,11 +23,16 @@ export const systemsCoreProvider: MetaDataTypeProvider = {
id: SYSTEMS_CORE_PROVIDER_ID,
dependencies: ["metaobjects-core-types"],
description:
- "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource and role.",
+ "Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource, role and grant, and the resource reference on source.rdb, source.document and source.search.",
registerTypes(registry: TypeRegistry): void {
const factories: FactoryMap = {};
for (const def of SYSTEMS_DEFINITION.types ?? []) {
- factories[`${def.type}.${def.subType}`] = (typeId: TypeId, name: string) => new MetaSystemsNode(typeId, name);
+ // source.document and source.search are sources: the one MetaSource class backs them,
+ // as it backs core's source subtypes.
+ factories[`${def.type}.${def.subType}`] =
+ def.type === TYPE_SOURCE
+ ? (typeId: TypeId, name: string) => new MetaSource(typeId, name)
+ : (typeId: TypeId, name: string) => new MetaSystemsNode(typeId, name);
}
applyProviderDefinition(registry, SYSTEMS_DEFINITION, factories);
},
diff --git a/server/typescript/packages/metadata/src/errors.ts b/server/typescript/packages/metadata/src/errors.ts
index 94b84b5d8e..f4a7ace37c 100644
--- a/server/typescript/packages/metadata/src/errors.ts
+++ b/server/typescript/packages/metadata/src/errors.ts
@@ -5,7 +5,6 @@ import type { ErrorSource, LoaderError, NodeContext } from "./source.js";
/** Stable, language-neutral error codes — mirrors fixtures/conformance/ERROR-CODES.json. */
// NOTE: The following codes are forward-declared (no emitting site in the current
// TS parser/loader — the condition is not yet detected):
-// - ERR_DUPLICATE_NAME: parser silently reuses existing same-name nodes (find-or-create).
// - ERR_INVALID_SUBTYPE_CHILD: no child-rule validation pass exists yet.
// Cross-language conformance consumers should not expect these codes from the TS adapter.
//
@@ -178,6 +177,10 @@ export const ERROR_CODES = [
// resolves to nothing, or to a node of the wrong type or subtype.
"ERR_REF_UNRESOLVED",
"ERR_REF_WRONG_KIND",
+ // ADR-0070 — the systems vocabulary's wrong-system codes (the facet's `wrongSystemCode`):
+ // a grant on another system's resource, an app running as another system's role.
+ "ERR_GRANT_CROSSES_SYSTEM",
+ "ERR_RUNSAS_OTHER_SYSTEM",
// Source v2 (ADR-0007) error codes — enforcement added during the source-v2 rollout.
"ERR_RESERVED_ATTR",
"ERR_SOURCE_NO_PRIMARY",
diff --git a/server/typescript/packages/metadata/src/parser-core.ts b/server/typescript/packages/metadata/src/parser-core.ts
index 8433f75521..fa14d1093c 100644
--- a/server/typescript/packages/metadata/src/parser-core.ts
+++ b/server/typescript/packages/metadata/src/parser-core.ts
@@ -47,6 +47,7 @@ import {
TYPE_ATTR,
TYPE_FIELD,
TYPE_OBJECT,
+ TYPE_SYSTEM,
TYPE_VALIDATOR,
SUBTYPE_BASE,
} from "./shared/base-types.js";
@@ -1246,6 +1247,22 @@ function createOrFindMetaData(
// its own target at application time, against the completed tree.
const existing = findOverlayTarget(parent, type, name, nodeData, inheritedContextPkg);
+ // Inside a system, a name is used once per TYPE (ADR-0070, spec/metamodel-definitions.md):
+ // a same-type, same-name sibling of ANOTHER subtype is a second node, not more of the
+ // first. Reusing it would silently fold, say, a `role.user api` into the
+ // `role.service api` beside it, so the second declaration is refused instead. Scoped
+ // to a system's children: elsewhere (two fields of one name) the field lint reports it.
+ if (existing !== undefined && existing.subType !== subType && parent.type === TYPE_SYSTEM) {
+ errors.push(
+ new ParseError(
+ `${type}.${subType} "${name}" shares its name with ${existing.type}.${existing.subType} "${name}" ` +
+ `under the same parent: names are unique per type within one parent, so rename one of them.`,
+ { code: "ERR_DUPLICATE_NAME", source: errSource() },
+ ),
+ );
+ return undefined;
+ }
+
// Default: no operator → silently reuse existing or create new.
if (existing !== undefined) {
parseNodeInto(nodeData, existing, accumRoot, inheritedContextPkg, registry, warnings, errors, strict, source, path);
diff --git a/server/typescript/packages/metadata/src/persistence/source/source-constants.ts b/server/typescript/packages/metadata/src/persistence/source/source-constants.ts
index 44317484d4..66b4e6fc4c 100644
--- a/server/typescript/packages/metadata/src/persistence/source/source-constants.ts
+++ b/server/typescript/packages/metadata/src/persistence/source/source-constants.ts
@@ -11,11 +11,16 @@ import { SUBTYPE_BASE } from "../../shared/base-types.js";
// --- Source v2 (ADR-0007): paradigm subtype "rdb"; physical name @table; @kind + @role. ---
export const SOURCE_SUBTYPE_RDB = "rdb";
-
-export const SOURCE_SUBTYPES = [
- SUBTYPE_BASE,
- SOURCE_SUBTYPE_RDB,
-] as const;
+/** ADR-0007's document paradigm (ADR-0070, 1.4.0): records kept as documents in a
+ * `resource.document`. Registered by the systems provider, not core (so it is not in
+ * SOURCE_SUBTYPES); no generator writes from it yet. */
+export const SOURCE_SUBTYPE_DOCUMENT = "document";
+/** ADR-0007's search paradigm (ADR-0070, 1.4.0): records kept in a `resource.search`.
+ * Registered by the systems provider, not core; no generator writes from it yet. */
+export const SOURCE_SUBTYPE_SEARCH = "search";
+
+/** The source subtypes core registers. */
+export const SOURCE_SUBTYPES = [SUBTYPE_BASE, SOURCE_SUBTYPE_RDB] as const;
export type SourceSubType = (typeof SOURCE_SUBTYPES)[number];
/** Optional DB schema attr on source.rdb. Postgres uses this to namespace
@@ -64,6 +69,14 @@ export const SOURCE_ATTR_ROLE = "role";
* new parameter.* node type. */
export const SOURCE_ATTR_PARAMETER_REF = "parameterRef";
+/** `source.rdb @resource` / `source.document @resource` / `source.search @resource`
+ * (ADR-0070, 1.4.0): the `resource.*` the data lives in, by name. A reference facet. */
+export const SOURCE_ATTR_RESOURCE = "resource";
+/** `source.document @collection`: the collection that holds the documents. */
+export const SOURCE_ATTR_COLLECTION = "collection";
+/** `source.search @index`: the index that holds the documents. */
+export const SOURCE_ATTR_INDEX = "index";
+
/** FR-024/#208 escape valve — a hand-written SQL body the tool REGISTERS +
* fingerprints + drift-checks but never authors or parses. Legal only on a
* read-only @kind (not "table"). Mutually exclusive with @unmanaged; forbids
diff --git a/server/typescript/packages/metadata/src/persistence/source/source-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/source/source-definition.embedded.ts
index d25c9d2b41..826403913e 100644
--- a/server/typescript/packages/metadata/src/persistence/source/source-definition.embedded.ts
+++ b/server/typescript/packages/metadata/src/persistence/source/source-definition.embedded.ts
@@ -17,7 +17,7 @@ export const SOURCE_DEFINITION: ProviderDefinition = {
{
"type": "source",
"subType": "rdb",
- "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, not by core-types.",
+ "description": "The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural `name`), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, and @resource by the systems provider (metaobjects-systems-core), not by core-types.",
"whenToUse": "The entity is backed by a relational table or view. Set @table/@kind — the default persistence source for any entity.",
"rules": "ADR-0007: source declares where an object's data lives; rdb is the relational paradigm subtype. An object may declare multiple sources, distinguished by @role, with exactly ONE @role: \"primary\" per object (write-through CQRS: a writable table for writes plus a read-only view for reads). The physical name is the @table attr (or the @kind-matching alias), never the structural `name`. Read-only-ness is derived from @kind (table → writable; view / materializedView / storedProc / tableFunction → read-only). The pre-v2 dbTable / dbView subtypes are retired."
}
diff --git a/server/typescript/packages/metadata/src/shared/base-types.ts b/server/typescript/packages/metadata/src/shared/base-types.ts
index 2dcd3027d7..e307f783ae 100644
--- a/server/typescript/packages/metadata/src/shared/base-types.ts
+++ b/server/typescript/packages/metadata/src/shared/base-types.ts
@@ -37,8 +37,8 @@ export const TYPE_BINDING = "binding";
export const TYPE_TRANSITION = "transition";
/**
* ADR-0070 — the systems vocabulary (provider `metaobjects-systems-core`, 1.4.0):
- * `organization.*`, `system.software`, `app.*`, `build.image`, `resource.*` and
- * `role.*`. The reference facet's `sameSystem` check reads `system` to find a node's
+ * `organization.*`, `system.software`, `app.*`, `build.image`, `resource.*`, `role.*`
+ * and `grant.*`. The reference facet's `sameSystem` check reads `system` to find a node's
* system, its nearest ancestor of that type.
*/
export const TYPE_ORGANIZATION = "organization";
@@ -47,6 +47,7 @@ export const TYPE_APP = "app";
export const TYPE_BUILD = "build";
export const TYPE_RESOURCE = "resource";
export const TYPE_ROLE = "role";
+export const TYPE_GRANT = "grant";
export const BASE_TYPES = [
TYPE_METADATA,
@@ -76,6 +77,7 @@ export const BASE_TYPES = [
TYPE_BUILD,
TYPE_RESOURCE,
TYPE_ROLE,
+ TYPE_GRANT,
] as const;
export type BaseType = (typeof BASE_TYPES)[number];
diff --git a/server/typescript/packages/metadata/test/definition-schema.test.ts b/server/typescript/packages/metadata/test/definition-schema.test.ts
index 98e6dd65f8..093ba1376d 100644
--- a/server/typescript/packages/metadata/test/definition-schema.test.ts
+++ b/server/typescript/packages/metadata/test/definition-schema.test.ts
@@ -62,10 +62,11 @@ describe("definition schema — the existing definition files", () => {
});
}
- test("the core definition files declare exactly the four core references with their existing codes, and the systems vocabulary's four", () => {
+ test("the core definition files declare exactly the four core references with their existing codes, and the systems vocabulary's", () => {
// spec/metamodel-definitions.md, "Existing references keep their codes": the four
// references core once declared in code live in the definition files. The systems
- // vocabulary (ADR-0070) adds four new references, which take the default codes.
+ // vocabulary (ADR-0070) adds new references, which take the default codes; the grants
+ // and @runsAs also stay inside their system, each with its own wrong-system code.
const found: string[] = [];
for (const file of definitionFiles) {
const doc = JSON.parse(readFileSync(join(specDir, file), "utf-8")) as {
@@ -89,7 +90,15 @@ describe("definition schema — the existing definition files", () => {
`relationship.association @objectRef ${relationship}`,
`relationship.base @objectRef ${relationship}`,
`relationship.composition @objectRef ${relationship}`,
- `app.base @runsAs ${JSON.stringify({ targetType: "role", targetSubTypes: ["service"] })}`,
+ `app.base @runsAs ${JSON.stringify({ targetType: "role", targetSubTypes: ["service"], sameSystem: true, wrongSystemCode: "ERR_RUNSAS_OTHER_SYSTEM" })}`,
+ ...["rdb", "keyValue", "objectStore", "document", "search", "queue", "stream"].map(
+ (kind) =>
+ `grant.${kind} @resource ${JSON.stringify({ targetType: "resource", targetSubTypes: [kind], sameSystem: true, wrongSystemCode: "ERR_GRANT_CROSSES_SYSTEM" })}`,
+ ),
+ `grant.api @api ${JSON.stringify({ targetType: "api" })}`,
+ `source.rdb @resource ${JSON.stringify({ targetType: "resource", targetSubTypes: ["rdb"] })}`,
+ `source.document @resource ${JSON.stringify({ targetType: "resource", targetSubTypes: ["document"] })}`,
+ `source.search @resource ${JSON.stringify({ targetType: "resource", targetSubTypes: ["search"] })}`,
`role.base @memberOf ${JSON.stringify({ targetType: "role", targetSubTypes: ["group"] })}`,
`role.token @heldBy ${JSON.stringify({ targetType: ["organization", "system"] })}`,
`system.base @owner ${JSON.stringify({ targetType: "organization" })}`,
diff --git a/server/typescript/packages/metadata/test/index.test.ts b/server/typescript/packages/metadata/test/index.test.ts
index b9bdefa3ee..5e3c955451 100644
--- a/server/typescript/packages/metadata/test/index.test.ts
+++ b/server/typescript/packages/metadata/test/index.test.ts
@@ -144,7 +144,7 @@ describe("Public API surface — @metaobjectsdev/metadata index", () => {
// The reporting and requirements packs own these; core alone has none.
if (t === "dimension" || t === "measure" || t === "segment" || t === "requirement") continue;
// The systems provider (metaobjects-systems-core) owns these; core alone has none.
- if (t === "organization" || t === "system" || t === "app" || t === "build" || t === "resource" || t === "role") continue;
+ if (t === "organization" || t === "system" || t === "app" || t === "build" || t === "resource" || t === "role" || t === "grant") continue;
const subs = registry.allSubTypesOf(t);
expect(subs.length).toBeGreaterThan(0);
}
@@ -319,7 +319,7 @@ describe("Public API surface — @metaobjectsdev/metadata index", () => {
});
test("BASE_TYPES array is exported and correct length", () => {
- expect(BASE_TYPES).toHaveLength(27);
+ expect(BASE_TYPES).toHaveLength(28);
expect(BASE_TYPES).toContain(TYPE_OBJECT);
expect(BASE_TYPES).toContain(TYPE_FIELD);
expect(BASE_TYPES).toContain(TYPE_LAYOUT);
diff --git a/server/typescript/packages/metadata/test/provider.test.ts b/server/typescript/packages/metadata/test/provider.test.ts
index 8aacb3554b..c6e9d65327 100644
--- a/server/typescript/packages/metadata/test/provider.test.ts
+++ b/server/typescript/packages/metadata/test/provider.test.ts
@@ -146,12 +146,13 @@ describe("coreTypesProvider", () => {
// requirements, systems).
const packTypes = [
"api", "operation", "binding", "transition", "dimension", "measure", "segment", "requirement",
- "organization", "system", "app", "build", "resource", "role",
+ "organization", "system", "app", "build", "resource", "role", "grant",
];
const coreOnly = viaProviders.allTypes().filter(
(t) =>
!packTypes.includes(t.type) &&
!(t.type === "origin" && t.subType === "function") &&
+ !(t.type === "source" && (t.subType === "document" || t.subType === "search")) &&
!(t.type === "object" && t.subType === "report"),
);
expect(viaWrapper.allTypes().length).toBe(coreOnly.length);
diff --git a/server/typescript/packages/metadata/test/reference-facet.test.ts b/server/typescript/packages/metadata/test/reference-facet.test.ts
index 97be2146e4..f3bb03fcd0 100644
--- a/server/typescript/packages/metadata/test/reference-facet.test.ts
+++ b/server/typescript/packages/metadata/test/reference-facet.test.ts
@@ -66,6 +66,7 @@ const DEFINITION: ProviderDefinition = {
attr("uses", { ref: { targetType: ["role", "resource"] } }),
],
},
+ { type: "app", subType: "job", description: "A test job: an app subtype no facet lists." },
{
type: "role",
subType: "service",
@@ -397,22 +398,13 @@ metadata.root:
});
it("targetSubTypes narrows whichever listed type the value resolves to", async () => {
- const yaml = `
-metadata.root:
- package: acme
- children:
- - system.software:
- name: Ledger
- children:
- - role.service: { name: clerk }
- - resource.rdb: { name: books }
- - resource.queue: { name: jobs }
- - app.service: { name: web, uses: clerk }
- - app.service: { name: worker, uses: books }
- - app.service: { name: pump, uses: jobs }
-`;
- const { errors } = await load(yaml);
- expect(errors).toEqual([]);
+ // `holder` lists app and system, narrowed to service and software. An app.service
+ // passes; an app.job is a listed type with an unlisted subtype, so it is the wrong kind.
+ const jobs = " - app.job: { name: Jobs }";
+ expect((await load(deploy("Feeds", jobs))).errors).toEqual([]);
+ const wrong = await load(deploy("Jobs", jobs));
+ expect(codes(wrong.errors)).toEqual(["ERR_REF_WRONG_KIND"]);
+ expect(wrong.errors[0]!.message).toContain("not a system or an app of subtype software or service");
});
it("two listed types sharing the name at the top level are ambiguous", async () => {
@@ -663,7 +655,7 @@ describe("reference facet — the registry manifest", () => {
t.attrs.filter((a) => a.ref !== undefined).map((a) => `${t.type}.${t.subType} @${a.name}`),
);
// The four core references (spec/metamodel-definitions.md) and the systems
- // vocabulary's four (ADR-0070), each written on every subtype that inherits it.
+ // vocabulary's (ADR-0070), each written on every subtype that inherits it.
expect(withRef.sort()).toEqual([
"app.base @runsAs",
"app.client @runsAs",
@@ -671,6 +663,14 @@ describe("reference facet — the registry manifest", () => {
"app.service @runsAs",
"field.map @objectRef",
"field.object @objectRef",
+ "grant.api @api",
+ "grant.document @resource",
+ "grant.keyValue @resource",
+ "grant.objectStore @resource",
+ "grant.queue @resource",
+ "grant.rdb @resource",
+ "grant.search @resource",
+ "grant.stream @resource",
"identity.reference @references",
"relationship.aggregation @objectRef",
"relationship.association @objectRef",
@@ -682,6 +682,9 @@ describe("reference facet — the registry manifest", () => {
"role.token @heldBy",
"role.token @memberOf",
"role.user @memberOf",
+ "source.document @resource",
+ "source.rdb @resource",
+ "source.search @resource",
"system.base @owner",
"system.software @owner",
]);
diff --git a/site-reference/index.html b/site-reference/index.html
index 3e709675bb..8ddf6d89df 100644
--- a/site-reference/index.html
+++ b/site-reference/index.html
@@ -271,6 +271,51 @@
The role may call an API, in any system: this is how one system reaches another's data. The access it implies on whatever carries the API is derived, never written.
Abstract grant base: what a role may do to one resource of its own system, or to one API. A grant is a child of a role. Its kind is the kind of thing it is on, so a grant.rdb names a resource.rdb. Not authored directly: a grant.base node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).
The document-store paradigm source (ADR-0007's document): the object's records are kept as documents in a collection, in the document store @resource names. Registered by the systems provider, not by core-types. No generator writes from it yet.
The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural name), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, not by core-types.
+
The relational-database paradigm source (ADR-0007): binds an object to a physical relational object. Its physical name is the @table attr (not the structural name), and read-only-ness is DERIVED from @kind — table is writable; view, materializedView, storedProc, and tableFunction are read-only. The @table/@kind/@role/@schema/@parameterRef attrs are contributed by the db domain provider, and @resource by the systems provider (metaobjects-systems-core), not by core-types.
The search-index paradigm source (ADR-0007's search): the object's records are kept in a search index, usually as a copy of data kept elsewhere. Registered by the systems provider, not by core-types. No generator writes from it yet.
Abstract system base: the attributes every system.* shares (ADR-0070, call 1). Not authored directly: a system.base node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).
Systems (ADR-0070): organization, system.software, app (service, client, job), build.image, resource, role and grant, and the resource reference on source.rdb, source.document and source.search.
The service role this app acts as: a role.service, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND.
+
The service role this app acts as: a role.service, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system).
Allowed children
@@ -104,7 +104,7 @@
app.client
metaobjects-systems-core
-
The service role this app acts as: a role.service, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND.
+
The service role this app acts as: a role.service, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system).
@shell
@@ -144,7 +144,7 @@
app.job
metaobjects-systems-core
-
The service role this app acts as: a role.service, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND.
+
The service role this app acts as: a role.service, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system).
@schedule
@@ -193,7 +193,7 @@
app.service
metaobjects-systems-core
-
The service role this app acts as: a role.service, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND.
+
The service role this app acts as: a role.service, by name. A bare name is a role of the app's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or a role that is not a service role, is ERR_REF_WRONG_KIND; a service role of another system is ERR_RUNSAS_OTHER_SYSTEM (an app acts only as a role of its own system).
Each section below is one grant.<subType>. The Attributes table lists
+the subtype's own + concern-contributed attributes (provider-tagged); universal
+documentation attributes are omitted here (see providers.md).
+Allowed children lists the structural child rules with their cardinality
+(min..max, * = unbounded).
+
grant.api
+
The role may call an API, in any system: this is how one system reaches another's data. The access it implies on whatever carries the API is derived, never written.
+
Owning provider: metaobjects-systems-core
+
When to use: A role whose app calls another system's API, or an outside party's token that consumes one of ours.
+
Attributes
+
+
+
+
Attribute
+
Type
+
Required
+
Default
+
Allowed values
+
Provider
+
Description
+
+
+
+
@api
+
string
+
yes
+
+
+
metaobjects-systems-core
+
The API, by name (pkg::ShipmentApi). A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node is ERR_REF_WRONG_KIND.
+
+
+
@credential
+
string
+
no
+
+
+
metaobjects-systems-core
+
The name of an existing key this grant uses (keys/LARKSPUR_API_KEY). Never a value. Written only for a key the model cannot create, such as one an outside party issued; otherwise the credential is implied, with a derived name.
+
+
+
@operations
+
string[]
+
no
+
+
+
metaobjects-systems-core
+
The operations of the API the role may call, by name. Absent: all of them.
+
+
+
Allowed children
+
No structural children.
+
grant.base
+
Abstract grant base: what a role may do to one resource of its own system, or to one API. A grant is a child of a role. Its kind is the kind of thing it is on, so a grant.rdb names a resource.rdb. Not authored directly: a grant.base node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).
+
Owning provider: metaobjects-systems-core
+
Attributes
+
No subtype-specific attributes.
+
Allowed children
+
No structural children.
+
grant.document
+
Access to a document store of the role's own system (resource.document), optionally limited to one collection.
+
Owning provider: metaobjects-systems-core
+
Rules: @resource names a resource.document of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
When to use: A role that reads or writes documents.
+
Attributes
+
+
+
+
Attribute
+
Type
+
Required
+
Default
+
Allowed values
+
Provider
+
Description
+
+
+
+
@access
+
string
+
yes
+
+
readWrite, read
+
metaobjects-systems-core
+
readWrite: reads and writes documents. read: reads documents.
+
+
+
@collection
+
string
+
no
+
+
+
metaobjects-systems-core
+
The one collection the grant covers. Absent: every collection.
+
+
+
@resource
+
string
+
yes
+
+
+
metaobjects-systems-core
+
The document store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).
+
+
+
Allowed children
+
No structural children.
+
grant.keyValue
+
Access to a key-value store of the role's own system (resource.keyValue), optionally limited to keys with one prefix.
+
Owning provider: metaobjects-systems-core
+
Rules: @resource names a resource.keyValue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
When to use: A role that reads or writes a cache or a key-value store.
+
Attributes
+
+
+
+
Attribute
+
Type
+
Required
+
Default
+
Allowed values
+
Provider
+
Description
+
+
+
+
@access
+
string
+
yes
+
+
readWrite, read
+
metaobjects-systems-core
+
readWrite: reads and writes values. read: reads values.
+
+
+
@keyPrefix
+
string
+
no
+
+
+
metaobjects-systems-core
+
The key prefix the grant covers. Absent: every key.
+
+
+
@resource
+
string
+
yes
+
+
+
metaobjects-systems-core
+
The key-value store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).
+
+
+
Allowed children
+
No structural children.
+
grant.objectStore
+
Access to an object store of the role's own system (resource.objectStore), optionally limited to objects under one prefix.
+
Owning provider: metaobjects-systems-core
+
Rules: @resource names a resource.objectStore of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
When to use: A role that uploads, downloads or manages files and blobs.
+
Attributes
+
+
+
+
Attribute
+
Type
+
Required
+
Default
+
Allowed values
+
Provider
+
Description
+
+
+
+
@access
+
string
+
yes
+
+
read, write, readWrite, manage
+
metaobjects-systems-core
+
read: reads objects. write: writes objects and cannot read them. readWrite: both. manage: also deletes objects and changes the store's settings.
+
+
+
@prefix
+
string
+
no
+
+
+
metaobjects-systems-core
+
The object key prefix the grant covers. Absent: every object.
+
+
+
@resource
+
string
+
yes
+
+
+
metaobjects-systems-core
+
The object store this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a store of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).
+
+
+
Allowed children
+
No structural children.
+
grant.queue
+
Access to a message queue of the role's own system (resource.queue).
+
Owning provider: metaobjects-systems-core
+
Rules: @resource names a resource.queue of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
When to use: A role that sends work to a queue or takes work from it.
+
Attributes
+
+
+
+
Attribute
+
Type
+
Required
+
Default
+
Allowed values
+
Provider
+
Description
+
+
+
+
@access
+
string
+
yes
+
+
publish, consume
+
metaobjects-systems-core
+
publish: sends messages. consume: receives and acknowledges them.
+
+
+
@resource
+
string
+
yes
+
+
+
metaobjects-systems-core
+
The queue this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a queue of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).
+
+
+
Allowed children
+
No structural children.
+
grant.rdb
+
Access to a relational database of the role's own system (resource.rdb), optionally limited to one schema.
+
Owning provider: metaobjects-systems-core
+
Rules: @resource names a resource.rdb of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
When to use: A role that connects to the database: the app's service role, a reporting job, the role migrations run as (access: owner).
+
Attributes
+
+
+
+
Attribute
+
Type
+
Required
+
Default
+
Allowed values
+
Provider
+
Description
+
+
+
+
@access
+
string
+
yes
+
+
owner, readWrite, read
+
metaobjects-systems-core
+
owner: creates and changes the schema's tables (the role migrations run as). readWrite: reads and writes rows. read: reads rows.
+
+
+
@maintain
+
boolean
+
no
+
+
+
metaobjects-systems-core
+
The role may also refresh materialized views and run maintenance on the tables it covers (PostgreSQL's MAINTAIN privilege). Absent means it may not.
+
+
+
@resource
+
string
+
yes
+
+
+
metaobjects-systems-core
+
The relational database this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a database of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).
+
+
+
@schema
+
string
+
no
+
+
+
metaobjects-systems-core
+
The one schema the grant covers. Absent: every schema of the database.
+
+
+
Allowed children
+
No structural children.
+
grant.search
+
Access to a search index of the role's own system (resource.search), optionally limited to one index.
+
Owning provider: metaobjects-systems-core
+
Rules: @resource names a resource.search of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
When to use: A role that queries an index or keeps it up to date.
+
Attributes
+
+
+
+
Attribute
+
Type
+
Required
+
Default
+
Allowed values
+
Provider
+
Description
+
+
+
+
@access
+
string
+
yes
+
+
read, write, manage
+
metaobjects-systems-core
+
read: queries. write: adds, changes and removes documents. manage: also creates and drops indexes.
+
+
+
@index
+
string
+
no
+
+
+
metaobjects-systems-core
+
The one index the grant covers. Absent: every index.
+
+
+
@resource
+
string
+
yes
+
+
+
metaobjects-systems-core
+
The search index this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; an index of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).
+
+
+
Allowed children
+
No structural children.
+
grant.stream
+
Access to a stream of the role's own system (resource.stream).
+
Owning provider: metaobjects-systems-core
+
Rules: @resource names a resource.stream of the role's own system (ERR_GRANT_CROSSES_SYSTEM otherwise).
+
When to use: A role that appends to a stream or reads it.
+
Attributes
+
+
+
+
Attribute
+
Type
+
Required
+
Default
+
Allowed values
+
Provider
+
Description
+
+
+
+
@access
+
string
+
yes
+
+
publish, consume
+
metaobjects-systems-core
+
publish: appends messages. consume: reads them, in a consumer group of its own.
+
+
+
@resource
+
string
+
yes
+
+
+
metaobjects-systems-core
+
The stream this grant is on, by name. A bare name is a resource of the role's own system. A name that resolves to nothing is ERR_REF_UNRESOLVED; one that names another kind of node, or another kind of resource, is ERR_REF_WRONG_KIND; a stream of another system is ERR_GRANT_CROSSES_SYSTEM (another system's data is reached through an API it provides, with grant.api).
Nobody directly: a group exists to carry what its members share (@memberOf), and cannot sign in.
Owning provider: metaobjects-systems-core
@@ -124,7 +126,9 @@
role.group
Allowed children
-
No structural children.
+
+
grant.* — 0..*
+
role.service
A running app or job. A generator creates a login for it and delivers the credential to the app that runs as it (@runsAs).
Owning provider: metaobjects-systems-core
@@ -162,7 +166,9 @@
role.service
Allowed children
-
No structural children.
+
+
grant.* — 0..*
+
role.token
Automation outside the system's own apps, given a scoped token: a deploy pipeline, CI, an outside consumer.
Owning provider: metaobjects-systems-core
@@ -209,7 +215,9 @@
role.token
Allowed children
-
No structural children.
+
+
grant.* — 0..*
+
role.user
A named person, or an agent acting for one. No shared secret is generated or stored for it.
Owning provider: metaobjects-systems-core
@@ -247,7 +255,9 @@
role.user
Allowed children
-
No structural children.
+
+
grant.* — 0..*
+
public static bool HasPrimarySource(MetaObject obj) =>
- obj.Sources().Any(s => s.Role == SOURCE_ROLE_PRIMARY);
+ obj.Sources().Any(s => s.IsRdb && s.Role == SOURCE_ROLE_PRIMARY);
///
/// §A2/§A3 — the ONE place a data name is resolved for a generator run. Both
@@ -670,8 +670,8 @@ public static bool HasPrimarySource(MetaObject obj) =>
// through Sources[role].PhysicalName, which is the point of the restructure: one
// key stopped meaning a table, a view and a procedure depending on the object.
Name = obj.Name,
- Sources = SourcesOf(obj.Sources(), obj.Name),
- OwnSources = SourcesOf(obj.OwnSources(), obj.Name),
+ Sources = SourcesOf(obj.Sources().Where(s => s.IsRdb).ToList(), obj.Name),
+ OwnSources = SourcesOf(obj.OwnSources().Where(s => s.IsRdb).ToList(), obj.Name),
Fields = fields,
OwnFields = ownFields,
Identities = KeysOf(obj.Identities()),
diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs
index 5d23cdc06d..99e11f7d59 100644
--- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs
+++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs
@@ -228,7 +228,7 @@ private static void ValidateProjectionLicensing(MetaData model, List
// unreachable without first tripping the extends rule above.
foreach (var child in model.OwnChildren())
{
- if (child.Type != TYPE_SOURCE) continue;
+ if (child.Type != TYPE_SOURCE || child.SubType != SOURCE_SUBTYPE_RDB) continue;
string kind = child is MetaSource ms ? ms.EffectiveKind : child.SubType;
if (!SOURCE_READ_ONLY_KINDS.Contains(kind))
{
@@ -3357,6 +3357,8 @@ private static string RuntimeTypeName(object? value)
// Pass: ValidateOnePrimarySource (source-v2, ADR-0007)
// An object that declares ≥1 source children MUST have exactly one whose
// effective role is "primary":
+ // Counts source.rdb children only; a document or search source is never a
+ // relational primary.
// 0 sources → OK (object is not persisted; no rule to enforce).
// 1+ sources, 1 primary → OK
// 1+ sources, 0 primary → ERR_SOURCE_NO_PRIMARY
@@ -3392,8 +3394,8 @@ private static void WalkOnePrimarySource(MetaData node, List errors)
private static void ValidateObjectPrimarySource(MetaObject obj, List errors)
{
- // Own-only MetaSource children.
- var sources = obj.OwnSources();
+ // Own-only source.rdb children: @role and the one-primary rule are rdb-only.
+ var sources = obj.OwnSources().Where(s => s.IsRdb).ToList();
if (sources.Count == 0)
{
// No sources declared — object is not persisted; rule does not apply.
diff --git a/server/csharp/MetaObjects/Meta/MetaSource.cs b/server/csharp/MetaObjects/Meta/MetaSource.cs
index fc43ae6bba..e6b0351d81 100644
--- a/server/csharp/MetaObjects/Meta/MetaSource.cs
+++ b/server/csharp/MetaObjects/Meta/MetaSource.cs
@@ -129,13 +129,20 @@ public bool IsCallable() =>
EffectiveKind == SOURCE_KIND_STORED_PROC || EffectiveKind == SOURCE_KIND_TABLE_FUNCTION;
///
- /// True when this source's effective kind is read-only (view, materializedView,
- /// storedProc, tableFunction). Derived from .
+ /// True when this is a source.rdb — the relational paradigm, the only one with a
+ /// writable/read-only @kind, a @role and the one-primary rule.
///
- public bool IsReadOnly() => SOURCE_READ_ONLY_KINDS.Contains(EffectiveKind);
+ public bool IsRdb => SubType == SOURCE_SUBTYPE_RDB;
- /// True when this source is writable (i.e. not read-only).
- public bool IsWritable() => !IsReadOnly();
+ ///
+ /// True when this is a source.rdb whose effective kind is read-only (view,
+ /// materializedView, storedProc, tableFunction). A document or search source is
+ /// neither read-only nor writable: writability is defined for the rdb paradigm only.
+ ///
+ public bool IsReadOnly() => IsRdb && SOURCE_READ_ONLY_KINDS.Contains(EffectiveKind);
+
+ /// True when this is a source.rdb whose effective kind is writable (table).
+ public bool IsWritable() => IsRdb && !SOURCE_READ_ONLY_KINDS.Contains(EffectiveKind);
///
/// Resolved physical SQL name for this source, following the FR-016 / ADR-0018
diff --git a/server/csharp/MetaObjects/Meta/SourceResolution.cs b/server/csharp/MetaObjects/Meta/SourceResolution.cs
index 9ecfd8d93d..5a8b47216f 100644
--- a/server/csharp/MetaObjects/Meta/SourceResolution.cs
+++ b/server/csharp/MetaObjects/Meta/SourceResolution.cs
@@ -56,7 +56,7 @@ public static class SourceResolution
/// only wants the refusal, and no third shape has a use.
///
private static IReadOnlyList PrimaryRdbSources(MetaObject obj) =>
- obj.Sources().Where(s => s.Role == SOURCE_ROLE_PRIMARY).ToList();
+ obj.Sources().Where(s => s.IsRdb && s.Role == SOURCE_ROLE_PRIMARY).ToList();
///
/// The role-scoped PRIMARY source of , or null when it has none
diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt
index 069fa6171d..77b1602e1c 100644
--- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt
+++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt
@@ -384,6 +384,7 @@ public object KotlinGenUtil {
// ADR-0039: getSources(true) resolves through `extends`; getSources(false) is the
// sanctioned own-only twin for "what does THIS object declare".
for (src in obj.getSources(includeParentData)) {
+ if (!src.isRdb) continue
val role = src.role
val resolved = sourceNamesOf(src)
val existing = out[role]
diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java
index fab269d2ee..32532852c4 100644
--- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java
+++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java
@@ -298,6 +298,7 @@ private static Map sourcesOf(MetaObject obj, boolean includ
// ADR-0039: getSources(true) resolves through `extends`; getSources(false) is the
// sanctioned own-only twin for "what does THIS class declare".
for (MetaSource src : obj.getSources(includeParentData)) {
+ if (!src.isRdb()) continue;
String role = src.getRole();
SourceNames resolved = sourceNamesOf(src);
SourceNames existing = out.get(role);
diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java
index 8d265d6618..3644d9f436 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java
@@ -1633,8 +1633,8 @@ private static void walkOnePrimarySource(MetaData node) {
/**
* Enforce the one-primary rule on a single {@code MetaObject} node.
*
- *
Counts own {@code MetaSource} children whose effective role is {@code "primary"}.
- * Objects with zero source children are exempt.
+ *
Counts own {@code source.rdb} children whose effective role is {@code "primary"};
+ * {@code @role} and the rule are rdb-only. Objects with zero such children are exempt.
*
* @param obj the object node to inspect
* @throws MetaDataException if the one-primary rule is violated
@@ -1645,7 +1645,9 @@ private static void validateObjectPrimarySource(MetaObject obj) {
// walked separately, so we count only THIS node's own source children (an
// inherited primary belongs to the parent's own validation). getSources(false)
// is the explicit own-only form (the no-arg getSources() now RESOLVES).
- java.util.Collection sources = obj.getSources(false);
+ java.util.List sources = obj.getSources(false).stream()
+ .filter(MetaSource::isRdb)
+ .collect(java.util.stream.Collectors.toList());
if (sources.isEmpty()) {
// No sources declared — object is not persisted; no rule to enforce.
@@ -6120,6 +6122,7 @@ private static void validateProjectionLicensing(MetaObject obj) {
for (MetaData child : obj.getChildren(MetaData.class, false)) {
if (!(child instanceof MetaSource)) continue;
MetaSource s = (MetaSource) child;
+ if (!s.isRdb()) continue;
if (!MetaSource.READ_ONLY_KINDS.contains(s.getEffectiveKind())) {
throw new MetaDataException(
"ERR_PROJECTION_SOURCE_WRITABLE"
diff --git a/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java b/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java
index 8ea451eef8..72f2f12746 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java
@@ -1077,7 +1077,7 @@ public boolean isWriteThrough() {
boolean hasReadOnly = false;
for (MetaSource src : getSources(false)) { // own-only (ADR-0039)
if (src.isReadOnly()) hasReadOnly = true;
- else hasWritable = true;
+ if (src.isWritable()) hasWritable = true;
}
return hasWritable && hasReadOnly;
}
diff --git a/server/java/metadata/src/main/java/com/metaobjects/source/MetaSource.java b/server/java/metadata/src/main/java/com/metaobjects/source/MetaSource.java
index 92d0edc772..0abcd38627 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/source/MetaSource.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/source/MetaSource.java
@@ -206,18 +206,27 @@ public String getRole() {
}
/**
- * Returns {@code true} when {@code @kind} names a read-only construct
- * (view, materializedView, storedProc, tableFunction).
+ * Returns {@code true} when this is a {@code source.rdb} — the relational paradigm, the only
+ * one with a writable/read-only {@code @kind}, a {@code @role} and the one-primary rule.
+ */
+ public boolean isRdb() {
+ return RdbSource.SUBTYPE_RDB.equals(getSubType());
+ }
+
+ /**
+ * Returns {@code true} when this is a {@code source.rdb} whose {@code @kind} names a
+ * read-only construct (view, materializedView, storedProc, tableFunction). A document or
+ * search source is neither read-only nor writable: writability is rdb-only.
*/
public boolean isReadOnly() {
- return READ_ONLY_KINDS.contains(getEffectiveKind());
+ return isRdb() && READ_ONLY_KINDS.contains(getEffectiveKind());
}
/**
- * Returns {@code true} when this source is writable (i.e. not read-only).
+ * Returns {@code true} when this is a {@code source.rdb} whose {@code @kind} is writable.
*/
public boolean isWritable() {
- return !isReadOnly();
+ return isRdb() && !READ_ONLY_KINDS.contains(getEffectiveKind());
}
/**
diff --git a/server/java/metadata/src/main/java/com/metaobjects/source/SourceResolution.java b/server/java/metadata/src/main/java/com/metaobjects/source/SourceResolution.java
index 7895ba6edf..200517da8f 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/source/SourceResolution.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/source/SourceResolution.java
@@ -72,7 +72,7 @@ private SourceResolution() {}
private static List primaryRdbSources(MetaObject obj) {
List primaries = new ArrayList<>();
for (MetaSource src : obj.getSources(true)) {
- if (MetaSource.ROLE_PRIMARY.equals(src.getRole())) primaries.add(src);
+ if (src.isRdb() && MetaSource.ROLE_PRIMARY.equals(src.getRole())) primaries.add(src);
}
return primaries;
}
diff --git a/server/python/src/metaobjects/codegen/generators/names_generator.py b/server/python/src/metaobjects/codegen/generators/names_generator.py
index 8f69acfb54..f3a9e3c725 100644
--- a/server/python/src/metaobjects/codegen/generators/names_generator.py
+++ b/server/python/src/metaobjects/codegen/generators/names_generator.py
@@ -363,7 +363,7 @@ def _sources_by_role(entity: MetaObject) -> dict[str, MetaSource]:
"""
out: dict[str, MetaSource] = {}
for child in entity.children():
- if not isinstance(child, MetaSource):
+ if not isinstance(child, MetaSource) or not child.is_rdb():
continue
role = child.role()
existing = out.get(role)
diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py
index c97a83c540..58626570c0 100644
--- a/server/python/src/metaobjects/loader/validation_passes.py
+++ b/server/python/src/metaobjects/loader/validation_passes.py
@@ -87,6 +87,7 @@
SOURCE_KIND_VIEW,
SOURCE_READ_ONLY_KINDS,
SOURCE_ROLE_PRIMARY,
+ SOURCE_SUBTYPE_RDB,
)
from ..meta.core.attr.attr_constants import (
ATTR_SUBTYPE_INT_MAP,
@@ -4008,8 +4009,9 @@ def _format_reference_candidates(candidates: list[MetaData]) -> str:
# ---------------------------------------------------------------------------
# Pass: one-primary multi-source rule (ADR-0007 source v2)
# ---------------------------------------------------------------------------
-# Walks every object.entity / object.value; counts source own-children with
-# role == "primary" (using the default-aware MetaSource.role() getter):
+# Walks every object.entity / object.value; counts source.rdb own-children with
+# role == "primary" (using the default-aware MetaSource.role() getter). @role and the
+# rule are rdb-only: a document or search source is never a relational primary.
# - 0 sources total → skip (object is not persisted).
# - exactly 1 primary → OK.
# - 0 primaries → ERR_SOURCE_NO_PRIMARY.
@@ -4028,7 +4030,9 @@ def _validate_one_primary_source(
# ADR-0039 sanctioned own: the one-primary rule validates the sources THIS
# object DECLARES (own) — mirrors the TS validate-source-roles `ownChildren`.
- sources = [c for c in node.own_children() if c.type == TYPE_SOURCE]
+ sources = [
+ c for c in node.own_children() if c.type == TYPE_SOURCE and c.sub_type == SOURCE_SUBTYPE_RDB
+ ]
if not sources:
continue
@@ -4527,7 +4531,7 @@ def _validate_projection_licensing(node: MetaObject, errors: list[MetaError]) ->
# super is unreachable without first tripping the extends rule above. Mirrors the
# TS validateProjectionLicensing (`model.ownChildren()` + `child.effectiveKind`).
for child in node.own_children():
- if child.type != TYPE_SOURCE:
+ if child.type != TYPE_SOURCE or child.sub_type != SOURCE_SUBTYPE_RDB:
continue
kind = child.effective_kind() if isinstance(child, MetaSource) else child.sub_type
if kind not in SOURCE_READ_ONLY_KINDS:
diff --git a/server/python/src/metaobjects/meta/core/object/meta_object.py b/server/python/src/metaobjects/meta/core/object/meta_object.py
index 985b80a0f0..ca3ea30002 100644
--- a/server/python/src/metaobjects/meta/core/object/meta_object.py
+++ b/server/python/src/metaobjects/meta/core/object/meta_object.py
@@ -50,7 +50,7 @@ def is_write_through(self) -> bool:
continue
if c.is_read_only():
has_read_only = True
- else:
+ if c.is_writable():
has_writable = True
return has_writable and has_read_only
diff --git a/server/python/src/metaobjects/meta/persistence/source/meta_source.py b/server/python/src/metaobjects/meta/persistence/source/meta_source.py
index a6598d1103..15537dcc49 100644
--- a/server/python/src/metaobjects/meta/persistence/source/meta_source.py
+++ b/server/python/src/metaobjects/meta/persistence/source/meta_source.py
@@ -20,6 +20,7 @@
SOURCE_ATTR_TABLE,
SOURCE_ATTR_UNMANAGED,
SOURCE_READ_ONLY_KINDS,
+ SOURCE_SUBTYPE_RDB,
)
@@ -75,14 +76,20 @@ def role(self) -> str:
v = self.get_meta_attr(SOURCE_ATTR_ROLE) # ADR-0039: resolving
return v if isinstance(v, str) and v else DEFAULT_SOURCE_ROLE
+ def is_rdb(self) -> bool:
+ """True when this is a ``source.rdb`` — the relational paradigm, the only one
+ with a writable/read-only ``@kind``, a ``@role`` and the one-primary rule."""
+ return self.sub_type == SOURCE_SUBTYPE_RDB
+
def is_read_only(self) -> bool:
- """True when ``@kind`` names a read-only construct (view,
- materializedView, storedProc, tableFunction)."""
- return self.effective_kind() in SOURCE_READ_ONLY_KINDS
+ """True when this is a ``source.rdb`` whose ``@kind`` names a read-only
+ construct (view, materializedView, storedProc, tableFunction). A document or
+ search source is neither read-only nor writable: writability is rdb-only."""
+ return self.is_rdb() and self.effective_kind() in SOURCE_READ_ONLY_KINDS
def is_writable(self) -> bool:
- """True when this source is writable (i.e. not read-only)."""
- return not self.is_read_only()
+ """True when this is a ``source.rdb`` whose ``@kind`` is writable (``table``)."""
+ return self.is_rdb() and self.effective_kind() not in SOURCE_READ_ONLY_KINDS
def schema(self) -> str | None:
"""The value of ``@schema``, or ``None`` if absent."""
diff --git a/server/python/src/metaobjects/source_resolution.py b/server/python/src/metaobjects/source_resolution.py
index 6d4032eb20..d3f730671a 100644
--- a/server/python/src/metaobjects/source_resolution.py
+++ b/server/python/src/metaobjects/source_resolution.py
@@ -89,7 +89,7 @@ def primary_rdb_source(entity: MetaObject) -> MetaSource | None:
primaries = [
c
for c in entity.children()
- if isinstance(c, MetaSource) and c.role() == SOURCE_ROLE_PRIMARY
+ if isinstance(c, MetaSource) and c.is_rdb() and c.role() == SOURCE_ROLE_PRIMARY
]
if not primaries:
return None
diff --git a/server/rust/metaobjects/src/docs_view/storage.rs b/server/rust/metaobjects/src/docs_view/storage.rs
index 20aa81f312..3530a6ac50 100644
--- a/server/rust/metaobjects/src/docs_view/storage.rs
+++ b/server/rust/metaobjects/src/docs_view/storage.rs
@@ -17,7 +17,7 @@ use super::{ATTR_DESCRIPTION, Build, DOT, TYPE_FIELD, str_attr};
use crate::loader::split_child_tail;
use crate::naming::{
NamingCtx, primary_rdb_source, resolve_column_name, resolve_flattened_column_name,
- source_effective_kind, source_is_read_only, source_physical_name,
+ source_effective_kind, source_is_writable, source_physical_name,
};
use crate::node::NodeId;
use crate::parser::TYPE_OBJECT;
@@ -25,7 +25,6 @@ use crate::parser::TYPE_OBJECT;
const TYPE_IDENTITY: &str = "identity";
const TYPE_ORIGIN: &str = "origin";
const TYPE_VALIDATOR: &str = "validator";
-const TYPE_SOURCE: &str = "source";
const SUBTYPE_PRIMARY: &str = "primary";
const SUBTYPE_REFERENCE: &str = "reference";
const SUBTYPE_REQUIRED: &str = "required";
@@ -365,8 +364,7 @@ impl Build<'_> {
let mut entities: Vec<(NodeId, NodeId)> = Vec::new();
let mut target_only: Vec<(NodeId, NodeId)> = Vec::new();
let mut tph_members: Vec<(NodeId, NodeId)> = Vec::new();
- let is_writable_source =
- |c: NodeId| tree.node(c).type_name == TYPE_SOURCE && !source_is_read_only(tree, c);
+ let is_writable_source = |c: NodeId| source_is_writable(tree, c);
for &obj in &objects {
let base = self.discriminator_base(obj);
if let Some(base) = base
diff --git a/server/rust/metaobjects/src/naming.rs b/server/rust/metaobjects/src/naming.rs
index c962fc9341..b43bb04fd2 100644
--- a/server/rust/metaobjects/src/naming.rs
+++ b/server/rust/metaobjects/src/naming.rs
@@ -605,9 +605,15 @@ pub fn source_role(tree: &Tree, source: NodeId) -> &str {
str_attr(tree, source, ATTR_ROLE).unwrap_or(DEFAULT_SOURCE_ROLE)
}
-/// True when the source's effective kind is read-only.
+/// True when the source is a `source.rdb` whose effective kind is read-only. A document
+/// or search source is neither read-only nor writable: writability is rdb-only.
pub fn source_is_read_only(tree: &Tree, source: NodeId) -> bool {
- READ_ONLY_KINDS.contains(&source_effective_kind(tree, source))
+ is_rdb_source(tree, source) && READ_ONLY_KINDS.contains(&source_effective_kind(tree, source))
+}
+
+/// True when the source is a `source.rdb` whose effective kind is writable (`table`).
+pub fn source_is_writable(tree: &Tree, source: NodeId) -> bool {
+ is_rdb_source(tree, source) && !READ_ONLY_KINDS.contains(&source_effective_kind(tree, source))
}
/// Resolved physical SQL name of a source, by the four-step rule (FR-016, ADR-0018):
diff --git a/server/rust/metaobjects/src/validate/persistence.rs b/server/rust/metaobjects/src/validate/persistence.rs
index 30a704f77e..4fcb32dd03 100644
--- a/server/rust/metaobjects/src/validate/persistence.rs
+++ b/server/rust/metaobjects/src/validate/persistence.rs
@@ -108,7 +108,7 @@ fn effective_kind(tree: &Tree, s: NodeId) -> &str {
}
fn is_read_only(tree: &Tree, s: NodeId) -> bool {
- READ_ONLY_KINDS.contains(&effective_kind(tree, s))
+ tree.node(s).sub_type == SOURCE_RDB && READ_ONLY_KINDS.contains(&effective_kind(tree, s))
}
fn sql_body_set(tree: &Tree, s: NodeId) -> bool {
@@ -149,13 +149,9 @@ fn js_blank(s: &str) -> bool {
pub fn validate_source_roles(ctx: &Ctx<'_>, out: &mut Findings) {
let tree = ctx.tree;
for obj in objects(tree, ctx.root) {
- // ADR-0039 own: the one-primary rule counts sources declared on THIS object.
- let sources: Vec = tree
- .own_children(obj)
- .iter()
- .copied()
- .filter(|&c| tree.node(c).type_name == TYPE_SOURCE)
- .collect();
+ // ADR-0039 own: the one-primary rule counts sources declared on THIS object, and
+ // only source.rdb ones: @role and the rule are rdb-only.
+ let sources: Vec = own_rdb_sources(tree, obj).collect();
if sources.is_empty() {
continue;
}
diff --git a/server/rust/metaobjects/src/validate/reporting.rs b/server/rust/metaobjects/src/validate/reporting.rs
index 6177b3d762..3faa2b4dd2 100644
--- a/server/rust/metaobjects/src/validate/reporting.rs
+++ b/server/rust/metaobjects/src/validate/reporting.rs
@@ -70,7 +70,6 @@ const CARDINALITY_ONE: &str = "one";
const STORAGE_FLATTENED: &str = "flattened";
const KIND_TABLE: &str = "table";
const KIND_VIEW: &str = "view";
-const READ_ONLY_KINDS: [&str; 4] = ["view", "materializedView", "storedProc", "tableFunction"];
const TIME_GRAINS: [&str; 6] = ["hour", "day", "week", "month", "quarter", "year"];
const GRAIN_HOUR: &str = "hour";
const DERIVED_FNS: [&str; 4] = ["add", "subtract", "multiply", "divide"];
@@ -1236,7 +1235,11 @@ fn derived_field_name(name: &str, grain: Option<&str>) -> String {
}
fn is_writable(tree: &Tree, source: NodeId) -> bool {
- !READ_ONLY_KINDS.contains(&effective_kind(tree, source))
+ crate::naming::source_is_writable(tree, source)
+}
+
+fn is_read_only(tree: &Tree, source: NodeId) -> bool {
+ crate::naming::source_is_read_only(tree, source)
}
fn effective_kind(tree: &Tree, source: NodeId) -> &str {
@@ -1284,7 +1287,7 @@ fn check_report(env: &Env<'_>, report: NodeId, sink: &Sink<'_>) {
}
}
for &s in &sources {
- if !is_writable(tree, s) && effective_kind(tree, s) != KIND_VIEW {
+ if is_read_only(tree, s) && effective_kind(tree, s) != KIND_VIEW {
err_at(
s,
ERR_INVALID_REPORT,
diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs
index 22d51cb2ab..35a6753ed4 100644
--- a/server/rust/metaobjects/src/validate/rules.rs
+++ b/server/rust/metaobjects/src/validate/rules.rs
@@ -108,10 +108,7 @@ const A_MANY: &str = "many";
const A_METHOD: &str = "method";
const A_PATH: &str = "path";
const A_FIELDS: &str = "fields";
-const A_KIND: &str = "kind";
-const KIND_TABLE: &str = "table";
-const READ_ONLY_KINDS: [&str; 4] = ["view", "materializedView", "storedProc", "tableFunction"];
const METHOD_POST: &str = "POST";
const METHOD_GET: &str = "GET";
@@ -730,14 +727,9 @@ fn check_redeclared_lifecycles(
}
}
-/// A source that is not one of the read-only kinds; `table` is the default.
+/// A `source.rdb` that is not one of the read-only kinds; `table` is the default.
fn is_writable_source(tree: &Tree, node: NodeId) -> bool {
- tree.node(node).type_name == T_SOURCE && {
- let kind = str_attr(tree, node, A_KIND)
- .filter(|k| !k.is_empty())
- .unwrap_or(KIND_TABLE);
- !READ_ONLY_KINDS.contains(&kind)
- }
+ crate::naming::source_is_writable(tree, node)
}
/// L2, L6 and L10 for one entity, over its effective (inherited) lifecycles.
diff --git a/server/rust/metaobjects/src/validate/structure.rs b/server/rust/metaobjects/src/validate/structure.rs
index 5671a5aafb..68d2b6d0cc 100644
--- a/server/rust/metaobjects/src/validate/structure.rs
+++ b/server/rust/metaobjects/src/validate/structure.rs
@@ -38,6 +38,7 @@ const TYPE_FIELD: &str = "field";
const SUB_ENTITY: &str = "entity";
const SUB_VALUE: &str = "value";
const SUB_PROJECTION: &str = "projection";
+const SUB_RDB: &str = "rdb";
const SUB_PRIMARY: &str = "primary";
const SUB_REFERENCE: &str = "reference";
const ATTR_FIELDS: &str = "fields";
@@ -232,7 +233,7 @@ fn projection_licensing(tree: &Tree, id: NodeId, out: &mut Findings) {
}
// ADR-0039: own: OWN sources only; an inherited source is validated where declared.
for &child in tree.own_children(id) {
- if !is_type(tree, child, TYPE_SOURCE) {
+ if !is_type(tree, child, TYPE_SOURCE) || tree.node(child).sub_type != SUB_RDB {
continue;
}
let kind = effective_kind(tree, child);
diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json
index 759fd63065..da3c8d55ff 100644
--- a/server/rust/metaobjects/tests/conformance-expected-failures.json
+++ b/server/rust/metaobjects/tests/conformance-expected-failures.json
@@ -1,6 +1,6 @@
{
"language": "rust",
"notes": "The Rust port passes every fixture of the shared metamodel corpus, so the ledger is empty. The ledger may only shrink and is kept for the day a new fixture lands that Rust does not pass yet: list it here with the reason, and it leaves when the work that covers it lands. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.",
- "minPassing": 608,
+ "minPassing": 609,
"fixtures": []
}
diff --git a/server/typescript/packages/codegen-ts/src/names.ts b/server/typescript/packages/codegen-ts/src/names.ts
index 50a9d08eeb..24cc6e11e0 100644
--- a/server/typescript/packages/codegen-ts/src/names.ts
+++ b/server/typescript/packages/codegen-ts/src/names.ts
@@ -14,7 +14,7 @@ import {
resolveIndexName,
resolveTableSchema,
isMetaObject,
- isMetaSource,
+ isRdbSource,
isWritableSource,
OBJECT_SUBTYPE_ENTITY,
FIELD_ATTR_OBJECT_REF,
@@ -272,7 +272,7 @@ function rdbSourcesOf(obj: MetaObject, own: boolean): MetaSource[] {
// ADR-0039: children() resolves through `extends`; ownChildren() is the sanctioned
// own-only twin for "what does THIS artifact declare".
const kids = own ? obj.ownChildren() : obj.children();
- return kids.filter((c): c is MetaSource => isMetaSource(c));
+ return kids.filter(isRdbSource);
}
/** Every `identity.*` / `index.*` child, keyed by metamodel name. */
diff --git a/server/typescript/packages/codegen-ts/src/source-detect.ts b/server/typescript/packages/codegen-ts/src/source-detect.ts
index e417798895..23df48489e 100644
--- a/server/typescript/packages/codegen-ts/src/source-detect.ts
+++ b/server/typescript/packages/codegen-ts/src/source-detect.ts
@@ -18,18 +18,13 @@ import {
OBJECT_SUBTYPE_PROJECTION,
OBJECT_SUBTYPE_REPORT,
SOURCE_KIND_VIEW,
- SOURCE_SUBTYPE_RDB,
isMetaSource,
+ isRdbSource,
isWritableSource,
reportReadModel,
reportReadSource,
} from "@metaobjectsdev/metadata";
-import type { MetaData, MetaObject, MetaRoot } from "@metaobjectsdev/metadata";
-
-/** True when the child is a source.rdb node (subType-scoped — the rdb paradigm only). */
-function isRdbSource(child: MetaData): boolean {
- return isMetaSource(child) && child.subType === SOURCE_SUBTYPE_RDB;
-}
+import type { MetaObject, MetaRoot } from "@metaobjectsdev/metadata";
/**
* True when the entity declares at least one writable source.rdb child.
diff --git a/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts b/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts
index ccdec00fd0..976b25a098 100644
--- a/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts
+++ b/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts
@@ -460,3 +460,16 @@ describe("prisma-schema — the generator", () => {
expect((await gen(without, [prismaSchemaFile()])).has("schema.checks.sql")).toBe(false);
});
});
+
+describe("prisma-schema — document and search sources", () => {
+ test("an entity kept only in a document store or a search index gets no model", async () => {
+ // The shared conformance fixture: Shipment has a source.rdb table, TrackingScan only a
+ // source.document and ShipmentHit only a source.search (ADR-0070). Only a table is a model.
+ const { root, errors } = await MetaDataLoader.fromDirectory(
+ join(import.meta.dir, "../../../../../../fixtures/conformance/systems-grants-and-sources/input"),
+ );
+ expect(errors.map((e) => e.message)).toEqual([]);
+ const spec = buildPrismaSchema(root, { provider: "postgresql" });
+ expect(spec.models.map((m) => m.name)).toEqual(["Shipment"]);
+ });
+});
diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts
index cb50c49c9a..fa05008193 100644
--- a/server/typescript/packages/metadata/src/index.ts
+++ b/server/typescript/packages/metadata/src/index.ts
@@ -168,6 +168,7 @@ export {
isMetaObject,
isMetaField,
isMetaSource,
+ isRdbSource,
isWritableSource,
isReadOnlySource,
} from "./shared/node-guards.js";
diff --git a/server/typescript/packages/metadata/src/naming.ts b/server/typescript/packages/metadata/src/naming.ts
index c7362e4c96..340d27c860 100644
--- a/server/typescript/packages/metadata/src/naming.ts
+++ b/server/typescript/packages/metadata/src/naming.ts
@@ -15,7 +15,7 @@ import type { MetaSource } from "./persistence/source/meta-source.js";
// would silently fall through to the entity-name fallback: a DIFFERENT table name,
// which migrate then emits as a rename against a live database. (The same split would
// also make the divergence refusal see no primaries at all, and say nothing.)
-import { isMetaSource } from "./shared/node-guards.js";
+import { isRdbSource } from "./shared/node-guards.js";
import { MetaModelError } from "./errors.js";
import { OBJECT_ATTR_COLLECTION_NAME } from "./core/object/object-constants.js";
@@ -507,7 +507,8 @@ export function declaredCollectionName(obj: MetaData): { name: string } | undefi
* from the object subtype, so an `object.value` and a sourceless
* `object.projection` both land here rather than being special-cased.
*
- * `isMetaSource`, not `instanceof`: under two physical copies of this package a
+ * Only a `source.rdb` counts: a document or search source has no relational address.
+ * `isRdbSource`, not `instanceof`: under two physical copies of this package a
* class check is false for a real primary source, and the failure is SILENT —
* the object reads as "not backed by any store".
*
@@ -574,7 +575,7 @@ export function sourceAddressKey(source: MetaSource): string {
export function primaryRdbSource(entity: MetaData): MetaSource | undefined {
const primaries = entity.children().filter(
- (c): c is MetaSource => isMetaSource(c) && c.role === SOURCE_ROLE_PRIMARY,
+ (c): c is MetaSource => isRdbSource(c) && c.role === SOURCE_ROLE_PRIMARY,
);
if (primaries.length === 0) return undefined;
const distinct = [...new Set(primaries.map(sourceAddressKey))].sort();
diff --git a/server/typescript/packages/metadata/src/persistence/source/meta-source.ts b/server/typescript/packages/metadata/src/persistence/source/meta-source.ts
index 7e36904622..2397460c66 100644
--- a/server/typescript/packages/metadata/src/persistence/source/meta-source.ts
+++ b/server/typescript/packages/metadata/src/persistence/source/meta-source.ts
@@ -18,6 +18,7 @@ import {
SOURCE_ATTR_SQL,
SOURCE_ATTR_UNMANAGED,
SOURCE_READ_ONLY_KINDS,
+ SOURCE_SUBTYPE_RDB,
DEFAULT_SOURCE_KIND,
DEFAULT_SOURCE_ROLE,
PHYSICAL_NAME_ATTR_BY_KIND,
@@ -83,16 +84,18 @@ export class MetaSource extends MetaData {
}
/**
- * True when this source's effective kind is read-only (view, materializedView,
- * storedProc, tableFunction). Derived from the @kind attr on source.rdb.
+ * True when this is a source.rdb whose effective kind is read-only (view,
+ * materializedView, storedProc, tableFunction). Derived from the @kind attr on
+ * source.rdb. A document or search source is neither read-only nor writable:
+ * writability is defined for the rdb paradigm only.
*/
isReadOnly(): boolean {
- return SOURCE_READ_ONLY_KINDS.has(this.effectiveKind);
+ return this.subType === SOURCE_SUBTYPE_RDB && SOURCE_READ_ONLY_KINDS.has(this.effectiveKind);
}
- /** True when this source is writable (i.e. not read-only). */
+ /** True when this is a source.rdb whose effective kind is writable (`table`). */
isWritable(): boolean {
- return !this.isReadOnly();
+ return this.subType === SOURCE_SUBTYPE_RDB && !SOURCE_READ_ONLY_KINDS.has(this.effectiveKind);
}
/**
diff --git a/server/typescript/packages/metadata/src/persistence/source/validate-source-roles.ts b/server/typescript/packages/metadata/src/persistence/source/validate-source-roles.ts
index cc01c2d8b2..d8309ae729 100644
--- a/server/typescript/packages/metadata/src/persistence/source/validate-source-roles.ts
+++ b/server/typescript/packages/metadata/src/persistence/source/validate-source-roles.ts
@@ -1,20 +1,22 @@
// Validation pass: one-primary multi-source rule.
//
-// An object that declares ≥1 source MUST have exactly one with role "primary".
-// Zero sources is allowed (object is not persisted). Violations:
+// An object that declares ≥1 source.rdb MUST have exactly one with role "primary".
+// Zero sources is allowed (object is not persisted). Only source.rdb counts: @role
+// is an rdb attr, and a document or search source is never a relational primary. Violations:
// ERR_SOURCE_NO_PRIMARY — sources present but none is role "primary"
// ERR_SOURCE_MULTIPLE_PRIMARY — more than one source has role "primary"
import type { MetaData } from "../../shared/meta-data.js";
import { ParseError } from "../../errors.js";
-import { TYPE_OBJECT, TYPE_SOURCE } from "../../shared/base-types.js";
-import { MetaSource } from "./meta-source.js";
+import { TYPE_OBJECT } from "../../shared/base-types.js";
+import type { MetaSource } from "./meta-source.js";
+import { isRdbSource } from "../../shared/node-guards.js";
import { SOURCE_ROLE_PRIMARY, SOURCE_READ_ONLY_KINDS } from "./source-constants.js";
import { OBJECT_SUBTYPE_ENTITY } from "../../core/object/object-constants.js";
/**
* Walks every object in the root and enforces the one-primary rule for
- * multi-source objects:
+ * multi-source objects, counting own source.rdb children only:
* - 0 sources → no error (object is not backed by any store).
* - 1+ sources, exactly 1 with role "primary" → OK.
* - 1+ sources, 0 with role "primary" → ERR_SOURCE_NO_PRIMARY.
@@ -28,10 +30,7 @@ export function validateSourceRoles(root: MetaData): ParseError[] {
// ADR-0039: own — the one-primary rule is a DECLARATION-layer check (cross-port
// parity: Java uses getSources(false)); it counts sources declared on THIS object,
// not inherited ones. The role/kind reads below resolve via MetaSource getters.
- const sources = obj
- .ownChildren()
- .filter((c) => c.type === TYPE_SOURCE)
- .map((c) => c as MetaSource);
+ const sources: MetaSource[] = obj.ownChildren().filter(isRdbSource);
if (sources.length === 0) continue;
diff --git a/server/typescript/packages/metadata/src/shared/node-guards.ts b/server/typescript/packages/metadata/src/shared/node-guards.ts
index 4bd3714de8..d14562fdce 100644
--- a/server/typescript/packages/metadata/src/shared/node-guards.ts
+++ b/server/typescript/packages/metadata/src/shared/node-guards.ts
@@ -47,6 +47,7 @@ import type { MetaRoot } from "./meta-root.js";
import type { MetaObject } from "../core/object/meta-object.js";
import type { MetaField } from "../core/field/meta-field.js";
import type { MetaSource } from "../persistence/source/meta-source.js";
+import { SOURCE_SUBTYPE_RDB } from "../persistence/source/source-constants.js";
/** The node's metamodel `type`, or undefined when the value is not a node at all. */
function nodeType(node: unknown): string | undefined {
@@ -75,6 +76,12 @@ export function isMetaSource(node: unknown): node is MetaSource {
return nodeType(node) === TYPE_SOURCE;
}
+/** True when the node is a `source.rdb` — the relational paradigm, the only one with a
+ * writable/read-only `@kind`, a `@role` and the one-primary rule. */
+export function isRdbSource(node: unknown): node is MetaSource {
+ return isMetaSource(node) && (node as { subType?: unknown }).subType === SOURCE_SUBTYPE_RDB;
+}
+
/**
* True when the node is a source that reports itself writable.
*
diff --git a/server/typescript/packages/metadata/src/subtype-rules.ts b/server/typescript/packages/metadata/src/subtype-rules.ts
index 3f21bbc21e..a3828d5cd4 100644
--- a/server/typescript/packages/metadata/src/subtype-rules.ts
+++ b/server/typescript/packages/metadata/src/subtype-rules.ts
@@ -35,7 +35,7 @@ import {
OBJECT_SUBTYPE_PROJECTION,
} from "./core/object/object-constants.js";
import { MetaSource } from "./persistence/source/meta-source.js";
-import { SOURCE_READ_ONLY_KINDS } from "./persistence/source/source-constants.js";
+import { SOURCE_READ_ONLY_KINDS, SOURCE_SUBTYPE_RDB } from "./persistence/source/source-constants.js";
export interface SubtypeRuleResult {
errors: ParseError[];
@@ -230,7 +230,7 @@ function validateProjectionLicensing(
// (projection) object that declares it; an inherited source from a non-projection
// super is unreachable without first tripping the extends rule above.
for (const child of model.ownChildren()) {
- if (child.type !== TYPE_SOURCE) continue;
+ if (child.type !== TYPE_SOURCE || child.subType !== SOURCE_SUBTYPE_RDB) continue;
const kind =
child instanceof MetaSource ? child.effectiveKind : child.subType;
if (!SOURCE_READ_ONLY_KINDS.has(kind)) {
diff --git a/server/typescript/packages/migrate-ts/test/expected-schema-non-rdb-source.test.ts b/server/typescript/packages/migrate-ts/test/expected-schema-non-rdb-source.test.ts
new file mode 100644
index 0000000000..d322675089
--- /dev/null
+++ b/server/typescript/packages/migrate-ts/test/expected-schema-non-rdb-source.test.ts
@@ -0,0 +1,37 @@
+// A source.document or source.search places an object in a document store or a search index,
+// not in a relational table (ADR-0070). Writability is defined for source.rdb only, so the
+// expected schema `meta migrate` diffs against plans a table for the rdb-backed object and for
+// nothing kept only in a document store or a search index. The models are the shared
+// conformance fixtures, so every port loads the same input.
+
+import { describe, expect, test } from "bun:test";
+import { join } from "node:path";
+import { MetaDataLoader } from "@metaobjectsdev/metadata";
+import type { MetaData } from "@metaobjectsdev/metadata";
+import { buildExpectedSchema } from "../src/expected-schema.js";
+
+const FIXTURES = join(import.meta.dir, "../../../../../fixtures/conformance");
+
+async function loadFixture(name: string): Promise {
+ const result = await MetaDataLoader.fromDirectory(join(FIXTURES, name, "input"));
+ if (result.errors.length > 0) {
+ throw new Error(`Loader errors:\n${result.errors.map((e) => e.message).join("\n")}`);
+ }
+ return result.root;
+}
+
+describe("buildExpectedSchema — document and search sources plan no table", () => {
+ test("an entity kept only in a document store or a search index gets no table", async () => {
+ // Shipment: source.rdb @table shipments. TrackingScan: only a source.document.
+ // ShipmentHit: only a source.search.
+ const root = await loadFixture("systems-grants-and-sources");
+ const snapshot = buildExpectedSchema(root);
+ expect(snapshot.tables.map((t) => t.name)).toEqual(["shipments"]);
+ });
+
+ test("a table with a search copy plans the table once", async () => {
+ const root = await loadFixture("systems-rdb-with-search-copy");
+ const snapshot = buildExpectedSchema(root);
+ expect(snapshot.tables.map((t) => t.name)).toEqual(["shipments"]);
+ });
+});
From 4bc145df5f46c174c22257353a01961b48905787 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Fri, 4 Dec 2026 20:07:52 -0500
Subject: [PATCH 3/8] no-mistakes(review): Treat non-rdb sources as sourceless
in every port
---
AGENTS.md | 2 +-
changelog.d/systems-grants-and-sources.md | 9 +++
docs/CONFORMANCE.md | 10 +--
examples/showcase/site-payload.json | 2 +-
explorer-app/assets/explorer-app.js | 2 +-
.../expected.json | 66 +++++++++++++++++++
.../input/meta.parcels.json | 66 +++++++++++++++++++
.../expected.json | 51 ++++++++++++++
.../input/meta.parcels-audit.json | 34 ++++++++++
.../input/meta.parcels.json | 38 +++++++++++
.../expected.json | 63 ++++++++++++++++++
.../input/meta.demo.json | 63 ++++++++++++++++++
.../SourcelessEntityGatesTests.cs | 37 ++++++++++-
.../ExplorerApp/assets/explorer-app.js | 2 +-
.../MetaObjects.Codegen/InstanceArtifacts.cs | 8 ++-
.../MetaObjects/Core/Transition/Lifecycle.cs | 10 +--
.../MetaObjects/Loader/ValidationPasses.cs | 12 ++--
.../com/metaobjects/generator/ModelWalk.java | 7 +-
.../generator/util/RestSurfaceGate.java | 10 +--
.../explorer-app/assets/explorer-app.js | 2 +-
.../spring/SpringSourcelessEntityTest.java | 47 +++++++++++++
.../java/com/metaobjects/api/Lifecycles.java | 9 ++-
.../metaobjects/loader/ValidationPhase.java | 19 ++++--
.../codegen/collection_name_collision.py | 4 +-
.../metaobjects/codegen/instance_artifacts.py | 8 ++-
.../explorer_app/assets/explorer-app.js | 2 +-
server/python/src/metaobjects/loader/merge.py | 4 +-
.../loader/validate_field_mutability.py | 5 +-
.../metaobjects/loader/validation_passes.py | 9 ++-
.../meta/core/transition/lifecycle.py | 10 +--
.../codegen/test_sourceless_entity_surface.py | 30 +++++++++
.../explorer-app/assets/explorer-app.js | 2 +-
server/rust/metaobjects/src/rules_check.rs | 8 +--
.../metaobjects/src/validate/field_policy.rs | 3 +-
.../metaobjects/src/validate/persistence.rs | 2 +-
server/rust/metaobjects/src/validate/rules.rs | 9 ++-
.../tests/conformance-expected-failures.json | 2 +-
.../packages/codegen-ts/src/source-detect.ts | 10 +--
.../test/sourceless-entity-surface.test.ts | 44 +++++++++++--
.../docs-site/app/assets/explorer-app.js | 2 +-
.../docs-site/src/explorer/view-index.ts | 5 +-
.../core/field/validate-field-mutability.ts | 7 +-
.../metadata/src/core/transition/lifecycle.ts | 12 ++--
.../metadata/src/loader/rules-validation.ts | 2 +-
.../metadata/src/loader/validation-passes.ts | 10 +--
45 files changed, 663 insertions(+), 96 deletions(-)
create mode 100644 fixtures/conformance/systems-document-only-lifecycle-inert/expected.json
create mode 100644 fixtures/conformance/systems-document-only-lifecycle-inert/input/meta.parcels.json
create mode 100644 fixtures/conformance/systems-role-grants-across-files/expected.json
create mode 100644 fixtures/conformance/systems-role-grants-across-files/input/meta.parcels-audit.json
create mode 100644 fixtures/conformance/systems-role-grants-across-files/input/meta.parcels.json
create mode 100644 fixtures/conformance/systems-sql-view-with-search-copy/expected.json
create mode 100644 fixtures/conformance/systems-sql-view-with-search-copy/input/meta.demo.json
diff --git a/AGENTS.md b/AGENTS.md
index de87cb7b72..5fb1d5901b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -74,7 +74,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken.
- **Kotlin** — `codegen-kotlin` (laid out by `KotlinWriter`, ADR-0063, on the JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres.
**Cross-port conformance corpora** (every port runs the shared corpus):
-- Metamodel: `fixtures/conformance/` (609 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green.
+- Metamodel: `fixtures/conformance/` (612 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green.
- Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python / C# / Rust byte-identical; the C# and Rust drift ledgers are empty (`docs/CONFORMANCE.md`).
- Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (the Node reference helper writes them; a native tool is equally first-class, ADR-0015 Amendment 2). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".)
- API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived.
diff --git a/changelog.d/systems-grants-and-sources.md b/changelog.d/systems-grants-and-sources.md
index 1239b33fe2..0b98fa893f 100644
--- a/changelog.d/systems-grants-and-sources.md
+++ b/changelog.d/systems-grants-and-sources.md
@@ -17,6 +17,15 @@
no table for an object kept only in one, and the one-primary rule (`ERR_SOURCE_NO_PRIMARY`,
`ERR_SOURCE_MULTIPLE_PRIMARY`) counts only the `source.rdb` children. A table with a search
copy (`source.rdb` beside `source.search`) loads clean (`systems-rdb-with-search-copy`).
+ Everything else that asks whether an object has a source asks the same of `source.rdb`, so an
+ object whose only sources are document or search sources behaves as one with no source: its
+ lifecycle is inert (`systems-document-only-lifecycle-inert`), its fields are not checked for
+ column collisions, a search copy beside a SQL view does not make that view's shared columns a
+ collision (`systems-sql-view-with-search-copy`), and the generators give it the same output as
+ a sourceless entity (the create and PATCH schemas and the filter and sort allowlists, no table
+ and no routes). A grant is unnamed, so a role redeclared in a second file keeps the grants of
+ both files; the Python loader used to fold them into one
+ (`systems-role-grants-across-files`).
Inside a system a name is used once per type: a `role.service` and a
`role.user` both called `api` are now `ERR_DUPLICATE_NAME` in every port, where the loader
used to merge the second into the first. A redeclaration of the same subtype still merges, and
diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md
index e1dc22d952..99c542b3dd 100644
--- a/docs/CONFORMANCE.md
+++ b/docs/CONFORMANCE.md
@@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor
| Corpus | Fixtures | TS | Java | Kotlin | C# | Python | Rust |
|---|---|---|---|---|---|---|---|
-| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 609 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (609 / 609, empty ledger) |
+| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 612 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (612 / 612, empty ledger) |
| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | 19 / 19 |
| [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | ✓ |
| [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | — |
@@ -82,7 +82,7 @@ and render ledgers; the api-contract runner's list of sub-corpora not built yet)
shrink, and the corpora without one assert each case outright. A new fixture that fails in
Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard
failure when ADR-0065 turns the warning off. A regression still fails: the ledger's
-`minPassing` (609) is the number of fixtures known to pass, and the run fails when fewer do.
+`minPassing` (612) is the number of fixtures known to pass, and the run fails when fewer do.
Beside the corpora it runs the codegen-compile gate (below) with every shipped generator, a
scale gate over twenty copies of the fitness model, and `examples/rust-service/`'s HTTP test.
[The Rust port page](ports/rust.md#conformance) has the detail.
@@ -445,7 +445,7 @@ carry it, and a model that uses it fails there by name. There is no row per pack
## Fixture-to-doc mapping
-### `fixtures/conformance/` — metamodel loader + canonical serializer (609)
+### `fixtures/conformance/` — metamodel loader + canonical serializer (612)
| Fixture prefix | Feature doc |
|---|---|
@@ -468,7 +468,7 @@ carry it, and a model that uses it fails there by name. There is no row per pack
| `origin-*`, `error-origin-*` | [features/templates-and-payloads.md](features/templates-and-payloads.md) (payload origins) |
| `projection-*`, `error-projection-*`, `field-readonly-on-view-projection` | [features/source-kinds.md](features/source-kinds.md) (projections + the object taxonomy, ADR-0028) |
| `requirement-*`, `error-unknown-attr-requirement` | [features/requirements.md](features/requirements.md) (vocabulary only — the gate has its own corpus, `requirement-check-conformance/`; see "Split coverage" above) |
-| `systems-vocabulary`, `error-ref-wrong-kind-runsas`, `error-ref-unresolved-runsas`, `ref-target-type-list-heldby`, `error-ref-wrong-kind-heldby`, `error-ref-ambiguous-heldby`, `error-resource-residency-bad-value`, `error-app-two-builds`, `error-app-three-builds`, `error-app-build-beside-inherited`, `systems-grants-and-sources`, `error-ref-unresolved-grant-resource`, `error-ref-wrong-kind-grant-rdb-on-queue`, `error-ref-wrong-kind-source-rdb-on-document`, `error-ref-wrong-kind-grant-stream-on-other-system-queue`, `error-grant-crosses-system`, `error-runsas-other-system`, `error-duplicate-name-in-system`, `error-ref-ambiguous-heldby-bare-name`, `systems-rdb-with-search-copy` | [spec/metamodel-definitions.md](../spec/metamodel-definitions.md) (the systems vocabulary, ADR-0070: the reference facet's worked cases, including the target type list behind `@heldBy`, the closed `@residency` set, an app's one build, counting a build it inherits, the grants and their same-system rule, `@resource` on a source, and one name per type within a system) |
+| `systems-vocabulary`, `error-ref-wrong-kind-runsas`, `error-ref-unresolved-runsas`, `ref-target-type-list-heldby`, `error-ref-wrong-kind-heldby`, `error-ref-ambiguous-heldby`, `error-resource-residency-bad-value`, `error-app-two-builds`, `error-app-three-builds`, `error-app-build-beside-inherited`, `systems-grants-and-sources`, `error-ref-unresolved-grant-resource`, `error-ref-wrong-kind-grant-rdb-on-queue`, `error-ref-wrong-kind-source-rdb-on-document`, `error-ref-wrong-kind-grant-stream-on-other-system-queue`, `error-grant-crosses-system`, `error-runsas-other-system`, `error-duplicate-name-in-system`, `error-ref-ambiguous-heldby-bare-name`, `systems-rdb-with-search-copy`, `systems-role-grants-across-files`, `systems-document-only-lifecycle-inert`, `systems-sql-view-with-search-copy` | [spec/metamodel-definitions.md](../spec/metamodel-definitions.md) (the systems vocabulary, ADR-0070: the reference facet's worked cases, including the target type list behind `@heldBy`, the closed `@residency` set, an app's one build, counting a build it inherits, the grants and their same-system rule, `@resource` on a source, one name per type within a system, a role redeclared in a second file keeping every grant, a search copy beside a SQL view leaving its columns unchecked, and a lifecycle that stays inert when its entity has no relational source) |
| `reporting-*`, `error-dimension-*`, `error-measure-*`, `error-ratio-*`, `error-segment-*`, `error-report-*`, `error-relative-date-*` | [features/reporting.md](features/reporting.md) (the `dimension` / `measure` / `segment` / `object.report` vocabulary and its load-time rules; design in the [FR-044 spec](superpowers/specs/2026-10-02-fr-044-core-reporting-design.md)) |
| `rules-*`, `error-rules-*` | [features/business-rules.md](features/business-rules.md) (operations, permission names and lifecycles: the vocabulary and its load-time rules, ADR-0066; the `verify` gate has its own corpus, `rules-check-conformance/`) |
| `provider-extension-*`, `provider-custom-vocabulary-*` | [features/extending-with-providers.md](features/extending-with-providers.md) (a project's own provider: a new subtype plus attributes on an existing type load with it and are refused without it, every port writing the provider in its own language) |
@@ -961,7 +961,7 @@ shared input.
## Orphaned fixtures (tested but not yet documented)
-The fixtures in the nine corpora mapped above (metamodel 609 + yaml 19 + verify 45
+The fixtures in the nine corpora mapped above (metamodel 612 + yaml 19 + verify 45
+ render 26 + persistence 68 + api-contract 191 + source-resolution 30 + scope 10 +
dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the
`cube-model` corpus, `explorer-conformance` and `list-query-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining
diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json
index bc57bf491b..df66bfbe10 100644
--- a/examples/showcase/site-payload.json
+++ b/examples/showcase/site-payload.json
@@ -7,7 +7,7 @@
"metamodel": "1.4"
},
"counts": {
- "fixtures": 609,
+ "fixtures": 612,
"corpora": 49,
"baseTypes": 28
},
diff --git a/explorer-app/assets/explorer-app.js b/explorer-app/assets/explorer-app.js
index dd2a04d098..a2681492a9 100644
--- a/explorer-app/assets/explorer-app.js
+++ b/explorer-app/assets/explorer-app.js
@@ -265,5 +265,5 @@
`);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(`
`)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",`
`,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(`${tag}>`)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(`
-`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(`
`).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
`}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`
${cols.map((o)=>`
${this.link(from,o.id)}
`).join("")}
`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`
`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`
`,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
None.
');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
None.
')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
Not scanned.
');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
No prompt text was read.
':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
None.
':`
${items.map((i)=>`
${i}
`).join("")}
`}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found
No such page
${escapeHtml2(r.path)} is not a page of this model.
`,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="
No model yet
The explorer is waiting for the running application's docs view.
";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(`
`).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
`}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`
${cols.map((o)=>`
${this.link(from,o.id)}
`).join("")}
`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`
`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`
`,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
None.
');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
None.
')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
Not scanned.
');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
No prompt text was read.
':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
None.
':`
${items.map((i)=>`
${i}
`).join("")}
`}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found
No such page
${escapeHtml2(r.path)} is not a page of this model.
`,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="
No model yet
The explorer is waiting for the running application's docs view.
";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="
explorer-model.js did not load. Run meta gen to write it beside this page.
";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})();
diff --git a/server/csharp/MetaObjects.Codegen/InstanceArtifacts.cs b/server/csharp/MetaObjects.Codegen/InstanceArtifacts.cs
index 85caa83fbc..a0825611aa 100644
--- a/server/csharp/MetaObjects.Codegen/InstanceArtifacts.cs
+++ b/server/csharp/MetaObjects.Codegen/InstanceArtifacts.cs
@@ -60,8 +60,8 @@ public static bool EmitsInstanceArtifacts(MetaObject entity) =>
///
/// True iff is a record whose store MetaObjects does not
- /// manage: concrete, with a primary identity and no source.* at all, declared or
- /// inherited (a MongoDB collection, a Cassandra table, a Neo4j node, a remote API). It
+ /// manage: concrete, with a primary identity and no relational (source.rdb) source,
+ /// declared or inherited (a MongoDB collection, a Cassandra table, a Neo4j node, a remote API). It
/// gets no EF mapping, DbSet or routes (#248); the adopter owns the data access. It
/// keeps its wire contract, because the identity makes it addressable: the entity class
/// and the filter allowlist for the list endpoint the adopter writes.
@@ -69,13 +69,15 @@ public static bool EmitsInstanceArtifacts(MetaObject entity) =>
/// Keyed on the identity rather than the object subtype (#248): ADR-0028 forbids a value
/// object any identity. The projection exclusion is ADR-0028's own rule — a projection
/// is read-only because of its subtype. Mirrors TypeScript's isSourcelessEntity.
+ /// A source.document or source.search does not count: no generator writes
+ /// from one yet, so an object whose only sources are those keeps the sourceless output.
///
///
public static bool IsSourcelessEntity(MetaObject entity) =>
!entity.IsAbstract
&& entity.SubType != OBJECT_SUBTYPE_PROJECTION
&& entity.PrimaryIdentity() is not null
- && entity.Sources().Count == 0;
+ && !HasAnyRdbSource(entity);
///
/// #484 — a credential is a field that declares (or inherits, ADR-0039) a view.password child.
diff --git a/server/csharp/MetaObjects/Core/Transition/Lifecycle.cs b/server/csharp/MetaObjects/Core/Transition/Lifecycle.cs
index bef3eb2d6e..b2bcd9226a 100644
--- a/server/csharp/MetaObjects/Core/Transition/Lifecycle.cs
+++ b/server/csharp/MetaObjects/Core/Transition/Lifecycle.cs
@@ -44,10 +44,12 @@ public static class Lifecycles
public static IReadOnlyList TransitionsOf(MetaData field) =>
field.Children().Where(c => c.Type == TYPE_TRANSITION && c.SubType == TRANSITION_SUBTYPE_ACTION).ToList();
- /// Whether an entity's lifecycles are live: it declares or inherits a source. A lifecycle on an
- /// entity with no source loads and is inert (it derives no command); the writable-source check applies
- /// once a source is added (ADR-0066 section 2). Read through the resolving accessor.
- public static bool LifecycleIsLive(MetaData entity) => entity.Children().Any(c => c.Type == TYPE_SOURCE);
+ /// Whether an entity's lifecycles are live: it declares or inherits a relational (source.rdb)
+ /// source. A lifecycle on an entity with no relational source loads and is inert (it derives no command);
+ /// the writable-source check applies once a relational source is added (ADR-0066 section 2). A document
+ /// or search source alone does not make one live. Read through the resolving accessor.
+ public static bool LifecycleIsLive(MetaData entity) =>
+ entity.Children().Any(c => c.Type == TYPE_SOURCE && c.SubType == SOURCE_SUBTYPE_RDB);
/// An entity and every entity it extends, nearest first.
public static IReadOnlyList EntityLineage(MetaData entity)
diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs
index 99e11f7d59..6e27cc87fa 100644
--- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs
+++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs
@@ -5304,12 +5304,12 @@ public static MutabilityValidationResult ValidateFieldMutability(MetaData root)
}
/// True when no write path reaches this object: an object.projection, or
- /// an object whose every source is a read-only @kind.
+ /// an object whose every relational (source.rdb) source is a read-only @kind.
private static bool IsWriteHostReadOnly(MetaData obj)
{
if (obj.SubType == OBJECT_SUBTYPE_PROJECTION) return true;
// ADR-0039: resolving — a source may be inherited via extends.
- var sources = obj.Children().OfType().ToList();
+ var sources = obj.Children().OfType().Where(s => s.SubType == SOURCE_SUBTYPE_RDB).ToList();
return sources.Count > 0 && sources.All(src => src.IsReadOnly());
}
@@ -5676,7 +5676,9 @@ void Walk(MetaData node)
// fields are skipped. A flattened field.object contributes one column per member of its
// value object (PhysicalColumnsOf below); any other field.object is one jsonb column.
// ADR-0039: effective children, so an inherited field collides like an own one.
- // Exempt: an object whose every source is read-only and at least one is a
+ // Only relational (source.rdb) sources count: a document or search source has no columns,
+ // so an object with none is not checked.
+ // Exempt: an object whose every relational source is read-only and at least one is a
// source.rdb @kind: view with an @sql body. The author's SQL defines that view's columns
// and the fields only READ them, so two fields on one column create no duplicate column
// and nothing can be written. A derived view (no @sql) emits a select list from its
@@ -5684,7 +5686,7 @@ void Walk(MetaData node)
// MetaObjects creates; both stay checked.
private static bool ReadsThroughSqlView(MetaData obj)
{
- var sources = obj.Children().OfType().ToList();
+ var sources = obj.Children().OfType().Where(s => s.SubType == SOURCE_SUBTYPE_RDB).ToList();
return sources.All(s => s.IsReadOnly()) &&
sources.Any(s => s.EffectiveKind == SourceConstants.SOURCE_KIND_VIEW && s.SqlBody is not null);
}
@@ -5724,7 +5726,7 @@ public static IReadOnlyList ValidateColumnNameCollisions(MetaData roo
foreach (var obj in root.OwnChildren().Where(c => c.Type == TYPE_OBJECT))
{
if (obj.IsAbstract) continue;
- if (!obj.Children().Any(c => c.Type == TYPE_SOURCE)) continue;
+ if (!obj.Children().Any(c => c.Type == TYPE_SOURCE && c.SubType == SOURCE_SUBTYPE_RDB)) continue;
if (ReadsThroughSqlView(obj)) continue;
var seen = new Dictionary(StringComparer.Ordinal);
foreach (var field in obj.Children().OfType())
diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/ModelWalk.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/ModelWalk.java
index bd8ef87461..87ccdf6f3e 100644
--- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/ModelWalk.java
+++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/ModelWalk.java
@@ -136,10 +136,11 @@ public static List primaryKeyFields(MetaObject o) {
return out;
}
- /** True when the object declares or inherits a {@code source.*} — it is persisted and the
- * reference routes serve it. */
+ /** True when the object declares or inherits a relational ({@code source.rdb}) source — it
+ * is persisted and the reference routes serve it. A {@code source.document} or
+ * {@code source.search} alone does not count: no generator writes from one yet. */
public static boolean hasSource(MetaObject o) {
- return !o.getChildren(MetaSource.class, true).isEmpty();
+ return o.getChildren(MetaSource.class, true).stream().anyMatch(MetaSource::isRdb);
}
/** The cross-port REST collection segment the reference routes serve an object at
diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/RestSurfaceGate.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/RestSurfaceGate.java
index 76fbbcb499..a348d71f27 100644
--- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/RestSurfaceGate.java
+++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/RestSurfaceGate.java
@@ -194,8 +194,8 @@ public static boolean hasItemRoute(MetaObject obj) {
/**
* True iff {@code obj} is a record whose store MetaObjects does not manage: a concrete
- * object with a primary identity and no {@code source.*} at all, declared or inherited
- * (a MongoDB collection, a Cassandra table, a Neo4j node, a remote API). It gets NO REST
+ * object with a primary identity and no relational ({@code source.rdb}) source, declared or
+ * inherited (a MongoDB collection, a Cassandra table, a Neo4j node, a remote API). It gets NO REST
* surface (#248 — no controller or repository), but it keeps its wire contract, because
* the identity makes it addressable: the DTO, a {@code Patch} and the filter allowlist
* for the endpoint its adopter writes. Nothing generated references those, so the trio
@@ -204,7 +204,9 @@ public static boolean hasItemRoute(MetaObject obj) {
*
Keyed on the identity rather than the object subtype (#248): ADR-0028 forbids a
* value object any identity. The projection exclusion is ADR-0028's own rule — a
* projection is read-only because of its subtype. Mirrors TypeScript's
- * {@code isSourcelessEntity} and Python's {@code is_sourceless_entity}.
+ * {@code isSourcelessEntity} and Python's {@code is_sourceless_entity}. A
+ * {@code source.document} or {@code source.search} does not count: no generator writes from
+ * one yet, so an object whose only sources are those keeps the sourceless output.
*/
public static boolean isSourcelessEntity(MetaObject obj) {
if (GeneratorUtil.isAbstract(obj)) return false;
@@ -214,7 +216,7 @@ public static boolean isSourcelessEntity(MetaObject obj) {
for (MetaIdentity identity : obj.getIdentities(true)) {
if (identity.isPrimary()) { identified = true; break; }
}
- return identified && obj.getSources(true).isEmpty();
+ return identified && obj.getSources(true).stream().noneMatch(MetaSource::isRdb);
}
/**
diff --git a/server/java/codegen-base/src/main/resources/metaobjects/explorer-app/assets/explorer-app.js b/server/java/codegen-base/src/main/resources/metaobjects/explorer-app/assets/explorer-app.js
index dd2a04d098..a2681492a9 100644
--- a/server/java/codegen-base/src/main/resources/metaobjects/explorer-app/assets/explorer-app.js
+++ b/server/java/codegen-base/src/main/resources/metaobjects/explorer-app/assets/explorer-app.js
@@ -265,5 +265,5 @@
`);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(`
`)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",`
`,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(`${tag}>`)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(`
-`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(`
`).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
`}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`
${cols.map((o)=>`
${this.link(from,o.id)}
`).join("")}
`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`
`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`
`,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
None.
');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
None.
')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
Not scanned.
');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
No prompt text was read.
':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
None.
':`
${items.map((i)=>`
${i}
`).join("")}
`}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found
No such page
${escapeHtml2(r.path)} is not a page of this model.
`,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="
No model yet
The explorer is waiting for the running application's docs view.
";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(`
`).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
`}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`
${cols.map((o)=>`
${this.link(from,o.id)}
`).join("")}
`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`
`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`
`,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
None.
');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
None.
')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
Not scanned.
');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
No prompt text was read.
':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
None.
':`
${items.map((i)=>`
${i}
`).join("")}
`}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found
No such page
${escapeHtml2(r.path)} is not a page of this model.
`,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="
No model yet
The explorer is waiting for the running application's docs view.
";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="
explorer-model.js did not load. Run meta gen to write it beside this page.
";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})();
diff --git a/server/python/src/metaobjects/loader/merge.py b/server/python/src/metaobjects/loader/merge.py
index 9ab28cfb34..a981da2777 100644
--- a/server/python/src/metaobjects/loader/merge.py
+++ b/server/python/src/metaobjects/loader/merge.py
@@ -126,6 +126,8 @@ def _find_merge_match(target: MetaData, sc: MetaData) -> Optional[MetaData]:
Nested children stay bare-name matched — they are scoped by their parent, and
packages don't disambiguate siblings inside a node.
"""
+ if not sc.name:
+ return None
is_root = target.parent is None
def scan() -> Optional[MetaData]:
@@ -192,7 +194,7 @@ def _merge_child_into(
return
tc = _find_merge_match(target, sc)
- if tc is not None and sc.name and tc.sub_type != sc.sub_type and target.type == TYPE_SYSTEM:
+ if tc is not None and tc.sub_type != sc.sub_type and target.type == TYPE_SYSTEM:
# Inside a system a name is used once per type (ADR-0070,
# spec/metamodel-definitions.md): a same-subtype redeclaration merges, one of
# another subtype is refused rather than folded into the first silently.
diff --git a/server/python/src/metaobjects/loader/validate_field_mutability.py b/server/python/src/metaobjects/loader/validate_field_mutability.py
index 6520111da3..c2fa7ca9d3 100644
--- a/server/python/src/metaobjects/loader/validate_field_mutability.py
+++ b/server/python/src/metaobjects/loader/validate_field_mutability.py
@@ -49,6 +49,7 @@
OBJECT_SUBTYPE_PROJECTION,
OBJECT_SUBTYPE_VALUE,
)
+from ..meta.persistence.source.source_constants import SOURCE_SUBTYPE_RDB
from ..shared.base_types import TYPE_FIELD, TYPE_IDENTITY, TYPE_OBJECT, TYPE_SOURCE
from ..source.error_source import LoaderWarning
@@ -101,11 +102,11 @@ def _rank(mode: str) -> int:
def _write_host_is_read_only(obj: MetaData) -> bool:
"""True when no write path reaches this object: an ``object.projection``, or
- an object whose every source is a read-only ``@kind``."""
+ an object whose every relational (``source.rdb``) source is a read-only ``@kind``."""
if obj.sub_type == OBJECT_SUBTYPE_PROJECTION:
return True
# ADR-0039: resolving — a source may be inherited via extends.
- sources = [c for c in obj.children() if c.type == TYPE_SOURCE]
+ sources = [c for c in obj.children() if c.type == TYPE_SOURCE and c.sub_type == SOURCE_SUBTYPE_RDB]
if not sources:
return False
return all(getattr(src, "is_read_only", lambda: False)() for src in sources)
diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py
index 58626570c0..ac1c0983ef 100644
--- a/server/python/src/metaobjects/loader/validation_passes.py
+++ b/server/python/src/metaobjects/loader/validation_passes.py
@@ -5884,7 +5884,10 @@ def _validate_column_name_collisions(root: MetaData, errors: list[MetaError]) ->
other ``field.object`` is one column under its own resolved name.
ADR-0039: effective children (inherited fields count).
- Exempt: an object whose every source is read-only and at least one is a
+ Only relational (``source.rdb``) sources count: a document or search source has no
+ columns, so an object with none is not checked.
+
+ Exempt: an object whose every relational source is read-only and at least one is a
``source.rdb @kind: view`` with an ``@sql`` body. The author's SQL defines that view's
columns and the fields only READ them, so two fields on one column create no duplicate
column and nothing can be written. A derived view (no ``@sql``) emits a select list
@@ -5895,9 +5898,9 @@ def _validate_column_name_collisions(root: MetaData, errors: list[MetaError]) ->
for obj in (c for c in root.children() if c.type == TYPE_OBJECT):
if obj.is_abstract:
continue
- if not any(c.type == TYPE_SOURCE for c in obj.children()):
+ sources = [c for c in obj.children() if isinstance(c, MetaSource) and c.sub_type == SOURCE_SUBTYPE_RDB]
+ if not sources:
continue
- sources = [c for c in obj.children() if isinstance(c, MetaSource)]
if all(s.is_read_only() for s in sources) and any(
s.effective_kind() == SOURCE_KIND_VIEW and s.sql_body() is not None
for s in sources
diff --git a/server/python/src/metaobjects/meta/core/transition/lifecycle.py b/server/python/src/metaobjects/meta/core/transition/lifecycle.py
index 421209a54e..3de2e9ef49 100644
--- a/server/python/src/metaobjects/meta/core/transition/lifecycle.py
+++ b/server/python/src/metaobjects/meta/core/transition/lifecycle.py
@@ -35,6 +35,7 @@
OBJECT_SUBTYPE_PROJECTION,
OBJECT_SUBTYPE_VALUE,
)
+from ...persistence.source.source_constants import SOURCE_SUBTYPE_RDB
from .transition_constants import TRANSITION_ATTR_FROM, TRANSITION_ATTR_TO, TRANSITION_SUBTYPE_ACTION
@@ -116,10 +117,11 @@ def lifecycles_of(obj: MetaData) -> list[Lifecycle]:
def lifecycle_is_live(entity: MetaData) -> bool:
- """Whether an entity's lifecycles are live: it declares or inherits a source (RESOLVING
- ``children()``, ADR-0039). A lifecycle on an entity with no source loads and is inert: it
- derives no command (ADR-0066 section 2)."""
- return any(c.type == TYPE_SOURCE for c in entity.children())
+ """Whether an entity's lifecycles are live: it declares or inherits a relational
+ (``source.rdb``) source (RESOLVING ``children()``, ADR-0039). A lifecycle on an entity with no
+ relational source loads and is inert: it derives no command (ADR-0066 section 2). A document
+ or search source alone does not make one live."""
+ return any(c.type == TYPE_SOURCE and c.sub_type == SOURCE_SUBTYPE_RDB for c in entity.children())
def entity_transitions(obj: MetaData) -> list[MetaData]:
diff --git a/server/python/tests/codegen/test_sourceless_entity_surface.py b/server/python/tests/codegen/test_sourceless_entity_surface.py
index d8b3166854..5a86cd475b 100644
--- a/server/python/tests/codegen/test_sourceless_entity_surface.py
+++ b/server/python/tests/codegen/test_sourceless_entity_surface.py
@@ -72,3 +72,33 @@ def test_sourceless_entity_gets_create_and_patch_models() -> None:
order = next(c for p, c in files.items() if p.endswith("Order.py"))
assert "class OrderCreate(BaseModel)" in order
assert "class OrderPatch(BaseModel)" in order
+
+
+def _objects_with(source: dict) -> dict[str, MetaObject]:
+ model = json.loads(json.dumps(MODEL))
+ children = model["metadata.root"]["children"]
+ children.insert(0, {"system.software": {"name": "Shop", "children": [
+ {"resource.document": {"name": "docs"}},
+ {"resource.search": {"name": "search"}},
+ ]}})
+ order = next(c["object.entity"] for c in children if c.get("object.entity", {}).get("name") == "Order")
+ order["children"].insert(0, source)
+ result = MetaDataLoader().load(
+ [InMemoryStringSource(json.dumps(model), id="m.json", format=MetaDataFormat.JSON)]
+ )
+ assert not result.errors, result.errors
+ return {o.name: o for o in result.root.own_children() if isinstance(o, MetaObject)}
+
+
+def test_document_or_search_source_removes_no_generated_output() -> None:
+ """No generator writes from a source.document or source.search yet, so an entity whose
+ only source is one of those keeps exactly the output it has with no source."""
+ baseline = _objects()["Order"]
+ for source in (
+ {"source.document": {"@resource": "Shop.docs", "@collection": "orders"}},
+ {"source.search": {"@resource": "Shop.search", "@index": "orders"}},
+ ):
+ order = _objects_with(source)["Order"]
+ assert is_sourceless_entity(order) is True
+ assert render_router(order) is None
+ assert render_filter_allowlist(order) == render_filter_allowlist(baseline)
diff --git a/server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js b/server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js
index dd2a04d098..a2681492a9 100644
--- a/server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js
+++ b/server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js
@@ -265,5 +265,5 @@
`);for(var i=0;i0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(`
`)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",`
`,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(`${tag}>`)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(`
-`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(`
`).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
`}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join(" "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`
${cols.map((o)=>`
${this.link(from,o.id)}
`).join("")}
`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`
`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`
`,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
None.
');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
None.
')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
Not scanned.
');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
No prompt text was read.
':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
None.
':`
${items.map((i)=>`
${i}
`).join("")}
`}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found
No such page
${escapeHtml2(r.path)} is not a page of this model.
`,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="
No model yet
The explorer is waiting for the running application's docs view.
";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="
explorer-model.js did not load. Run meta gen to write it beside this page.
";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})();
diff --git a/server/rust/metaobjects/src/rules_check.rs b/server/rust/metaobjects/src/rules_check.rs
index f756850c0e..c0c0c30436 100644
--- a/server/rust/metaobjects/src/rules_check.rs
+++ b/server/rust/metaobjects/src/rules_check.rs
@@ -56,7 +56,6 @@ pub const WARN_DERIVED_COMMAND_BYPASSES_DECLARED: &str = "WARN_DERIVED_COMMAND_B
const T_API: &str = "api";
const T_OPERATION: &str = "operation";
-const T_SOURCE: &str = "source";
const SUB_ENTITY: &str = "entity";
const SUB_ENUM: &str = "enum";
const SUB_COMMAND: &str = "command";
@@ -239,12 +238,13 @@ fn declared_lifecycles<'a>(tree: &'a Tree, root: NodeId) -> Vec> {
out
}
-/// Whether an entity's lifecycles are live: it declares or inherits a source. A lifecycle on
-/// an entity with no source loads and is inert: it derives no command.
+/// Whether an entity's lifecycles are live: it declares or inherits a relational
+/// (`source.rdb`) source. A lifecycle on an entity with no relational source loads and is
+/// inert: it derives no command. A document or search source alone does not make one live.
pub(crate) fn lifecycle_is_live(tree: &Tree, entity: NodeId) -> bool {
tree.children(entity)
.iter()
- .any(|&c| tree.node(c).type_name == T_SOURCE)
+ .any(|&c| crate::naming::is_rdb_source(tree, c))
}
pub(crate) fn transition_from(tree: &Tree, t: NodeId) -> Vec<&str> {
diff --git a/server/rust/metaobjects/src/validate/field_policy.rs b/server/rust/metaobjects/src/validate/field_policy.rs
index 6433b95ebf..b84e9333f3 100644
--- a/server/rust/metaobjects/src/validate/field_policy.rs
+++ b/server/rust/metaobjects/src/validate/field_policy.rs
@@ -21,7 +21,6 @@ pub const ERR_READONLY_ASSIGNED_PRIMARY: &str = "ERR_READONLY_ASSIGNED_PRIMARY";
const TYPE_OBJECT: &str = "object";
const TYPE_FIELD: &str = "field";
const TYPE_IDENTITY: &str = "identity";
-const TYPE_SOURCE: &str = "source";
const SUB_ENUM: &str = "enum";
const SUB_VALUE: &str = "value";
const SUB_PROJECTION: &str = "projection";
@@ -215,7 +214,7 @@ fn write_host_read_only(ctx: &Ctx<'_>, obj: NodeId) -> bool {
.children(obj)
.iter()
.copied()
- .filter(|&c| tree.node(c).type_name == TYPE_SOURCE)
+ .filter(|&c| crate::naming::is_rdb_source(tree, c))
.collect();
!sources.is_empty()
&& sources.iter().all(|&s| {
diff --git a/server/rust/metaobjects/src/validate/persistence.rs b/server/rust/metaobjects/src/validate/persistence.rs
index 4fcb32dd03..0c46c65b72 100644
--- a/server/rust/metaobjects/src/validate/persistence.rs
+++ b/server/rust/metaobjects/src/validate/persistence.rs
@@ -412,7 +412,7 @@ pub fn validate_column_name_collisions(ctx: &Ctx<'_>, out: &mut Findings) {
let mut has_source = false;
let (mut all_read_only, mut sql_view) = (true, false);
for &c in kids.iter() {
- if tree.node(c).type_name == TYPE_SOURCE {
+ if crate::naming::is_rdb_source(tree, c) {
has_source = true;
all_read_only &= is_read_only(tree, c);
sql_view |= effective_kind(tree, c) == KIND_VIEW && sql_body_set(tree, c);
diff --git a/server/rust/metaobjects/src/validate/rules.rs b/server/rust/metaobjects/src/validate/rules.rs
index 35a6753ed4..bfa8773398 100644
--- a/server/rust/metaobjects/src/validate/rules.rs
+++ b/server/rust/metaobjects/src/validate/rules.rs
@@ -79,7 +79,6 @@ const T_API: &str = "api";
const T_OPERATION: &str = "operation";
const T_BINDING: &str = "binding";
const T_TRANSITION: &str = "transition";
-const T_SOURCE: &str = "source";
const T_IDENTITY: &str = "identity";
const SUB_ENTITY: &str = "entity";
@@ -760,9 +759,9 @@ fn check_entity_lifecycles(tree: &Tree, entity: NodeId, sink: &mut Sink<'_>) {
}
}
let kids = tree.children(entity);
- // A lifecycle is live once the entity declares or inherits a source. With no source
- // at all it loads and is inert, like everything else on a sourceless entity.
- let live = kids.iter().any(|&c| tree.node(c).type_name == T_SOURCE);
+ // A lifecycle is live once the entity declares or inherits a relational source. With no
+ // source.rdb it loads and is inert, like everything else on a sourceless entity.
+ let live = kids.iter().any(|&c| crate::naming::is_rdb_source(tree, c));
if !enode.is_abstract && live && !kids.iter().any(|&c| is_writable_source(tree, c)) {
let fields = unique(transitions.iter().map(|&t| {
tree.node(t)
@@ -1169,7 +1168,7 @@ fn check_permission_names(ctx: &Ctx<'_>, top_level: &[NodeId], sink: &mut Sink<'
if !tree
.children(entity)
.iter()
- .any(|&c| tree.node(c).type_name == T_SOURCE)
+ .any(|&c| crate::naming::is_rdb_source(tree, c))
{
continue;
}
diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json
index da3c8d55ff..947a6c9dae 100644
--- a/server/rust/metaobjects/tests/conformance-expected-failures.json
+++ b/server/rust/metaobjects/tests/conformance-expected-failures.json
@@ -1,6 +1,6 @@
{
"language": "rust",
"notes": "The Rust port passes every fixture of the shared metamodel corpus, so the ledger is empty. The ledger may only shrink and is kept for the day a new fixture lands that Rust does not pass yet: list it here with the reason, and it leaves when the work that covers it lands. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.",
- "minPassing": 609,
+ "minPassing": 612,
"fixtures": []
}
diff --git a/server/typescript/packages/codegen-ts/src/source-detect.ts b/server/typescript/packages/codegen-ts/src/source-detect.ts
index 23df48489e..5fb0245f87 100644
--- a/server/typescript/packages/codegen-ts/src/source-detect.ts
+++ b/server/typescript/packages/codegen-ts/src/source-detect.ts
@@ -18,7 +18,6 @@ import {
OBJECT_SUBTYPE_PROJECTION,
OBJECT_SUBTYPE_REPORT,
SOURCE_KIND_VIEW,
- isMetaSource,
isRdbSource,
isWritableSource,
reportReadModel,
@@ -63,7 +62,7 @@ export function hasAnyRdbSource(entity: MetaObject): boolean {
/**
* True for a record whose store MetaObjects does not manage: a concrete object with a primary
- * identity and no `source.*` at all, declared or inherited. A MongoDB collection, a Cassandra
+ * identity and no relational source (`source.rdb`), declared or inherited. A MongoDB collection, a Cassandra
* table, a Neo4j node or a remote API is modelled this way. #248 gives it no table, queries,
* routes or migration; the adopter owns its data access.
*
@@ -76,12 +75,15 @@ export function hasAnyRdbSource(entity: MetaObject): boolean {
* construction. The one subtype read is the projection exclusion, and it is ADR-0028's own
* rule: a projection is read-only because of its subtype, so it has no PATCH surface even when
* it borrows an identity.
+ *
+ * A `source.document` or `source.search` does not count: no generator writes from one yet, so
+ * an object whose only sources are those keeps the same output as one with no source.
*/
export function isSourcelessEntity(obj: MetaObject): boolean {
if (obj.isAbstract === true || obj.subType === OBJECT_SUBTYPE_PROJECTION) return false;
if (obj.primaryIdentity() === undefined) return false;
- // ADR-0039: resolving — a source inherited through extends makes the object persistable.
- return !obj.children().some(isMetaSource);
+ // ADR-0039: resolving — a source.rdb inherited through extends makes the object persistable.
+ return !obj.children().some(isRdbSource);
}
/**
diff --git a/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts b/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts
index f30c03e459..dda8d09c1e 100644
--- a/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts
+++ b/server/typescript/packages/codegen-ts/test/sourceless-entity-surface.test.ts
@@ -64,16 +64,32 @@ const MODEL = {
},
};
-async function loadRoot() {
- const result = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(MODEL))]);
+// The same model with the Order backed by a document or search store of a system: no generator
+// writes from a source.document or source.search yet, so the Order keeps its sourceless output.
+function withNonRdbSource(source: Record): typeof MODEL {
+ const model = structuredClone(MODEL) as { "metadata.root": { children: Record[] } };
+ const children = model["metadata.root"].children;
+ children.unshift({
+ "system.software": {
+ children: [{ "resource.document": { name: "docs" } }, { "resource.search": { name: "search" } }],
+ name: "Shop",
+ } as never,
+ });
+ const order = children.find((c) => c["object.entity"] !== undefined)!["object.entity"]!;
+ order.children!.unshift(source);
+ return model as unknown as typeof MODEL;
+}
+
+async function loadRoot(model: object = MODEL) {
+ const result = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(model))]);
if (result.errors.length > 0) {
throw new Error(`Loader errors:\n${result.errors.map((e) => e.message).join("\n")}`);
}
return result.root;
}
-async function generate(dir: string): Promise