From 2b539bfbc056f766c5e79be26eff0559a2407365 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 20 Nov 2026 00:27:44 -0500 Subject: [PATCH 1/3] fix(rust): make the metaobjects crate package and build on its own The crate embedded the metamodel JSON, the shared error catalogue and the shipped libraries from outside its directory, so the packaged tarball did not compile (and would have embedded no libraries). Vendor them under data/ with a byte-parity test against the source copies, and give the codegen and cli path dependencies a version requirement so they can be packaged once metaobjects is on crates.io. --- server/rust/metaobjects-cli/Cargo.toml | 4 +- server/rust/metaobjects-codegen/Cargo.toml | 2 +- server/rust/metaobjects/build.rs | 2 +- server/rust/metaobjects/data/ERROR-CODES.json | 131 ++++++++ .../rust/metaobjects/data/library/ai/db.yaml | 16 + .../metaobjects/data/library/ai/library.json | 20 ++ .../metaobjects/data/library/ai/model.yaml | 44 +++ .../data/library/ai/requirements.yaml | 112 +++++++ .../rust/metaobjects/data/library/iam/db.yaml | 81 +++++ .../metaobjects/data/library/iam/library.json | 16 + .../metaobjects/data/library/iam/model.yaml | 157 +++++++++ .../data/library/iam/requirements.yaml | 156 +++++++++ .../rust/metaobjects/data/metamodel/api.json | 73 +++++ .../rust/metaobjects/data/metamodel/attr.json | 71 ++++ .../rust/metaobjects/data/metamodel/db.json | 106 ++++++ .../data/metamodel/documentation.json | 78 +++++ .../metaobjects/data/metamodel/field.json | 199 +++++++++++ .../metaobjects/data/metamodel/identity.json | 37 +++ .../metaobjects/data/metamodel/index.json | 14 + .../metaobjects/data/metamodel/layout.json | 15 + .../metaobjects/data/metamodel/object.json | 81 +++++ .../metaobjects/data/metamodel/origin.json | 74 +++++ .../metaobjects/data/metamodel/prompt.json | 99 ++++++ .../data/metamodel/relationship.json | 68 ++++ .../metaobjects/data/metamodel/reporting.json | 51 +++ .../data/metamodel/requirement.json | 189 +++++++++++ .../metaobjects/data/metamodel/source.json | 17 + .../metaobjects/data/metamodel/template.json | 308 ++++++++++++++++++ .../data/metamodel/transition.json | 27 ++ .../metaobjects/data/metamodel/ui-web.json | 21 ++ .../rust/metaobjects/data/metamodel/ui.json | 34 ++ .../metaobjects/data/metamodel/validator.json | 122 +++++++ .../rust/metaobjects/data/metamodel/view.json | 88 +++++ server/rust/metaobjects/src/errors.rs | 2 +- server/rust/metaobjects/src/providers.rs | 2 +- server/rust/metaobjects/src/validate/attrs.rs | 2 +- server/rust/metaobjects/src/validate/field.rs | 2 +- .../metaobjects/src/validate/field_expr.rs | 2 +- .../metaobjects/src/validate/field_policy.rs | 2 +- .../rust/metaobjects/src/validate/origin.rs | 2 +- .../metaobjects/src/validate/persistence.rs | 2 +- .../rust/metaobjects/src/validate/prompt.rs | 6 +- server/rust/metaobjects/src/validate/refs.rs | 2 +- .../metaobjects/src/validate/relationships.rs | 2 +- .../metaobjects/src/validate/reporting.rs | 2 +- server/rust/metaobjects/src/validate/rules.rs | 2 +- .../metaobjects/src/validate/structure.rs | 2 +- .../metaobjects/tests/vendored_data_parity.rs | 69 ++++ 48 files changed, 2593 insertions(+), 21 deletions(-) create mode 100644 server/rust/metaobjects/data/ERROR-CODES.json create mode 100644 server/rust/metaobjects/data/library/ai/db.yaml create mode 100644 server/rust/metaobjects/data/library/ai/library.json create mode 100644 server/rust/metaobjects/data/library/ai/model.yaml create mode 100644 server/rust/metaobjects/data/library/ai/requirements.yaml create mode 100644 server/rust/metaobjects/data/library/iam/db.yaml create mode 100644 server/rust/metaobjects/data/library/iam/library.json create mode 100644 server/rust/metaobjects/data/library/iam/model.yaml create mode 100644 server/rust/metaobjects/data/library/iam/requirements.yaml create mode 100644 server/rust/metaobjects/data/metamodel/api.json create mode 100644 server/rust/metaobjects/data/metamodel/attr.json create mode 100644 server/rust/metaobjects/data/metamodel/db.json create mode 100644 server/rust/metaobjects/data/metamodel/documentation.json create mode 100644 server/rust/metaobjects/data/metamodel/field.json create mode 100644 server/rust/metaobjects/data/metamodel/identity.json create mode 100644 server/rust/metaobjects/data/metamodel/index.json create mode 100644 server/rust/metaobjects/data/metamodel/layout.json create mode 100644 server/rust/metaobjects/data/metamodel/object.json create mode 100644 server/rust/metaobjects/data/metamodel/origin.json create mode 100644 server/rust/metaobjects/data/metamodel/prompt.json create mode 100644 server/rust/metaobjects/data/metamodel/relationship.json create mode 100644 server/rust/metaobjects/data/metamodel/reporting.json create mode 100644 server/rust/metaobjects/data/metamodel/requirement.json create mode 100644 server/rust/metaobjects/data/metamodel/source.json create mode 100644 server/rust/metaobjects/data/metamodel/template.json create mode 100644 server/rust/metaobjects/data/metamodel/transition.json create mode 100644 server/rust/metaobjects/data/metamodel/ui-web.json create mode 100644 server/rust/metaobjects/data/metamodel/ui.json create mode 100644 server/rust/metaobjects/data/metamodel/validator.json create mode 100644 server/rust/metaobjects/data/metamodel/view.json create mode 100644 server/rust/metaobjects/tests/vendored_data_parity.rs diff --git a/server/rust/metaobjects-cli/Cargo.toml b/server/rust/metaobjects-cli/Cargo.toml index 256bbdd79b..4646cd99c5 100644 --- a/server/rust/metaobjects-cli/Cargo.toml +++ b/server/rust/metaobjects-cli/Cargo.toml @@ -20,8 +20,8 @@ name = "cargo-meta" path = "src/main.rs" [dependencies] -metaobjects = { path = "../metaobjects" } -metaobjects-codegen = { path = "../metaobjects-codegen" } +metaobjects = { path = "../metaobjects", version = "0.1.0" } +metaobjects-codegen = { path = "../metaobjects-codegen", version = "0.1.0" } [dev-dependencies] serde_json.workspace = true diff --git a/server/rust/metaobjects-codegen/Cargo.toml b/server/rust/metaobjects-codegen/Cargo.toml index 529f13b528..bbaa36a98d 100644 --- a/server/rust/metaobjects-codegen/Cargo.toml +++ b/server/rust/metaobjects-codegen/Cargo.toml @@ -11,7 +11,7 @@ publish = false build = "build.rs" [dependencies] -metaobjects = { path = "../metaobjects" } +metaobjects = { path = "../metaobjects", version = "0.1.0" } serde_json.workspace = true indexmap.workspace = true serde.workspace = true diff --git a/server/rust/metaobjects/build.rs b/server/rust/metaobjects/build.rs index 68b9e98c8b..a162e46d94 100644 --- a/server/rust/metaobjects/build.rs +++ b/server/rust/metaobjects/build.rs @@ -36,7 +36,7 @@ fn collect( fn main() { let manifest_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR")); - let lib_dir = manifest_dir.join("../../../library"); + let lib_dir = manifest_dir.join("data/library"); println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed={}", lib_dir.display()); let (mut yaml, mut manifests) = (Vec::new(), Vec::new()); diff --git a/server/rust/metaobjects/data/ERROR-CODES.json b/server/rust/metaobjects/data/ERROR-CODES.json new file mode 100644 index 0000000000..757bc735b6 --- /dev/null +++ b/server/rust/metaobjects/data/ERROR-CODES.json @@ -0,0 +1,131 @@ +{ + "version": 1, + "codes": { + "ERR_MALFORMED_JSON": "The input is not valid JSON (parse failure before structural checks).", + "ERR_TOP_LEVEL_NOT_OBJECT": "The metadata document root is not a JSON object.", + "ERR_UNKNOWN_TYPE": "A node uses a type not registered in the registry.", + "ERR_CHILD_NOT_OBJECT": "A child wrapper's body is not a JSON object. Every child in a `children` array is one `{ \".\": { …node body… } }` pair; a string, number, boolean, array or null body carries no node to read. Reported AFTER the wrapper key's type resolves, so a bad key is still diagnosed as a bad key (ERR_UNKNOWN_TYPE / ERR_UNKNOWN_SUBTYPE / ERR_MISSING_SUBTYPE) rather than as a body-shape problem. Distinct from ERR_TOP_LEVEL_NOT_OBJECT, which is about the DOCUMENT root.", + "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_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.", + "ERR_TOO_MANY_OCCURRENCES": "A type.subType declared with maxOccurs (e.g. identity.primary, maxOccurs:1) appears more times than allowed under one parent.", + "ERR_PROJECTION_IDENTITY_NOT_EXTENDED": "FR-024: an identity.* on an object.projection lacks extends — a projection identity is a pass-through of an entity identity.", + "ERR_IDENTITY_KEY_MISMATCH": "FR-024: identity key correspondence broken — an extended-identity field has no local pass-through field extending it, or an explicit @fields disagrees with the computed pass-through key.", + "ERR_PROJECTION_SOURCE_WRITABLE": "FR-024 (ADR-0028): a source.* on an object.projection has a writable @kind (table, or @kind omitted which defaults to table) — a projection is a derived read-only representation; its sources must be read-only kinds (view, materializedView, storedProc, tableFunction).", + "ERR_PROJECTION_INHERITED_SOURCE": "FR-024 (ADR-0028): a concrete object.projection inherits a source.* through extends instead of declaring its own. A projection's extends is shape lineage, not a shared-storage hierarchy: extends only ADDS members, so the child's extra fields have no provider in the parent's view, and two objects would claim one physical view with different declared exposures. Declare the source on the concrete projection; an abstract projection base carries shape only.", + "ERR_INVALID_SUBTYPE_CHILD": "A child node type/subType is not permitted under its parent.", + "ERR_CHILD_NOT_ALLOWED": "FR-033: a structural child (field/identity/source/validator/… — not an attr) is placed under a parent whose registered childRules do not admit it (the structural analogue of ERR_UNKNOWN_ATTR). Strict-load only; a no-op under wildcard childRules. The detail names the parent, the child (type.subType 'name'), and which placement was rejected.", + "ERR_COLLECTION_NOT_FOUND": "Phase-1 metadata-source-resolution: no metadata collection was discovered — no config declaring sources, and no default metaobjects/ directory.", + "ERR_UNKNOWN_ATTR": "An attribute name is not declared on the node's type.", + "ERR_MISSING_REQUIRED_ATTR": "A required attribute is absent from the node.", + "ERR_BAD_ATTR_VALUE": "An attribute value fails its declared schema (type/range).", + "ERR_BAD_DEFAULT_SORT_FIELD": "A layout @defaultSortField names a field absent from the entity.", + "ERR_PROVIDER_DEPENDENCY_CYCLE": "Provider composition has a dependency cycle.", + "ERR_PROVIDER_DUPLICATE_ID": "Two providers in a composition share the same id.", + "ERR_PROVIDER_MISSING_DEPENDENCY": "A provider declares a dependency id with no matching provider.", + "ERR_PROVIDER_ATTR_CONFLICT": "A provider extend redefines an attr another provider already declared, or a provider registers a common attr whose name another provider holds as a common attr or on any type, or the reverse (ADR-0062).", + "ERR_PROVIDER_ATTR_SHADOW": "A provider declares an attribute name on a type that another provider already declares on a related slot: the type it inherits from (.base), or a subtype that inherits from it (ADR-0062). Two providers may not claim one attribute name on a node type; the second needs its own idiomatic name. The same provider re-declaring its own attribute stays legal.", + "ERR_EXTEND_REQUIRED_ATTR": "A provider tried to project a REQUIRED attribute onto a type it does not own (via extends). Projection is optional-only: a required attr registered this way disappears silently whenever that provider is composed out, taking its validation rule with it. Declare it with the type instead (ADR-0050).", + "ERR_SUBTYPE_RULE_VIOLATION": "A node violates a subtype composition rule (e.g. a value object with an identity or a source — FR-024 value purity; a projection extending a non-projection — FR-024/ADR-0028).", + "ERR_OVERLAY_NO_TARGET": "An overlay node has no existing target to merge into.", + "ERR_MALFORMED_YAML": "The YAML metadata input is not valid YAML, or cannot be desugared into canonical metadata.", + "ERR_INVALID_ORIGIN": "A field origin declares an invalid path or attribute. Covers passthrough/aggregate path + attribute violations, and (post-#195) origin.computed @expr op-legality/inference failures (e.g. an op illegal for an operand subtype, or a field ref that does not resolve on the derived base entity) and every origin.first rule (missing/unresolvable @of or @orderBy, @of type-preservation, first-on-@required). The dedicated computed codes ERR_UNKNOWN_EXPR_NODE (unknown @expr node/op/fn) and ERR_COMPUTED_TYPE_MISMATCH (@expr root type != field subType) are raised separately.", + "ERR_AMBIGUOUS_PATH": "FR-024 (ADR-0029): an implicit (omitted-@via) origin path is ambiguous — more than one single-hop relationship leads from the base entity to the @from/@of entity (the error names the candidates), or a projection's base entity cannot be derived because its fields extend multiple entities and no extended identity anchors the base.", + "ERR_ORIGIN_CARDINALITY": "FR-024 (ADR-0029): origin cardinality contract broken — a passthrough @via path crosses a to-many hop (row-multiplying passthrough — you meant aggregate), or an aggregate @via path is to-one at every hop (aggregating over a to-one path — you meant passthrough). Checked on explicit AND inferred paths.", + "ERR_EXTENDS_ORIGIN_MISMATCH": "FR-024 (ADR-0029 decision 7): a field declares both an entity-nested extends (shape lineage) and an origin.passthrough @from (data lineage) and they disagree — the resolved @from target is not the field's resolved extends target (nor anywhere on its extends chain). Host-agnostic (projections, entities, values). origin.aggregate is never judged (it computes something new); a top-level abstract extends target is never judged (shape-only reuse makes no lineage claim).", + "ERR_PASSTHROUGH_TYPE_MISMATCH": "#185: a field carrying origin.passthrough @from: \"Entity.field\" declares a field. or array-ness that differs from its resolved source field — a passthrough forwards the value unchanged, so its type must be identical. Host-agnostic (projections, entities, values, stored-proc parameter refs). Nullability is NOT judged (a view over an outer join legitimately widens NOT NULL → nullable). Opt out of a deliberate type change with @convert: true on the origin.passthrough (an acknowledgement — it does not generate a cast); real type-converting projections are origin.expression's job (#159).", + "ERR_DERIVED_FIELD_NO_READ_SOURCE": "FR-024 (spec §7): an object.entity field carrying an origin.* child is derived (read-only) and must be providable — the entity must declare at least one source with a read-only @kind (view/materializedView/storedProc/tableFunction, e.g. a @role replica view beside the table primary). Table-only or source-less entities with origin-bearing fields error on the field. Projections and object.value hosts are exempt. Until the Phase-E B4b cutover removes view-primary entities, a read-only-kind PRIMARY source also counts as providable (legacy spelling).", + "ERR_COLUMN_NAME_COLLISION": "Two fields of one stored object (a concrete object declaring a source) resolve to the same physical column name: snake_case folds `userId` and `userID` into `user_id`, or two fields share an explicit @column. Only RESOLVED physical names are compared (explicit @column honoured, inherited fields included, derived and source-less objects exempt, and so is an object whose every source is read-only and at least one is a `@sql` view, since the author's SQL defines those columns). The message names both fields and the column.", + "ERR_INVALID_TEMPLATE": "A template (prompt/output) declares a @payloadRef that does not resolve, or @requiredSlots that are not fields on its payload.", + "ERR_INVALID_RELATIONSHIP": "FR-017: a M:N relationship's slim vocabulary is invalid — @through does not resolve to a junction declaring two identity.reference children (ADR-0042: @through resolves package-locally when bare, exactly when FQN — a bare cross-package @through no longer binds elsewhere), @sourceRefField does not match one of them, or a M:N-only attr (@through/@sourceRefField/@symmetric) is set on a non-M:N (1:N / @cardinality:one) relationship; OR a relationship's @objectRef does not resolve to any object in the loaded tree (a dangling target).", + "ERR_INVALID_REFERENCE": "An identity.reference @references names an FK target object that does not resolve to any object in the loaded tree (a dangling cross-reference between metadata).", + "ERR_VAR_NOT_ON_PAYLOAD": "Build-time verify: a template variable references a field the (contextual) payload view-object does not declare.", + "ERR_PAYLOAD_NAME_COLLISION": "Codegen (ADR-0044): no port raises it since 1.3.0, because a value object is never renamed (ADR-0044 Amendment 1, ADR-0056 Amendment 2); a short-name clash is the port-local ERR_NAME_COLLISION instead. Kept in the ledger so code that matches on it still compiles. Before 1.3.0: two distinct value-object FQNs in one payload artifact's reference closure derived the same emitted payload record name even after package-qualification.", + "ERR_COLLECTION_NAME_COLLISION": "Codegen: two distinct entities/projections in one generation run take the same API-surface collection name (REST path, generated hook/query/finder/list names, DbSet/collection variable name), after `@collectionName` and the `naming.collections` pluralizer apply — set `@collectionName` on one, or rename it, so the two differ.", + "ERR_PARTIAL_UNRESOLVED": "Build-time verify: a template partial ({{> group/source}}) does not resolve in the configured provider.", + "ERR_REQUIRED_SLOT_UNUSED": "Build-time verify (warning): a template's declared @requiredSlots slot is never referenced by the template text.", + "ERR_OUTPUT_TAG_MISSING": "Build-time verify: a template declares @requiredTags but its text (including provider-resolved partials) omits a required output tag's opening () form. path = the tag name.", + "ERR_TEMPLATE_NOT_STATIC": "Build-time verify (ADR-0061, Jinja bodies, Python and TypeScript): a template reference the check cannot settle statically — a computed attribute or include name, a dynamic subscript, a call, a tag outside the supported set. Reported rather than passed; path = the expression or tag.", + "ERR_TEMPLATE_SYNTAX": "Build-time verify: the template body, or a template it includes or imports, does not parse. Jinja bodies (ADR-0061, Python and TypeScript): path = the parser's message, which is engine-specific. Mustache bodies (every port): an unbalanced section (a close with no open, a close naming another section, a section never closed); path = the section's name.", + "ERR_TEMPLATE_ENGINE_UNSUPPORTED": "Build-time verify and render (ADR-0061): a template body is written for an engine this port does not ship — a Jinja body (.jinja / .j2 / .jinja2) in the Java, Kotlin or C# port, which render Mustache only. path = the template ref.", + "ERR_BAD_ATTR_FILTER": "An attr.filter references a field that is not addressable in that context or uses a disallowed op: a dataGrid @filter over a non-filterable field or an op disallowed for the field's subtype, or a projection row-scope @filter over a non-declared (dangling) or aggregate-derived field (#207). FR-044: a segment / measure.aggregate / object.report @filter names a field its entity (or @from) lacks or an op illegal for the field (S1); a relative-date value { \"now\": \"\" } appears outside the @filter of a segment, measure.aggregate, object.report, object.projection, origin.aggregate or origin.first (F1); or a relative-date value sits on a field that is not field.date/field.timestamp, under an op other than gt/gte/lt/lte, carries a value that is not an ISO-8601 duration, or has a startOf other than day, week or month, or a key besides now and startOf (F2).", + "ERR_STORAGE_FLATTENED_ARRAY": "@storage \"flattened\" cannot be combined with isArray=true.", + "ERR_SEQUENCE_START_OUT_OF_RANGE": "An identity.primary @sequenceStart is below 1, or above the largest value its key field can hold (2147483647 for a field.int). Postgres would refuse the sequence when the migration is applied, so the model is refused at load.", + "ERR_SEQUENCE_WITHOUT_INCREMENT": "An identity.primary sets @sequenceStart or @sequenceName, but its @generation is not \"increment\". Only an increment key draws from a sequence, so the attribute would change nothing: the identity is refused rather than silently ignored.", + "ERR_CROSS_FIELD_WITHOUT_CHECK": "A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) sets @dbCheck: false. Nothing but its database CHECK enforces a cross-field validator, so false would leave the rule enforced nowhere: the validator is refused. Remove the validator instead.", + "ERR_CONSTRAINT_NAME_WITHOUT_CHECK": "A numeric, length or regex validator or a field.enum sets @dbCheck: false, which generates no database CHECK, and @constraintName, which names that CHECK. With no CHECK there is nothing to name, so the node is refused rather than one of the two silently ignored.", + "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH": "A string-stored field.enum declares @maxLength (its column length) shorter than one of its @values members, which could not be stored in the column. The longest offending member is named.", + "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP": "A field.enum sets both @maxLength and @intValueMap. An @intValueMap enum is stored as an integer, so a column length would change nothing: the field is refused rather than silently ignored.", + "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE": "@flattenedColumnPrefix is set on a field.object whose @storage is not \"flattened\" (jsonb, subdocument, or absent, which is jsonb). Only a flattened value object puts its members' columns in the owning table, so the prefix would change nothing: the field is refused rather than silently ignored.", + "ERR_STORAGE_WITHOUT_OBJECT_REF": "@storage was set on a field that has no @objectRef.", + "ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF": "ADR-0013: a field.object declares no @objectRef. A field.object models a typed nested value and REQUIRES @objectRef. The message states the whole ladder rather than only the escape hatch: a known key set is an object.value the field @objectRefs; dynamic keys over a known value type are a field.map (@objectRef for a value object, @valueType for a scalar); only a bag no reader pins a key in is @dbColumnType: jsonb on a field.string. Naming the escape hatch alone is what taught adopters to reach for the bag by default.", + "ERR_UNRESOLVED_OBJECT_REF": "ADR-0042: a field.object / field.map @objectRef does not resolve to any object in the loaded tree (a dangling target). The ref resolves package-locally when bare (referrer's package, else root-level) and exactly when FQN — a bare cross-package ref no longer binds elsewhere. The error names same-short-name objects in other packages so the author can qualify it.", + "ERR_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.", + "ERR_SOURCE_MULTIPLE_PRIMARY": "An object declares more than one source node with role=primary.", + "ERR_SOURCE_KIND_UNSUPPORTED": "Phase-1 metadata-source-resolution: a declared source kind (resource or package) is not supported by this toolchain.", + "ERR_SOURCE_UNRESOLVED": "Phase-1 metadata-source-resolution: a path source declared in .metaobjects/config.json does not exist on disk.", + "ERR_PHYSICAL_NAME_KIND_MISMATCH": "FR-016 / ADR-0018: a source.rdb declares a kind-aware physical-name alias (@view/@materializedView/@proc/@function) that does not match its @kind. The legacy @table-for-non-table case warns rather than errors.", + "ERR_PHYSICAL_NAME_MULTIPLE": "FR-016 / ADR-0018: a source.rdb declares two or more kind-aware physical-name aliases at once (e.g. both @table and @view). Exactly one is permitted.", + "ERR_MUTABILITY_AUTOSET_CONFLICT": "FR-037 R1: a field declares @autoSet together with @mutability \"writeOnce\" or \"readOnly\". @autoSet already means the SERVER supplies the value; @mutability says who may write it. The pair states two contradictory things about one column. The boolean era left readOnly x @autoSet representable but UNVALIDATED; the enum cut closes both arms with one rule.", + "ERR_MUTABILITY_DOWNGRADE": "FR-037 R1: a subtype LOOSENS an inherited @mutability mode. A subtype may only tighten (readWrite < writeOnce < readOnly), never loosen. Replaces ERR_READONLY_DOWNGRADE, which was renamed because the rule now spans three modes and a code named READONLY would misdescribe a writeOnce -> readWrite loosening.", + "ERR_READONLY_ASSIGNED_PRIMARY": "FR-037 R1: a field with @mutability: \"readOnly\" is the target of an identity.primary with @generation: \"assigned\". The application has no path to populate the identity value (no setter; not generated; not defaulted). KEEPS its readOnly-specific name because the condition is readOnly-specific: @mutability: \"writeOnce\" on an assigned primary key is LEGAL, and indeed the natural declaration for one.", + "ERR_PARAMETER_REF_UNRESOLVED": "FR-015: source.rdb @parameterRef names an object that does not exist in the loaded model.", + "ERR_PARAMETER_REF_NOT_VALUE_OBJECT": "FR-015: source.rdb @parameterRef references an object.entity instead of object.value. Input shapes are value-objects by definition (no identity).", + "ERR_PARAMETER_REF_ON_NON_CALLABLE_KIND": "FR-015: source.rdb @parameterRef is set with @kind: \"table\" / \"view\" / \"materializedView\". These kinds do not accept parameters; only \"storedProc\" / \"tableFunction\" do.", + "ERR_DISCRIMINATOR_FIELD_NOT_FOUND": "FR-014: object.entity @discriminator names a field that does not exist on the entity (including inherited fields).", + "ERR_DISCRIMINATOR_VALUE_DUPLICATE": "FR-014: two subtypes of the same @discriminator-bearing root declare the same @discriminatorValue.", + "ERR_DISCRIMINATOR_VALUE_MISSING": "FR-014: a concrete entity extends a chain whose root declares @discriminator but the subtype lacks @discriminatorValue.", + "ERR_DISCRIMINATOR_VALUE_TYPE_MISMATCH": "FR-014: @discriminatorValue is not a member of the discriminator field's @values (when the discriminator field is field.enum) or cannot be coerced to its subtype.", + "ERR_YAML_COERCION": "A YAML 1.2 silent type coercion produced a value whose runtime type differs from the attribute's declared valueType (e.g. an unquoted `column: TRUE` parsed as boolean for a string-typed attr). Emitted by every port's YAML loader; canonical JSON is unaffected.", + "ERR_MERGE_CONFLICT": "FR5c: multi-file overlay merge produced an attribute conflict — two contributing files declared the same @attr with different non-empty values on the same logical node. Envelope is `format: \"merged\"` with `contributors[]` naming both files.", + "ERR_FILTERABLE_UNSUPPORTED_SUBTYPE": "#335 Half B / SP-H Unit9: a field carries @filterable: true but cannot be filtered — either it is an array (isArray: true; a collection column has no filter-operator band) or its subtype has no filter-operator band (e.g. field.object), the same subtype-support signal @sortable uses. Generating a filter for it would emit an empty operator set — a filter route that rejects every request. Use a filterable subtype (string/enum/uuid/number/currency/date/boolean), drop isArray, or remove @filterable.", + "ERR_SORTABLE_UNSUPPORTED_SUBTYPE": "#335 Half B: a field carries @sortable: true but cannot be ordered — either it is an array (isArray: true; a collection column has no ordering) or its subtype has no filter-operator band (e.g. field.object), the same subtype-support signal @filterable uses (SP-H Unit9). Generating a sort entry for it would emit an ORDER BY no dialect can execute. Use a sortable subtype (string/enum/uuid/number/currency/date/boolean) or remove @sortable.", + "ERR_COLLECT_WHOLE_OBJECT": "#335 Half A: a whole-object origin.aggregate @agg:collect — one with no @of, which rolls the related rows up as the carrying field's declared @objectRef value object rather than as one scalar column — is malformed. Raised when the carrying field is not a field.object declaring @objectRef; when @via is absent (there is no @of entity to infer the relationship from); when @distinct is declared (refused — a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal); when an @orderBy key does not resolve against the @via TERMINAL entity; or when a value-object member's declared field.[] disagrees with the matched terminal field's. Distinct from ERR_INVALID_ORIGIN so a conformance fixture can tell \"the whole-object arm rejected this\" from \"a loader that still requires @of rejected this\" — indistinguishable otherwise, since the corpus compares only code + source envelope.", + "ERR_COLLECT_MEMBER_UNRESOLVED": "#335 Half A: a whole-object origin.aggregate @agg:collect (no @of — the carrying field.object collects related rows as its declared @objectRef value object) has a value-object member with no matching field (by name) on the @via terminal entity. The lowering projects exactly the declared members; failing open here is how #270 turned a curated value object into the full entity, invisible in a diff because the metadata still read as curated.", + "ERR_REGISTRY_SEALED": "ADR-0023: a registration (register / registerType / extend / registerCommonAttrs / setDefaultSubType / addConstraint / registerProviders) was attempted against a registry sealed after its agreed metamodel-provider bootstrap. Made-up metamodel attributes/types are structurally disallowed in the library: codegen cannot register post-bootstrap. A new metamodel attribute requires a registered provider + human agreement. Downstream apps that need extra vocabulary compose their own (unsealed) registry.", + "ERR_UNKNOWN": "An internal loader error with no stable error code.", + "ERR_ENTITY_PRIMARY_SOURCE_READONLY": "FR-024 (ADR-0028) hard cutover: an object.entity's PRIMARY source has a read-only @kind (view/materializedView/storedProc/tableFunction). Read-only kinds are legal only in non-primary roles; a derived read model is an object.projection.", + "ERR_INVALID_METAMODEL_CONSTRAINT": "FR-033: a provider set's merged metamodel constraint graph contains a contradiction surfaced by validateConstraints — one of: (1) a parents/children rule references an unregistered type.subType (dangling); (2) a required child (min>=1) whose type.subType is not admitted under that parent (unsatisfiable); (3) bad cardinality (min>max, max:0 with min>=1, or min<0); (4) closed-set clash — a child declares a parent whose OWN children is a closed set (no * wildcard) that does not admit it; (5) a required-child cycle that cannot bottom out; (6) the same attr name contributed twice (across providers or the extends chain) with a conflicting valueType/required/default. The detail names which check and the offending type(s).", + "ERR_INVALID_INDEX": "An index.lookup or identity.secondary declares neither @fields nor @expr, declares BOTH (they are the two mutually exclusive ways to key an index — @expr is used INSTEAD of @fields), or names a field that does not exist on the owning entity's effective (resolved, via extends) field set.", + "ERR_INVALID_DIMENSION": "FR-044: a dimension.* is invalid: @of is not Entity.field on the owning entity (or, with @via, on the @via terminal) or names no field (D1); @via does not start at the owning entity, names an unknown hop, or crosses a hop that is not @cardinality: one or an identity.reference (D2); a dimension.time's @of is not a field.date or field.timestamp (D3); or a dimension.time over a field.date declares the 'hour' grain (D4).", + "ERR_INVALID_MEASURE": "FR-044: a measure.* is invalid: an @of item is not a field of the owning entity (M1); more than one @of item without @agg: count and @distinct: true (M2); @distinct: true with an @agg other than count (M3); sum/avg over a non-numeric field or min/max over a boolean, object or map field (M4); @segment names no segment of the owning entity (M5); or a measure.ratio @numerator/@denominator does not name a measure.aggregate of the same entity (M6).", + "ERR_INVALID_REPORT": "FR-044: an object.report is invalid: @from does not resolve to an object.entity (R1); a @dimensions item names no dimension of @from, omits the grain of a time dimension, uses a grain the dimension does not declare, gives a grain to an attribute dimension, or repeats (R2); a @measures item resolves to no measure at all (R3); the report declares a field.* or identity.* child (R4) or a writable source (R5); two items derive the same report field name (R6); or @segment names no segment of @from (R7).", + "ERR_REPORT_FOREIGN_MEASURE": "FR-044: an object.report lists a measure (bare or dotted) that belongs to an entity other than @from (R3). All measures of a report come from @from; combining two fact tables is a second report.", + "ERR_TRANSITION_UNKNOWN_STATE": "ADR-0066 (L4): a transition.action's @from or @to names a value that is not a member of its parent field.enum's @values.", + "ERR_TRANSITION_NOT_ON_ENTITY": "ADR-0066: a transition.action is declared on a field that is not a field of an object.entity (L1: a document-root field, or a field of a value, projection or report), or a concrete entity has a lifecycle and a source but no writable one (L2; reported on the entity). A transition is a guarded update of a stored row; an entity with no source at all may carry a lifecycle, which is inert.", + "ERR_LIFECYCLE_NO_INITIAL": "ADR-0066 (L3): a field.enum declares transitions but no @default. The @default is the lifecycle's initial state; it is never inferred.", + "ERR_LIFECYCLE_REDECLARED": "ADR-0066 (L10): an entity declares a field with the name of an inherited lifecycle field and does not extend it, so the base's transitions would silently stop applying. Extend the base field or name the field differently.", + "ERR_TRANSITION_NAME_COLLISION": "ADR-0066: a transition.action or an operation is named create, get, list, update or delete in any case (the derived CRUD verbs, L5 / O0), two transitions of one entity share a name across its lifecycles (L6; reported on the later one), or two operations of one package share a name, in one API or across its APIs (O6; one operation declared twice merges, and one operation declared identically in two APIs is the same operation, so neither is a collision). Names are compared without case, because a derived command, permission constant or file collides on a case-folding target. Transition names share one namespace per entity because each may derive a command.", + "ERR_OPERATION_TARGET_UNRESOLVED": "ADR-0066 (O2): an operation's @objectRef does not name an object.entity, or an operation.command lists @transitions and has no target entity: none is declared and none derives from its @inputRef (fields extending each primary key field of exactly one entity, each once) or its @outputRef (an entity, or a projection's base entity).", + "ERR_OPERATION_TARGET_MISMATCH": "ADR-0066 (O3): an operation declares @objectRef and its @inputRef / @outputRef derive a different target entity. @objectRef is declared only when the target cannot be derived; when both exist they must agree.", + "ERR_OPERATION_UNKNOWN_TRANSITION": "ADR-0066 (O4): an operation.command's @transitions names something that is not a transition.action of its target entity (declared or inherited).", + "ERR_OPERATION_SHAPE": "ADR-0066 (O1): an operation's @inputRef does not name an object.value, or its @outputRef does not name an object.entity, object.projection or object.value (an unresolved reference included).", + "ERR_PERMISSION_PUBLIC_CONFLICT": "ADR-0066 (P1): an operation or a transition.action declares both @public: true and @permission. A public operation calls no permission check, so the two contradict.", + "ERR_BINDING_PATH_MISMATCH": "ADR-0066 (B1): a binding.rest @path's {placeholders} are not exactly the target entity's primary key fields for an operation that addresses one row by key, or are not empty for one that does not; or (B2) two binding.rest of one API declare the same effective method and the same @path once placeholder names are ignored.", + "ERR_COMPUTED_TYPE_MISMATCH": "#195: an origin.computed @expr tree's inferred root type does not equal the carrying field's declared field.. A computed column's type is DERIVED from its expression, never asserted (no @convert escape), so a mismatch is a hard load error (sibling of ERR_PASSTHROUGH_TYPE_MISMATCH).", + "ERR_UNKNOWN_EXPR_NODE": "#195: an origin.computed @expr tree contains a node whose kind/op/fn is not in the closed expression grammar (field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now), or a node carries a key its kind does not take (a misspelled `else`, or a `field` node that also carries `case`). Fail-closed per ADR-0023; the detail names the offending token.", + "ERR_SQL_BODY_WITH_UNMANAGED": "#208: a source.rdb declares both @sql (author-supplied body) and @unmanaged (DDL owned elsewhere). The two markers are the mutually exclusive non-default states of one DDL-ownership axis — contradictory on a single source.", + "ERR_SQL_BODY_ON_WRITABLE_KIND": "#208: a source.rdb declares @sql with a writable @kind (\"table\", the default). A hand-written CREATE TABLE would bypass the column-diff machinery; tables are fully modeled or @unmanaged, never opaque-bodied.", + "ERR_ORIGIN_UNDER_SQL_BODY": "#208: a host object whose read source carries @sql also declares an origin.*-bearing (derived) field, or (on object.projection) an @filter (#207) — two sources of truth for the same body (the synthesized derivation/outer-WHERE vs. the author's verbatim SQL). Fail-closed.", + "ERR_ENUM_EXTENDS_VALUES_CONFLICT": "A field.enum both extends a shared package-level abstract enum and declares its own @values. One shared enum type has one member set — the own @values would be silently dropped in codegen. Remove the own @values to inherit the shared set, or extend a concrete (non-shared) enum instead.", + "ERR_ENUM_NORMALIZE_COLLISION": "Two declared members of one field.enum normalize to the same key under the default `@normalize: strip` (upper-case, delete everything outside A-Z0-9), e.g. READ_ONLY and READONLY. A reply naming one of them is indistinguishable from the other, so the extract engine would coerce it to the wrong member. Rename a member so the two differ after that fold, or set `@normalize: collapse` or `none` on the field. Not raised under collapse or none.", + "ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS": "A requirement.* with @status: retired declares @implementedBy. Refused rather than exempted (FR-039): a retired capability has no implementation by definition, so forbidding the attribute makes the dangling-reference class unreachable instead of silently tolerated.", + "ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED": "@supersededBy on a requirement whose @status is not `retired`. The attribute names what REPLACED a withdrawn capability; on a live one there is nothing to have replaced it.", + "ERR_UNKNOWN_LIBRARY": "FR-043: .metaobjects/config.json's `libraries` names a shipped library or layer this build does not have. Refused with the available tokens rather than skipped — skipped, it resurfaces as ERR_UNRESOLVED_SUPER against the adopter's own metadata.", + "ERR_LIBRARY_PACKAGE_COLLISION": "FR-043: a node is declared by BOTH an adopter's own metadata and a shipped library the project opts into — the `meta eject ` copy with the library still in `libraries`. The two merge silently and asymmetrically: additions take, deletions do not. TypeScript only (the SDK load path).", + "ERR_LIBRARY_PACKAGE_NOT_OWNED": "FR-043: a NEW top-level node is declared into a package a shipped library owns while that library is opted in — a later release of the library may ship a node of that name and merge into it. `overlay: true` on one of the library's OWN nodes is the documented amendment door and is untouched. TypeScript only (the SDK load path).", + "ERR_DEPENDENCY_UNRESOLVED": "FR-023: a declared dependency's transport could not locate a directory holding metaobjects.pkg.json.", + "ERR_DEPENDENCY_MANIFEST_INVALID": "FR-023: a dependency's metaobjects.pkg.json fails its schema, names a different dependency, points at a missing or hash-mismatched artifact, or its artifact does not load standalone / does not declare exactly the listed packages and nodes.", + "ERR_DEPENDENCY_SNAPSHOT_STALE": "FR-023: the committed snapshot does not match .metaobjects/deps.lock.json (lock missing, entry missing or extra, artifact missing, or hash mismatch) — run `meta deps sync`.", + "ERR_DEPENDENCY_NODE_COLLISION": "FR-023: two dependencies export the same fully-qualified node.", + "ERR_DEPENDENCY_PACKAGE_NOT_OWNED": "FR-023: a local top-level node is declared into a package owned by a dependency.", + "ERR_DEPENDENCY_METAMODEL_INCOMPATIBLE": "FR-023: a dependency's metamodelVersion major differs from this toolchain's.", + "ERR_DEPENDENCY_UPSTREAM_DRIFT": "FR-023: `meta deps check` / `verify --deps` found the installed dependency differs from the committed snapshot." + } +} diff --git a/server/rust/metaobjects/data/library/ai/db.yaml b/server/rust/metaobjects/data/library/ai/db.yaml new file mode 100644 index 0000000000..2e39b8f92b --- /dev/null +++ b/server/rust/metaobjects/data/library/ai/db.yaml @@ -0,0 +1,16 @@ +# library/ai/db.yaml — the DB PERSISTENCE layer for metaobjects::ai. +# +# Opted into as `"ai/db"`, which IMPLIES `"ai"`: `LlmCall` is declared in model.yaml and +# this file only re-opens it, so without the core layer the overlay has no target. +# +# `LlmCall` is the concrete, table-backed instance of the abstract envelope. An adopter +# who wants their OWN table (a different name, extra columns, a different id strategy) +# extends `LlmCallBase` in their own metadata and never opts into this layer at all. +metadata: + package: metaobjects::ai + children: + - object.entity: + name: LlmCall + overlay: true + children: + - source.rdb: { table: llm_call, role: primary } diff --git a/server/rust/metaobjects/data/library/ai/library.json b/server/rust/metaobjects/data/library/ai/library.json new file mode 100644 index 0000000000..da94fff915 --- /dev/null +++ b/server/rust/metaobjects/data/library/ai/library.json @@ -0,0 +1,20 @@ +{ + "$comment": "Library manifest (FR-043 §4). Embedded beside the YAML in every port. Every fact here is RESOLVED by a test, never trusted: `packages` against the library loaded standalone, `layers[].refs` against the embedded set, `generators[].name` against the generator registry, `generators[].anchor` against the library's own nodes, and `name` against the last package segment.", + "name": "ai", + "kind": "feature", + "stability": "stable", + "since": "0.20.0", + "description": "The LLM-call trace envelope: what was asked, what came back, what it cost, how long it took.", + "useWhen": "the application calls a language model and someone will ask what it cost or why a call failed", + "packages": ["metaobjects::ai"], + "layers": { + "": { "refs": ["ai/model", "ai/requirements"], "description": "the core model and its requirements — sourceless, so it adds no tables" }, + "db": { "refs": ["ai/db"], "description": "the concrete llm_call table" } + }, + "generators": [ + { "name": "trace-helper", "anchor": "metaobjects::ai::LlmCallBase" } + ], + "runtime": { + "typescript": ["@metaobjectsdev/runtime-ts"] + } +} diff --git a/server/rust/metaobjects/data/library/ai/model.yaml b/server/rust/metaobjects/data/library/ai/model.yaml new file mode 100644 index 0000000000..619d7ad242 --- /dev/null +++ b/server/rust/metaobjects/data/library/ai/model.yaml @@ -0,0 +1,44 @@ +# library/ai/model.yaml — the CORE layer: the LLM-call trace envelope. +# +# Adopters opt in via `libraries: ["ai"]`, then `extends: "metaobjects::ai::LlmCallBase"`. +# +# This layer declares NO `source.rdb`, so opting into `"ai"` alone adds zero tables and +# zero generated code — the design is present and resolvable, and nothing else happens +# until the adopter adds `"ai/db"`. See library/iam/model.yaml for the full rationale. +# +# This file was split out of the former `library/ai/llm-call.yaml`, which shipped the +# abstract base and a concrete `LlmCall` carrying `source.rdb` together. That was +# recorded as an accepted wart on the grounds that splitting would change what existing +# `ai` adopters get; a sweep of the estate found there are none, so it was closed rather +# than documented (FR-043 Amendment 1). +metadata: + package: metaobjects::ai + children: + - object.entity: + name: LlmCallBase + abstract: true + children: + - field.uuid: { name: traceId } + - field.uuid: { name: spanId } + - field.uuid: { name: parentSpanId } + - field.string: { name: sessionId } + - field.string: { name: callType } + - field.string: { name: system } + - field.string: { name: requestModel } + - field.string: { name: responseModel } + - field.int: { name: inputTokens } + - field.int: { name: outputTokens } + - field.currency: { name: costMinor, currency: USD } + - field.int: { name: latencyMs } + - field.string: { name: finishReason } + - field.string: { name: status } + - field.string: { name: errorDetail } + - field.timestamp: { name: startedAt } + - field.string: { name: llmRequest, dbColumnType: jsonb } # generic jsonb (no objectRef) + - field.string: { name: llmResponse, dbColumnType: jsonb } + - object.entity: + name: LlmCall + extends: metaobjects::ai::LlmCallBase + description: The concrete trace row. Its `source.rdb` lives in db.yaml, so opting into the core layer alone declares the shape without proposing a table. + children: + - identity.primary: { name: id, fields: ["spanId"] } diff --git a/server/rust/metaobjects/data/library/ai/requirements.yaml b/server/rust/metaobjects/data/library/ai/requirements.yaml new file mode 100644 index 0000000000..ca98132473 --- /dev/null +++ b/server/rust/metaobjects/data/library/ai/requirements.yaml @@ -0,0 +1,112 @@ +# library/ai/requirements.yaml — what the LLM-call trace envelope PROMISES. +# +# A RETROFIT, not new design: llm-call.yaml landed 2026-06-03 and `requirement.functional` +# first appears 2026-08-11, so the library could not have carried requirements when it was +# written. That is why this file is worth reading as a worked example — it shows what +# declaring the design of something that already exists actually turns up. +# +# The entry that earns its keep is `typedIo`, honestly `partial` + `accepted`: the library +# declares the ENVELOPE and the adopter declares the typed VO columns. Recording that seam +# in the ledger is where an agent meets it, before adding a fourth trace column. +# +# HIERARCHY IS NESTING, and the L4/L5 split is grain. An L4 names the OBJECT it is about; +# the fields that carry it hang off it as an L5 child. Writing the fields at L4 is +# ERR_REQUIREMENT_L4_NOT_OBJECT, and writing the concerns as SIBLINGS of the L2 leaves the +# L2 claiming nothing — both of which this file did until the standalone verify gate +# existed (`cli/test/shipped-library-verify.test.ts`). +metadata: + package: metaobjects::ai + children: + - requirement.functional: + name: llmTracing + level: 2 + status: live + statement: Every call to a language model leaves a row that says what was asked, what came back, what it cost and how long it took. + counterexample: A spend figure nobody can attribute to a call. + description: The segment this library covers. Its three children below are the concerns it decomposes into. + children: + - requirement.functional: + name: envelope + level: 4 + status: live + statement: A trace row identifies its call and its place in a trace — trace, span, parent span, session, call type, system. + counterexample: A log line that cannot be joined to the request that produced it. + implementedBy: [LlmCallBase] + children: + - requirement.functional: + name: traceAddressing + level: 5 + status: live + statement: The four addressing columns are declared on the base — trace, span, parent span and session. + counterexample: A row whose place in a trace is inferred from insertion order. + description: >- + The member grain exists here so the claim RESOLVES against the fields + themselves: renaming or dropping one of them dangles this reference and + fails the build, which naming the object alone would not. + implementedBy: [LlmCallBase.traceId, LlmCallBase.spanId, LlmCallBase.parentSpanId, LlmCallBase.sessionId] + + - requirement.functional: + name: accounting + level: 4 + status: live + statement: A trace row carries the tokens in, the tokens out, and the cost in integer minor units. + counterexample: A cost stored as a float. + description: >- + `field.currency` — integer minor units on the wire, always. Float arithmetic for + money is forbidden by the cross-port wire contract, and a spend total is exactly + the sum that exposes it. + implementedBy: [LlmCallBase] + children: + - requirement.functional: + name: tokenAndCostColumns + level: 5 + status: live + statement: Tokens in, tokens out and cost are three declared columns, the cost a field.currency. + counterexample: A cost column declared as a double. + implementedBy: [LlmCallBase.inputTokens, LlmCallBase.outputTokens, LlmCallBase.costMinor] + + - requirement.functional: + name: typedIo + level: 4 + status: partial + disposition: accepted + statement: The request and response bodies are stored as structured jsonb, not as opaque text. + counterexample: A prompt stored as a string nobody can query a field out of. + notes: >- + The library declares the two columns as generic jsonb with no `@objectRef`, + because it cannot know the adopter's request/response shape. Typing them is the + ADOPTER's move: declare an `object.value` and overlay the field with + `@objectRef` + `@storage: jsonb`. This is the seam ADR-0024 drew, recorded here + rather than in prose so it is in the ledger an agent reads before adding a + fourth trace column of its own. + implementedBy: [LlmCallBase] + children: + - requirement.functional: + name: jsonbBodies + level: 5 + status: live + statement: The request and response bodies are declared as jsonb columns on the base. + counterexample: A prompt stored in a text column. + description: >- + `live` where its parent is `partial`, and the split is the point: the + COLUMNS are shipped and this claim is fully realised; what is outstanding + is the TYPING of them, which is the parent's gap and the adopter's move. + implementedBy: [LlmCallBase.llmRequest, LlmCallBase.llmResponse] + + - requirement.architectural: + name: traceRowsCarryTiming + status: live + statement: Every trace row records when the call started and how long it took. + counterexample: A latency figure derived from log timestamps after the fact. + description: >- + Architectural, so it propagates down `extends` to every adopter entity deriving + from LlmCallBase — which is the point: an adopter's own trace table is claimed + by this requirement for free, and dropping the columns breaks the build. + implementedBy: [LlmCallBase] + + - requirement.architectural: + name: traceRowsCarryOutcome + status: live + statement: Every trace row records how the call ended — a status, a finish reason, and the error detail when there was one. + counterexample: A failed call indistinguishable from one that never happened. + implementedBy: [LlmCallBase] diff --git a/server/rust/metaobjects/data/library/iam/db.yaml b/server/rust/metaobjects/data/library/iam/db.yaml new file mode 100644 index 0000000000..ac4021d1d1 --- /dev/null +++ b/server/rust/metaobjects/data/library/iam/db.yaml @@ -0,0 +1,81 @@ +# library/iam/db.yaml — the DB PERSISTENCE layer for metaobjects::iam. +# +# Opted into as `"iam/db"`, which IMPLIES `"iam"`: this file is nothing but +# `overlay: true` redeclarations, and an overlay whose target was never declared is +# ERR_OVERLAY_NO_TARGET. +# +# It carries exactly two kinds of child — `source.rdb` and `index.lookup` — and nothing +# else. The field set, the identities and the relationships all live in model.yaml, +# because they are the DESIGN; what lives here is where the rows go and which lookups are +# worth an index. Add a field here and the core layer stops being the whole model, which +# is the thing the split exists to guarantee. +# +# Physical names are `iam_`-prefixed. Two reasons, both real: `user` and `group` are +# reserved words in Postgres, and an adopter very likely has tables of their own by those +# names. A library that collides on a table name is a library nobody can adopt. +metadata: + package: metaobjects::iam + children: + - object.entity: + name: User + overlay: true + children: + - source.rdb: { table: iam_user, role: primary } + + - object.entity: + name: GroupType + overlay: true + children: + - source.rdb: { table: iam_group_type, role: primary } + + - object.entity: + name: Group + overlay: true + children: + - source.rdb: { table: iam_group, role: primary } + # Nesting is walked parent-ward constantly; the FK alone gives no index. + - index.lookup: { name: ixParent, fields: [parentId] } + + - object.entity: + name: Role + overlay: true + children: + - source.rdb: { table: iam_role, role: primary } + + - object.entity: + name: Permission + overlay: true + children: + - source.rdb: { table: iam_permission, role: primary } + + - object.entity: + name: GroupMember + overlay: true + children: + - source.rdb: { table: iam_group_member, role: primary } + # The composite PK covers (userId, groupId), so "who is in this group?" — + # the other direction — has no index without this one. Same reasoning for + # every ixSecond below. + - index.lookup: { name: ixGroup, fields: [groupId] } + + - object.entity: + name: RolePermission + overlay: true + children: + - source.rdb: { table: iam_role_permission, role: primary } + - index.lookup: { name: ixPermission, fields: [permissionId] } + + - object.entity: + name: UserRole + overlay: true + children: + - source.rdb: { table: iam_user_role, role: primary } + - index.lookup: { name: ixRole, fields: [roleId] } + + - object.entity: + name: GroupMemberRole + overlay: true + children: + - source.rdb: { table: iam_group_member_role, role: primary } + # "who holds this role in this group?" — the scoped-grant read. + - index.lookup: { name: ixGroupRole, fields: [groupId, roleId] } diff --git a/server/rust/metaobjects/data/library/iam/library.json b/server/rust/metaobjects/data/library/iam/library.json new file mode 100644 index 0000000000..39fcc18a51 --- /dev/null +++ b/server/rust/metaobjects/data/library/iam/library.json @@ -0,0 +1,16 @@ +{ + "$comment": "Library manifest (FR-043 §4). Embedded beside the YAML in every port. Every fact here is RESOLVED by a test, never trusted: `packages` against the library loaded standalone, `layers[].refs` against the embedded set, `generators[].name` against the generator registry, `generators[].anchor` against the library's own nodes, and `name` against the last package segment.", + "name": "iam", + "kind": "feature", + "stability": "preview", + "since": "1.1.0", + "description": "Users, nestable typed groups, roles as permission bundles, grants global or scoped to a group.", + "useWhen": "the application has people who log in and things some of them may not do", + "packages": ["metaobjects::iam"], + "layers": { + "": { "refs": ["iam/model", "iam/requirements"], "description": "the core model and its requirements — sourceless, so it adds no tables" }, + "db": { "refs": ["iam/db"], "description": "nine tables, iam_-prefixed, plus the lookup indexes the composite keys do not cover" } + }, + "generators": [], + "runtime": {} +} diff --git a/server/rust/metaobjects/data/library/iam/model.yaml b/server/rust/metaobjects/data/library/iam/model.yaml new file mode 100644 index 0000000000..ee8000be38 --- /dev/null +++ b/server/rust/metaobjects/data/library/iam/model.yaml @@ -0,0 +1,157 @@ +# library/iam/model.yaml — the CORE layer: identity and access management. +# +# Adopters opt in via `libraries: ["iam"]` in .metaobjects/config.json. +# +# This layer declares NO `source.rdb`, and that is the whole point of the split. A +# sourceless object is inert by a contract that already ships: migrate skips an object +# with no writable source, and codegen emits no route, queries, hooks, grid or form for +# one (both citing #248 — persistability derives from source presence, never from the +# object subtype). It still gets a type-only interface, so `extends` and reference work. +# +# So `libraries: ["iam"]` adds ZERO tables and ZERO generated code. What an adopter gains +# is the design being present and resolvable: an agent working in the repo knows the +# capability exists and can draw on it, and nothing else happens until the adopter adds +# `"iam/db"`. +# +# Authoring discipline (FR-043 §3.1), so the departures are visible: +# - `field.uuid` + `generation: uuid` on principals; composite ASSIGNED keys on +# junctions. Never `increment` — a library cannot know the adopter's id strategy. +# - Physical names carry the `iam_` prefix (in db.yaml): `user` and `group` are +# reserved words in Postgres, and an adopter has tables of their own. +# - No adopter-facing profile data. That arrives by `overlay: true`. +# - No credentials. See requirements.yaml → `noCredentialsOnUser`. +metadata: + package: metaobjects::iam + children: + - object.entity: + name: IamBase + abstract: true + description: Shared shape of every iam principal and definition — a stable uuid plus change timestamps. Junctions do not extend it; they are addressed by their participants. + children: + - field.uuid: { name: id, required: true } + - field.timestamp: { name: createdAt, autoSet: onCreate } + - field.timestamp: { name: updatedAt, autoSet: onUpdate } + + - object.entity: + name: User + extends: IamBase + description: A person or service account that can be granted access. Carries no authentication secret of any kind — see the noCredentialsOnUser requirement. + children: + - field.string: { name: username, required: true, maxLength: 64, filterable: true } + - field.string: { name: email, required: true, maxLength: 254, stringFormat: email, filterable: true } + - field.string: { name: displayName, maxLength: 120 } + # NOT `filterable: true`, deliberately. The loader warns when a filterable + # field is in no identity — filtering on it sequential-scans — and a library + # must not ship a warning to every adopter. `username` and `email` carry it + # because they have identity.secondary; `status` does not. An adopter who + # wants to filter on status overlays `filterable` AND an index together, + # which is exactly what the layer split is for. + - field.enum: { name: status, required: true, values: [invited, active, suspended, closed], default: active } + - field.timestamp: { name: emailVerifiedAt } + - field.timestamp: { name: lastSeenAt } + - identity.primary: { name: pk, fields: [id], generation: uuid } + - identity.secondary: { name: uqUsername, fields: [username] } + - identity.secondary: { name: uqEmail, fields: [email] } + - relationship.association: { name: groups, objectRef: Group, cardinality: many, through: GroupMember } + - relationship.association: { name: roles, objectRef: Role, cardinality: many, through: UserRole } + + - object.entity: + name: GroupType + extends: IamBase + description: What KIND of group this is — a team, a tenant, a project. An entity rather than an enum, because "which roles may be held in this kind of group" is data an adopter extends, and an enum's values cannot be extended by overlay. + children: + - field.string: { name: key, required: true, maxLength: 64 } + - field.string: { name: name, required: true, maxLength: 120 } + - field.string: { name: description, maxLength: 500 } + - identity.primary: { name: pk, fields: [id], generation: uuid } + - identity.secondary: { name: uqGroupTypeKey, fields: [key] } + + - object.entity: + name: Group + extends: IamBase + description: A nestable collection of users, of a declared GroupType. Nesting is by parentId; acyclicity is an invariant the schema cannot express — see the acyclicGroupNesting requirement. + children: + - field.uuid: { name: groupTypeId, required: true } + - field.uuid: { name: parentId } + - field.string: { name: key, required: true, maxLength: 64 } + # Not filterable for the same reason as User.status above. + - field.string: { name: name, required: true, maxLength: 120 } + - field.string: { name: description, maxLength: 500 } + - identity.primary: { name: pk, fields: [id], generation: uuid } + - identity.secondary: { name: uqGroupKey, fields: [key] } + - identity.reference: { name: fkGroupType, fields: [groupTypeId], references: GroupType, onDelete: restrict } + - identity.reference: { name: fkParent, fields: [parentId], references: Group, onDelete: restrict } + + - object.entity: + name: Role + extends: IamBase + description: A reusable bundle of permissions. Code never compares a role NAME to a literal — it asks whether a user holds a permission, and the mapping is data. + children: + - field.string: { name: key, required: true, maxLength: 64 } + - field.string: { name: name, required: true, maxLength: 120 } + - field.string: { name: description, maxLength: 500 } + - field.uuid: { name: groupTypeId, description: "When set, this role may be held only within groups of this type; absent means grantable anywhere." } + - identity.primary: { name: pk, fields: [id], generation: uuid } + - identity.secondary: { name: uqRoleKey, fields: [key] } + - identity.reference: { name: fkGroupType, fields: [groupTypeId], references: GroupType, onDelete: restrict } + - relationship.association: { name: permissions, objectRef: Permission, cardinality: many, through: RolePermission } + + - object.entity: + name: Permission + extends: IamBase + description: "The assignable unit — a stable : key the application checks against. An entity, not an enum, on ADR-0037's own reasoning: it has its own identity, its own lifecycle, and a junction with real foreign keys." + children: + - field.string: { name: key, required: true, maxLength: 128, description: "Stable : key the application checks against." } + - field.string: { name: description, maxLength: 500 } + - identity.primary: { name: pk, fields: [id], generation: uuid } + - identity.secondary: { name: uqPermissionKey, fields: [key] } + + # ---- grant surface: every grant is a row, addressed by its participants ---- + # + # Junctions do NOT extend IamBase: they have no identity of their own, and adding a + # surrogate uuid to a row whose identity IS its participants invites a duplicate. + + - object.entity: + name: GroupMember + description: A user's membership of a group. + children: + - field.uuid: { name: userId, required: true } + - field.uuid: { name: groupId, required: true } + - field.timestamp: { name: joinedAt, autoSet: onCreate } + - identity.primary: { name: pk, fields: [userId, groupId], generation: assigned } + - identity.reference: { name: fkUser, fields: [userId], references: User, onDelete: cascade } + - identity.reference: { name: fkGroup, fields: [groupId], references: Group, onDelete: cascade } + + - object.entity: + name: RolePermission + description: A permission granted by a role. + children: + - field.uuid: { name: roleId, required: true } + - field.uuid: { name: permissionId, required: true } + - identity.primary: { name: pk, fields: [roleId, permissionId], generation: assigned } + - identity.reference: { name: fkRole, fields: [roleId], references: Role, onDelete: cascade } + - identity.reference: { name: fkPermission, fields: [permissionId], references: Permission, onDelete: restrict } + + - object.entity: + name: UserRole + description: A system-wide grant of a role to a user. + children: + - field.uuid: { name: userId, required: true } + - field.uuid: { name: roleId, required: true } + - field.timestamp: { name: grantedAt, autoSet: onCreate } + - identity.primary: { name: pk, fields: [userId, roleId], generation: assigned } + - identity.reference: { name: fkUser, fields: [userId], references: User, onDelete: cascade } + - identity.reference: { name: fkRole, fields: [roleId], references: Role, onDelete: restrict } + + - object.entity: + name: GroupMemberRole + description: A grant of a role to a user WITHIN one group. Three foreign keys, so it is not an M:N @through junction (which must declare exactly two identity.reference children); it is read by explicit finders. + children: + - field.uuid: { name: userId, required: true } + - field.uuid: { name: groupId, required: true } + - field.uuid: { name: roleId, required: true } + - field.timestamp: { name: grantedAt, autoSet: onCreate } + - identity.primary: { name: pk, fields: [userId, groupId, roleId], generation: assigned } + - identity.reference: { name: fkUser, fields: [userId], references: User, onDelete: cascade } + - identity.reference: { name: fkGroup, fields: [groupId], references: Group, onDelete: cascade } + - identity.reference: { name: fkRole, fields: [roleId], references: Role, onDelete: restrict } diff --git a/server/rust/metaobjects/data/library/iam/requirements.yaml b/server/rust/metaobjects/data/library/iam/requirements.yaml new file mode 100644 index 0000000000..0fb7cf0921 --- /dev/null +++ b/server/rust/metaobjects/data/library/iam/requirements.yaml @@ -0,0 +1,156 @@ +# library/iam/requirements.yaml — what this library's design PROMISES. +# +# This is what makes iam a library rather than a schema snippet. Without requirements an +# adopter gets nine tables; with them they get nine tables plus a build that is held to +# "no authorization decision is hard-wired to a name", which no snippet can do. +# +# Two reading rules, both load-bearing: +# +# `live` here means "the model AS SHIPPED realises this" — never "your application +# does". A ledger binds to model nodes; runtime guarantees are the runtime's tests, and +# this library does not invent a way to point a requirement at code (@verifiedBy was +# retired for exactly that). Behaviour the model cannot carry ships as `partial` + +# `disposition: accepted` with a notes sentence naming what the adopter must do. +# +# The functional tree roots at L2, not L1. L1 is the adopter's SOLUTION, and a library +# is by definition a segment of someone else's. Architectural claims ship flat. +# +# HIERARCHY IS NESTING, and the L4/L5 split is grain. The concerns are CHILDREN of the L2 +# rather than its siblings, and an L4 names the OBJECT it is about while the field that +# carries it hangs off it as an L5 child. Written flat, the L2 claims nothing in its whole +# subtree; written at L4, a field reference is ERR_REQUIREMENT_L4_NOT_OBJECT. Both shipped +# here until the standalone verify gate existed (`cli/test/shipped-library-verify.test.ts`). +metadata: + package: metaobjects::iam + children: + # ---- functional: the L2 segment and the concerns nested under it -------- + - requirement.functional: + name: accessControl + level: 2 + status: live + statement: Who may do what is answered from stored grants, never from a name compared to a literal in code. + counterexample: A branch that reads `if (user.role === "admin")`. + description: The segment this library covers. The concerns beneath it are what it decomposes into. + children: + - requirement.functional: + name: identity + level: 4 + status: live + statement: A person or service account is represented once, addressed by a uuid, and reachable by username or email. + counterexample: Two rows for the same person because the email changed. + implementedBy: [User] + + - requirement.functional: + name: grouping + level: 4 + status: live + statement: Users are collected into typed, nestable groups, and the kind of group is data rather than a hard-coded set. + counterexample: A `teamOrTenant` boolean. + implementedBy: [Group, GroupType, GroupMember] + + - requirement.functional: + name: acyclicGroupNesting + level: 4 + status: partial + disposition: accepted + statement: A group is never its own ancestor. + counterexample: Two groups each naming the other as parent. + notes: >- + The schema cannot express this — a self-referencing FK admits a cycle, and the + only relational forms that would catch it (a recursive CHECK, a closure table + maintained by trigger) are DB-specific and would not survive three dialects. + The adopter enforces it where the write happens. Recorded rather than omitted + so an agent reading the ledger before adding a parent-setting endpoint sees the + obligation. + implementedBy: [Group] + + - requirement.functional: + name: grants + level: 4 + status: live + statement: A role is granted to a user either system-wide or scoped to one group, and both are ordinary rows. + counterexample: A nullable `groupId` on one grant table, where NULL means "everywhere". + description: >- + Two junctions, not one with a nullable scope. A NULL in a unique key is DISTINCT + from every other NULL in SQL, so a nullable-scope design lets the same global + grant be inserted twice; the fix needs a partial index whose expression carries + a physical column name. Two composite-keyed tables need no escape hatch and + survive three dialects and five ports unchanged. + implementedBy: [UserRole, GroupMemberRole] + + - requirement.functional: + name: roleScopedToGroupType + level: 4 + status: partial + disposition: accepted + statement: A role bound to a group type is granted only within groups of that type. + counterexample: A "tenant admin" role granted inside a project group. + notes: >- + Expressing this relationally needs the grant row to carry the group's type and + a composite FK back to (group, type) — three foreign keys deep, unverified + across five ports' DDL and ORM paths. The adopter checks it at the point of + grant. The declared half is the L5 child below; the enforcement is not. + implementedBy: [Role, GroupMemberRole] + children: + - requirement.functional: + name: roleDeclaresItsGroupType + level: 5 + status: live + statement: A role declares the group type it is bound to, as a nullable reference. + counterexample: A role whose intended scope is recoverable only from its name. + description: >- + `live` where its parent is `partial`, and the split is grain as much as + verdict: the DECLARATION is shipped and resolves against the field itself, + so dropping the column fails the build — while the ENFORCEMENT, which no + schema here can carry, stays the parent's accepted gap. + implementedBy: [Role.groupTypeId] + + - requirement.functional: + name: decision + level: 4 + status: live + statement: An authorization decision is the question "does this user hold this permission key", answered from rows. + counterexample: A hard-coded list of usernames that bypass a check. + implementedBy: [Permission, RolePermission] + + # ---- architectural: prohibitions in force -------------------------------- + + - requirement.architectural: + name: grantsAreRows + status: live + statement: A grant exists only as a stored row; nothing is granted by naming, position or convention. + counterexample: A superuser recognised by username. + implementedBy: [UserRole, GroupMemberRole, RolePermission, GroupMember] + + - requirement.architectural: + name: noCredentialsOnUser + status: live + statement: A user row carries no authentication secret — no password, no hash, no knowledge-based question or answer. + counterexample: A password or secret-answer column on the user table. + description: >- + Authentication is a separate capability with an entity per factor; this library + is identity and authorization only. + notes: >- + This is the one thing every reader of a user table proposes adding, and a real + legacy model of this shape stored a length-bounded plaintext password and a + knowledge-based secret pair on the user row. Stating it as a prohibition IN + FORCE — claimable, and rendered on agent/requirements.md — is what stops an + agent extending "the user model" from re-deriving it on sight. It is + `architectural`, not `retired`: retired is chartered for a capability built + here and removed, and this library never built one. + implementedBy: [User] + + - requirement.architectural: + name: principalDeletionRevokesGrants + status: live + statement: Deleting a user or group removes its grants; deleting a role or permission still in use is refused. + counterexample: A grant row pointing at a user who no longer exists. + description: The referential rule in one sentence — cascade from a principal, restrict from a definition. + implementedBy: [GroupMember, UserRole, GroupMemberRole, RolePermission] + + - requirement.architectural: + name: stableIdentifiers + status: live + statement: Every principal and definition is addressed by a uuid that never changes; every grant by its participants. + counterexample: A group referenced by its display name. + implementedBy: [IamBase] diff --git a/server/rust/metaobjects/data/metamodel/api.json b/server/rust/metaobjects/data/metamodel/api.json new file mode 100644 index 0000000000..0f30e16e08 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/api.json @@ -0,0 +1,73 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "api", + "subType": "base", + "description": "Registry anchor for the declared API surface (ADR-0030, ADR-0054): not authorable. The `api` subtype axis is the interaction model, never the protocol; protocol lives in `binding.*` on each operation.", + "children": [] + }, + { + "type": "api", + "subType": "operational", + "extendsBase": true, + "description": "A named, packaged request/response surface whose children are operations (ADR-0030). It is a wire contract: two of them (`v1`, `v2`) may declare the same operation side by side. The code behind it is one service per metadata package, whose surface is the package's operations (ADR-0067). Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "The application does something beyond derived CRUD: a named command (approve, cancel, import) or a named query (my open requests). Declare it here so its input, output, permission and business errors are part of the model. A plain lifecycle needs no api.operational at all: a transition nobody claims is held to derive its own command once a shell is generated, and no shell is generated yet.", + "rules": "Children are `operation.command` and `operation.query`. Lives at the document root. Declares no fields, sources or identities: shapes are referenced, never defined, by the surface. Operation names are compared without case, are unique across every API of one package, except one operation declared identically in two APIs, such as a versioned API beside its successor (one operation declared twice in one API merges), and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). Two declared bindings of one API may not share a method and path (ERR_BINDING_PATH_MISMATCH).", + "children": [ + { "type": "operation", "subType": "*", "name": "*", "min": 0, "max": null, "description": "The operations this surface exposes." } + ] + }, + { + "type": "operation", + "subType": "base", + "description": "Registry anchor for the attributes every operation shares (ADR-0054): not authorable.", + "children": [ + { "type": "binding", "subType": "*", "name": "*", "min": 0, "max": null, "description": "Optional protocol bindings. Only needed to override the derived method and path." }, + { "type": "attr", "subType": "string", "name": "inputRef", "min": 0, "max": 1, "description": "The `object.value` this operation takes as its input (ADR-0030). Absent on an operation whose only parameter is the target's borrowed key. Anything other than an `object.value` is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "outputRef", "min": 0, "max": 1, "description": "The object this operation returns: an `object.projection`, `object.entity` or `object.value`. Which projection a query returns is the author's choice among several over one entity, so it cannot be computed. Anything else is ERR_OPERATION_SHAPE." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "The entity this operation acts on, declared only when it cannot be derived. It is derived from the input value when its fields `extend` every primary key field of exactly one entity, each once, else from the output's base entity; an input that borrows part of a key, one key field twice, or the keys of two entities derives nothing, so declare it. Declared and derivable, the two must agree (ERR_OPERATION_TARGET_MISMATCH). It must name an `object.entity` (ERR_OPERATION_TARGET_UNRESOLVED)." }, + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "The permission name the generated shell will ask the project's policy about before anything is written (no shell is generated yet). A key into grant data (who holds it is data, what the policy decides is code), so an explicit name is stable: a derived name moves when the operation is renamed. A dotted identifier path such as `purchasing.approve`; a package prefix may use `::` (ERR_BAD_ATTR_VALUE otherwise). Absent and not @public: the shell will use the derived name `.`, with the package of the operation's API, and `verify` advises or requires an explicit one (setting `rules.permissions.names`). Several operations may share one." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "The shell will call no permission check (no shell is generated yet). Authentication is the transport's job and is unaffected. Absent means checked. Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." } + ] + }, + { + "type": "operation", + "subType": "command", + "extendsBase": true, + "description": "A named operation that changes state. Takes an `object.value` (ADR-0030). Its body is hand-written. The contract (ADR-0066) is that a generated shell around it loads the row, checks the permission and the current state, runs the body, and makes the guarded update in one transaction. No shell is generated yet: this vocabulary is registered, loaded and checked, and nothing is generated from it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A business action with its own name, input and rules: approve, cancel, transfer. A command that moves a lifecycle names the transitions it may make in @transitions; its body decides which one applies.", + "children": [ + { "type": "attr", "subType": "string", "name": "transitions", "isArray": true, "min": 0, "max": 1, "description": "The lifecycle moves this command may make: names of `transition.action` nodes on its target entity (ERR_OPERATION_UNKNOWN_TRANSITION otherwise). A fact of the business the model cannot compute. A transition a command lists gets no derived command of its own. Listing any requires a target (ERR_OPERATION_TARGET_UNRESOLVED)." }, + { "type": "attr", "subType": "string", "name": "errors", "isArray": true, "min": 0, "max": 1, "description": "The business failures the hand-written body may return, each a lower snake case code (`insufficient_funds`). They name the wire error, the OpenAPI document and the typed result; the shell will refuse an undeclared one (no shell is generated yet). A code that is not lower snake case, appears twice, or is one the route answers itself (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed, validation, invalid_json, invalid_id, method_not_allowed, constraint_violation, internal) is ERR_BAD_ATTR_VALUE." } + ] + }, + { + "type": "operation", + "subType": "query", + "extendsBase": true, + "description": "A named operation that reads. Returns an `object.projection` (or an entity or value). It changes nothing. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A read with its own name and shape beyond derived get and list: my open requests, the dashboard summary.", + "children": [ + { "type": "attr", "subType": "boolean", "name": "many", "min": 0, "max": 1, "description": "The query returns a list and takes the filter, sort and paging contract. Not implied by the projection, so declared. Absent means one row. Legal on a query only." } + ] + }, + { + "type": "binding", + "subType": "base", + "description": "Registry anchor for protocol bindings (ADR-0030, ADR-0054): not authorable.", + "children": [] + }, + { + "type": "binding", + "subType": "rest", + "extendsBase": true, + "description": "The HTTP method and path of an operation, declared only to override the derived ones. A query is `GET`, a command `POST`; the path is `//{id}/` for an operation with a target key and `//` without one. Most models never write it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "An operation must keep a method or path the derived one would not give it, such as an existing public URL.", + "children": [ + { "type": "attr", "subType": "string", "name": "method", "min": 0, "max": 1, "allowedValues": ["GET", "POST", "PUT", "PATCH", "DELETE"], "description": "The HTTP method. Absent: GET for a query, POST for a command." }, + { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "A path template. Its `{name}` placeholders must be exactly the target's primary key fields when the operation is keyed, and there must be none when it is not; two declared bindings of one API may not share the method and path (ERR_BINDING_PATH_MISMATCH)." } + ] + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/attr.json b/server/rust/metaobjects/data/metamodel/attr.json new file mode 100644 index 0000000000..ec55a95947 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/attr.json @@ -0,0 +1,71 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "attr", + "subType": "base", + "dataType": "string", + "description": "Abstract base attribute — the polymorphic/unconstrained value-type marker. Stores its value type-preserved (never stringified), accepting any type; used for an untyped attr (e.g. a field's @default, whose value-type follows the owning field's subtype). Not authored directly: a `attr.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." + }, + { + "type": "attr", + "subType": "string", + "dataType": "string", + "description": "A string-valued metadata attribute. Coerces to and validates as text; the default value-type for inline @-syntax attrs (array-of-string is the same subtype with isArray)." + }, + { + "type": "attr", + "subType": "int", + "dataType": "int", + "description": "A 32-bit-integer-valued metadata attribute. Coerces to and validates as a number." + }, + { + "type": "attr", + "subType": "intMap", + "dataType": "object", + "description": "An object-shaped attribute whose values are all integers (e.g. field.enum's @intValueMap: {memberSymbol: int}). Generic shape check only; a consumer field type layers its own semantic rules (key-set membership, uniqueness) in its own content-rule validation." + }, + { + "type": "attr", + "subType": "long", + "dataType": "long", + "description": "A 64-bit-integer-valued metadata attribute. Coerces to and validates as a number." + }, + { + "type": "attr", + "subType": "double", + "dataType": "double", + "description": "A double-precision floating-point-valued metadata attribute. Coerces to and validates as a number." + }, + { + "type": "attr", + "subType": "boolean", + "dataType": "boolean", + "description": "A boolean-valued metadata attribute. Coerces to and validates as true/false." + }, + { + "type": "attr", + "subType": "class", + "dataType": "string", + "description": "A class-/type-reference-valued metadata attribute. String-backed (a fully-qualified class or type name) used by binding facets." + }, + { + "type": "attr", + "subType": "properties", + "dataType": "object", + "description": "A key/value map attribute (a bag of arbitrary author-supplied properties). Object-shaped value; the registered escape hatch for author-supplied properties (exempt from the strict-attr check, ADR-0023)." + }, + { + "type": "attr", + "subType": "filter", + "dataType": "object", + "description": "A filter-expression-valued metadata attribute. Object-shaped value that desugars a preset filter to the canonical { field: { op: value } } form (scalar→eq, array→in, null→isNull; or/and recurse)." + }, + { + "type": "attr", + "subType": "expression", + "dataType": "object", + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/db.json b/server/rust/metaobjects/data/metamodel/db.json new file mode 100644 index 0000000000..1c61a0bdac --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/db.json @@ -0,0 +1,106 @@ +{ + "provider": "metaobjects-db", + "extends": [ + { + "type": "field", + "subType": "*", + "children": [ + { "type": "attr", "subType": "string", "name": "column", "min": 0, "max": 1, "description": "Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the \"naming\" setting in .metaobjects/config.json)." }, + { "type": "attr", "subType": "boolean", "name": "db.indexed", "min": 0, "max": 1, "description": "When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means)." }, + { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } + ] + }, + { + "type": "field", + "subType": "timestamp", + "children": [ + { "type": "attr", "subType": "boolean", "name": "localTime", "min": 0, "max": 1, "description": "When true, the timestamp is a naive wall-clock value with no timezone (Postgres `timestamp without time zone`); absent/false (the default) = an absolute instant (`timestamptz`). ADR-0036 Wave 2 — replaces the retired @dbColumnType: timestamp_with_tz escape hatch." } + ] + }, + { + "type": "field", + "subType": "object", + "children": [ + { "type": "attr", "subType": "string", "name": "flattenedColumnPrefix", "min": 0, "max": 1, "description": "On a field.object with @storage \"flattened\": the text put before each member's column, verbatim (\"\" allowed, so the members keep their own column names). Absent: this field's resolved column name and \"_\" (with @column \"bill\", the members are bill_). A fact about the owning table, so it lives on the embedding field, never on the value object. Refused on any other storage (ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE). Justified in ADR-0023 Amendment 1." }, + { "type": "attr", "subType": "string", "name": "storage", "min": 0, "max": 1, "allowedValues": ["flattened", "jsonb", "subdocument"], "description": "Storage strategy for an object-typed field (set with @objectRef). \"flattened\" expands the nested value into prefixed columns on the parent table. \"jsonb\" stores the structured value in a single jsonb column (supports isArray=true for arrays of values). \"subdocument\" is a hint for document-store codegen targets and emits no Postgres column." } + ] + }, + { + "type": "field", + "subType": ["date", "time", "timestamp"], + "children": [ + { "type": "attr", "subType": "string", "name": "autoSet", "min": 0, "max": 1, "allowedValues": ["onCreate", "onUpdate"], "description": "Auto-set semantics for timestamp-like fields: 'onCreate' stamps on insert, 'onUpdate' stamps on every write." } + ] + }, + { + "type": "source", + "subType": "rdb", + "children": [ + { "type": "attr", "subType": "string", "name": "table", "min": 0, "max": 1, "description": "Physical SQL table name for source.rdb @kind: \"table\" (default). FR-016: Defaults from the source's bare structural `name` under the project's naming.tables rule (the \"naming\" setting in .metaobjects/config.json) when omitted, then from the owning entity's name. Pre-1.0 legacy spelling for view/materializedView/storedProc/tableFunction kinds during the transition; canonical-serializer rewrites to the kind-matching alias." }, + { "type": "attr", "subType": "string", "name": "view", "min": 0, "max": 1, "description": "Physical SQL view name for source.rdb @kind: \"view\". Same internal slot as @table." }, + { "type": "attr", "subType": "string", "name": "materializedView", "min": 0, "max": 1, "description": "Physical SQL materialized-view name for source.rdb @kind: \"materializedView\". Same internal slot as @table." }, + { "type": "attr", "subType": "string", "name": "proc", "min": 0, "max": 1, "description": "Physical SQL stored-procedure name for source.rdb @kind: \"storedProc\". Same internal slot as @table." }, + { "type": "attr", "subType": "string", "name": "function", "min": 0, "max": 1, "description": "Physical SQL table-function name for source.rdb @kind: \"tableFunction\". Same internal slot as @table." }, + { "type": "attr", "subType": "string", "name": "kind", "min": 0, "max": 1, "allowedValues": ["table", "view", "materializedView", "storedProc", "tableFunction"], "description": "The kind of database object this source represents: table (default, writable), view, materializedView, storedProc, or tableFunction. Non-table kinds are read-only." }, + { "type": "attr", "subType": "string", "name": "role", "min": 0, "max": 1, "allowedValues": ["primary", "replica"], "description": "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." }, + { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "Optional database schema name (e.g. 'catalog', 'public'). Postgres defaults to 'public'; SQLite rejects any non-default value." }, + { "type": "attr", "subType": "string", "name": "sql", "min": 0, "max": 1, "description": "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)." }, + { "type": "attr", "subType": "boolean", "name": "unmanaged", "min": 0, "max": 1, "description": "FR-024/#208 escape valve — this DB object is managed elsewhere (Flyway / a hand-migration owns its DDL). meta migrate does NOT create, drop, or drift-check it; verify --db reports it as external (declared). Legal on any @kind including table (the externally-managed-entity case). Mutually exclusive with @sql." }, + { "type": "attr", "subType": "string", "name": "parameterRef", "min": 0, "max": 1, "description": "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." } + ] + }, + { + "type": "identity", + "subType": "secondary", + "children": [ + { "type": "attr", "subType": "string", "name": "orders", "isArray": true, "min": 0, "max": 1, "allowedValues": ["asc", "desc"], "description": "Physical index-key sort direction, positional to @fields ('asc' | 'desc'). Omit for all-ascending (the default); a shorter array leaves trailing keys ascending. Drives DESC-ordered index keys (e.g. a recency index on a timestamp). RDB-physical — contributed by the db provider, not core identity." }, + { "type": "attr", "subType": "string", "name": "where", "min": 0, "max": 1, "description": "Partial-index predicate (raw SQL, e.g. \"delivered_at IS NULL\"). When set, the index covers only rows matching the predicate — smaller and cheaper for queries that always filter on it. Absent = a full index over every row. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "string", "name": "expr", "min": 0, "max": 1, "description": "Raw key EXPRESSION for a functional/expression index (e.g. \"lower(email)\"). Used INSTEAD of @fields — the index key is the expression rather than plain columns. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "string", "name": "using", "min": 0, "max": 1, "description": "Index access method (e.g. \"gin\", \"gist\", \"hash\"); default \"btree\" (not rendered). Pair with @expr for e.g. a GIN index over an array/jsonb expression. RDB-physical — contributed by the db provider." } + ] + }, + { + "type": "field", + "subType": "enum", + "children": [ + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent: __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } + ] + }, + { + "type": "validator", + "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne", "exactlyOne"], + "children": [ + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } + ] + }, + { + "type": "identity", + "subType": "primary", + "children": [ + { "type": "attr", "subType": "long", "name": "sequenceStart", "min": 0, "max": 1, "description": "The first value an @generation \"increment\" key's sequence hands out (Postgres: GENERATED BY DEFAULT AS IDENTITY (START WITH n)). Absent: 1. Lets a model reproduce a table that keeps a low id range for seeded rows. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { "type": "attr", "subType": "string", "name": "sequenceName", "min": 0, "max": 1, "description": "The physical name of an @generation \"increment\" key's sequence (Postgres: GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME ...)). Absent: the database's own default,
__seq on Postgres. Lets a model adopt a sequence that kept its name across a table rename. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." } + ] + }, + { + "type": "identity", + "subType": "reference", + "children": [ + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "Physical foreign-key constraint name override. Absent → the backend's auto-derived default (e.g. `
__fk`). Lets a model adopt an existing database whose FK constraints follow a different naming convention without a destructive rename. RDB-physical — contributed by the db provider. Justified in ADR-0023 Amendment 1." }, + { "type": "attr", "subType": "string", "name": "onDelete", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on parent delete, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Precedence: this attr → a correlated relationship's @onDelete (declared on either side of the FK) → the relationship's subtype default. Use for a reference-only FK (no relationship), an M:N junction's FK sides, or a per-FK override; prefer declaring the action on the relationship otherwise. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "string", "name": "onUpdate", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on key update, declared directly on the FK-defining reference — the explicit per-FK override (ADR-0047). Same precedence as @onDelete; when only a correlated relationship is present, @onUpdate defaults to cascade. RDB-physical — contributed by the db provider." } + ] + }, + { + "type": "index", + "subType": "lookup", + "children": [ + { "type": "attr", "subType": "string", "name": "orders", "isArray": true, "min": 0, "max": 1, "allowedValues": ["asc", "desc"], "description": "Physical index-key sort direction, positional to @fields ('asc' | 'desc'). Omit for all-ascending (the default); a shorter array leaves trailing keys ascending. Drives DESC-ordered index keys (e.g. a recency index on a timestamp). RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "string", "name": "where", "min": 0, "max": 1, "description": "Partial-index predicate (raw SQL, e.g. \"delivered_at IS NULL\"). When set, the index covers only rows matching the predicate — smaller and cheaper for queries that always filter on it. Absent = a full index over every row. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "string", "name": "expr", "min": 0, "max": 1, "description": "Raw key EXPRESSION for a functional/expression index (e.g. \"lower(email)\"). Used INSTEAD of @fields — the index key is the expression rather than plain columns. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "string", "name": "using", "min": 0, "max": 1, "description": "Index access method (e.g. \"gin\", \"gist\", \"hash\"); default \"btree\" (not rendered). Pair with @expr for e.g. a GIN index over an array/jsonb expression. RDB-physical — contributed by the db provider." } + ] + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/documentation.json b/server/rust/metaobjects/data/metamodel/documentation.json new file mode 100644 index 0000000000..65f8fa1125 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/documentation.json @@ -0,0 +1,78 @@ +{ + "provider": "metaobjects-documentation", + "types": [ + { + "type": "*", + "subType": "*", + "description": "Universal documentation common attrs — accepted on EVERY metatype (registered as common attrs, NOT per-type). The named attr children below are the documentation vocabulary.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "description", + "min": 0, + "max": 1, + "description": "What this element IS and COVERS, written for someone using it. Markdown allowed, multi-line via YAML '|' block scalar. Flows into doc-gen surfaces (JSDoc / XML-doc / Postgres COMMENT / Mermaid prose). State scope and boundary — what it covers, what it deliberately does NOT, and which sibling owns the rest — all of which is derivable from the model itself. Anything you had to read the implementation to learn belongs in @notes, not here." + }, + { + "type": "attr", + "subType": "string", + "name": "summary", + "min": 0, + "max": 1, + "description": "Short single-line SENTENCE (OpenAPI `summary` pattern) — used in index tables, sidebar previews, and AI prompts where the full @description is too long. Distinct from @title, which is a noun label rather than a sentence. When @summary is unset, doc surfaces typically fall back to the first sentence of @description." + }, + { + "type": "attr", + "subType": "string", + "name": "title", + "min": 0, + "max": 1, + "description": "Short single-line human label — a NOUN PHRASE naming the element (e.g. 'Email' for a `field.string email`), never a sentence. What a tab, an index row or a sidebar shows when the name is an identifier rather than a label. See @summary for the one-line sentence form." + }, + { + "type": "attr", + "subType": "string", + "name": "notes", + "min": 0, + "max": 1, + "description": "Internal-only rationale, never emitted to user-facing docs — the slot for what you had to look OUTSIDE the model to learn: evidence, measurements, citations, the control that proved an absence was real, and what breaks if this changes. It is NOT a longer @description, and restating the description here is the failure mode this slot invites. Mechanical test: a sentence belongs in @notes exactly when it would have to change because the IMPLEMENTATION changed while the model did not." + }, + { + "type": "attr", + "subType": "string", + "name": "deprecated", + "min": 0, + "max": 1, + "description": "Text reason for deprecation. Presence ⇒ deprecated. Codegen emits @deprecated / [Obsolete] with this reason." + }, + { + "type": "attr", + "subType": "string", + "name": "replacedBy", + "min": 0, + "max": 1, + "description": "FQN reference to the replacement element. Only meaningful with `deprecated`. Codegen appends 'Replaced by ' to deprecation messages." + }, + { + "type": "attr", + "subType": "string", + "name": "seeAlso", + "min": 0, + "max": 1, + "isArray": true, + "description": "External documentation URLs. Codegen emits @see / ." + }, + { + "type": "attr", + "subType": "string", + "name": "aliases", + "min": 0, + "max": 1, + "isArray": true, + "description": "Alternate names for this element. Aids AI authoring disambiguation, search, migration." + } + ] + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/field.json b/server/rust/metaobjects/data/metamodel/field.json new file mode 100644 index 0000000000..8d4c5a2185 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/field.json @@ -0,0 +1,199 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "field", + "subType": "base", + "dataType": "string", + "description": "Abstract base field — the shared root subtype that concrete field subtypes specialize. Carries the attrs common to every field but binds no concrete data type of its own (falls back to string). Not authored directly: a `field.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.", + "children": [ + { "type": "validator", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "view", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "origin", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "attr", "subType": "boolean", "name": "required", "min": 0, "max": 1, "description": "When true, the field is NOT NULL. Equivalent to attaching a validator.required child. On a non-array string, generated wire-tier input validation (create/patch) additionally rejects the empty string by default — whitespace is accepted — unless an explicit validator.length @min: 0 opts back to presence-only. In-process read models never enforce this at construction." }, + { "type": "attr", "subType": "string", "name": "mutability", "min": 0, "max": 1, "allowedValues": ["readWrite", "writeOnce", "readOnly"], "description": "FR-037 R1: who may write this field, and when. 'readWrite' (the default when absent) — the caller may set it on create and change it on update. 'writeOnce' — the caller sets it on create; it is excluded from the update shape thereafter, so a value presented on PATCH is ignored rather than rejected. 'readOnly' — nobody writes it: codegen emits no setter / writable property, the persistence layer skips the column on INSERT/UPDATE, and Zod/Pydantic/class-validator schemas omit it from input variants; the value is populated by the database (computed column, default expression, trigger), by replication, or by another external owner. The three are mutually exclusive modes of ONE axis — who may write, and when — so the illegal pair is unrepresentable and inheritance has a total order: a subtype may TIGHTEN an inherited mode (readWrite < writeOnce < readOnly) and never loosen it (ERR_MUTABILITY_DOWNGRADE). Pairing a non-readWrite mode with @autoSet is ERR_MUTABILITY_AUTOSET_CONFLICT: @autoSet already says the SERVER supplies the value, which is a different axis from who may write it." }, + { "type": "attr", "name": "default", "min": 0, "max": 1, "description": "Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue()." }, + { "type": "attr", "subType": "boolean", "name": "unique", "min": 0, "max": 1, "description": "When true, the field gets a column-level UNIQUE constraint." } + ] + }, + { + "type": "field", + "subType": "string", + "dataType": "string", + "extendsBase": true, + "description": "Variable-length text. Binds to the native string type; DB column is VARCHAR/TEXT (use @maxLength for VARCHAR(n)).", + "whenToUse": "Plain variable-length text. Set @maxLength to size the column. The default for textual data.", + "children": [ + { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Maximum character length for string-typed fields (drives VARCHAR(n))." }, + { "type": "attr", "subType": "string", "name": "stringFormat", "min": 0, "max": 1, "allowedValues": ["email", "hostname"], "description": "ADR-0036/0037: a closed validation format for a plain string field that has NO native type or behavior of its own — email | hostname. The field stays a plain string (native binding + DB column unchanged); codegen emits the matching validator (Zod z.email() / a hostname check; PG CHECK where appropriate). The canonical matcher per format lives in each port's codegen, NOT author validator.regex (cross-language regex engines diverge). Named @stringFormat (not @format) to avoid colliding with template.* @format (output format). Concepts WITH a native type or behavior are subtypes instead (uuid → field.uuid, url/uri → field.uri, ip → field.inet)." } + ] + }, + { + "type": "field", + "subType": "int", + "dataType": "int", + "extendsBase": true, + "description": "32-bit signed integer. Binds to the native int type; DB column is INTEGER.", + "whenToUse": "A whole number within +/-2^31. Use long instead if values can exceed that." + }, + { + "type": "field", + "subType": "long", + "dataType": "long", + "extendsBase": true, + "description": "64-bit signed integer. Binds to the native long/bigint type; DB column is BIGINT.", + "whenToUse": "A whole number that may exceed 32 bits (ids, counters, epoch millis)." + }, + { + "type": "field", + "subType": "double", + "dataType": "double", + "extendsBase": true, + "description": "Double-precision (64-bit) IEEE-754 floating point. Binds to the native double/number type; DB column is DOUBLE PRECISION. Not for money — use field.currency or field.decimal.", + "whenToUse": "An approximate floating-point number where exactness is not required. For money/precision use decimal." + }, + { + "type": "field", + "subType": "float", + "dataType": "double", + "extendsBase": true, + "description": "Single-precision floating point. Binds to the native double/number type (TS has no distinct float); DB column is REAL. Not for money." + }, + { + "type": "field", + "subType": "decimal", + "dataType": "string", + "extendsBase": true, + "description": "Precision-exact decimal (use @precision/@scale). Native TS binding is string (lossless); DB column is NUMERIC(p,s); the wire form is a string. Classified DATA_TYPE_STRING so an exact decimal is never silently rounded through a double.", + "whenToUse": "A value needs exact precision (money amounts, rates, quantities). Use decimal with @precision/@scale — never double, which loses precision.", + "rules": "The wire and native-TS form is a STRING to stay precision-exact end-to-end (Drizzle pg numeric infers as string; SP-H/ADR-0019). Set @precision (total significant digits) and @scale (digits right of the point) to drive NUMERIC(p,s).", + "children": [ + { "type": "attr", "subType": "int", "name": "precision", "min": 0, "max": 1, "description": "Total number of significant digits for decimal-typed fields." }, + { "type": "attr", "subType": "int", "name": "scale", "min": 0, "max": 1, "description": "Number of digits to the right of the decimal point for decimal-typed fields." } + ] + }, + { + "type": "field", + "subType": "boolean", + "dataType": "boolean", + "extendsBase": true, + "description": "True/false flag. Binds to the native boolean type; DB column is BOOLEAN.", + "whenToUse": "A true/false flag." + }, + { + "type": "field", + "subType": "date", + "dataType": "date", + "extendsBase": true, + "description": "Calendar date (no time-of-day). Binds to the native date/temporal type; DB column is DATE.", + "whenToUse": "A column is a calendar date with no time-of-day. Use date instead of a string." + }, + { + "type": "field", + "subType": "time", + "dataType": "date", + "extendsBase": true, + "description": "Time-of-day (no calendar date). Binds to the native date/temporal type; DB column is TIME." + }, + { + "type": "field", + "subType": "timestamp", + "dataType": "date", + "extendsBase": true, + "description": "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.", + "whenToUse": "A column records an instant (created/updated at). Use timestamp so it serializes ISO-8601 with timezone consistently." + }, + { + "type": "field", + "subType": "object", + "dataType": "object", + "extendsBase": true, + "description": "A nested structured value (set @objectRef to the target object). Storage is governed by @storage: flattened (prefixed columns), jsonb (single jsonb column, supports isArray), or subdocument (document-store hint).", + "whenToUse": "A field holds a nested structured value (or an array of them). Set @objectRef + @storage so the shape is typed and persisted (flattened/jsonb) instead of an untyped blob.", + "rules": "Set @objectRef to the nested object's name (or FQN). @storage selects physical layout — flattened expands into prefixed parent columns (isArray must be false), jsonb stores the structured value (or array when isArray=true) in one jsonb column, subdocument emits no Postgres column. Defaults to single-jsonb-column when @storage is absent.", + "children": [ + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the target object an object-typed field nests — drives nested-object (de)serialization." } + ] + }, + { + "type": "field", + "subType": "map", + "dataType": "object", + "extendsBase": true, + "description": "An open-keyed map (Record / dict[str,V]) stored in a single jsonb column. Keys are always strings (the JSON object constraint); the value type is set by @valueType (a scalar field subtype) or @objectRef (a value-object).", + "whenToUse": "A field is an open-keyed map of values (Record). Use it for dynamic keys instead of an untyped jsonb string.", + "rules": "Keys are always strings. Set exactly one of @valueType (a scalar value subtype: string/int/long/double/float/decimal/boolean/date/time/timestamp/uuid) or @objectRef (a value-object name or FQN). Stored as a single jsonb column holding the JSON object — never a native array; isArray does not apply.", + "children": [ + { "type": "attr", "subType": "string", "name": "valueType", "min": 0, "max": 1, "description": "Scalar value subtype for a scalar-valued map (string/int/long/double/float/decimal/boolean/date/time/timestamp/uuid). Mutually exclusive with @objectRef; exactly one of the two must be set." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name (or FQN) of the value-object for a value-object-valued map. Mutually exclusive with @valueType; exactly one of the two must be set." } + ] + }, + { + "type": "field", + "subType": "currency", + "dataType": "long", + "extendsBase": true, + "description": "Stores money as integer minor units (cents). Binds to long; the client formats via @currency/@locale. Float arithmetic for money is forbidden.", + "whenToUse": "A column holds money. Use currency so it stores integer minor-units and the client formats it — never floats or hand-rolled cents math.", + "rules": "Storage is integer minor units (cents for USD, yen for JPY) — the wire form is unchanged from long. The server never formats currency; all formatting is client-side via Intl.NumberFormat using @currency (ISO 4217) and @locale (BCP 47). Float arithmetic for money is forbidden.", + "children": [ + { "type": "attr", "subType": "string", "name": "currency", "min": 0, "max": 1, "default": "USD", "description": "ISO 4217 currency code for a currency-subtype field. Storage is integer minor units; defaults to 'USD' when omitted." } + ] + }, + { + "type": "field", + "subType": "enum", + "dataType": "string", + "extendsBase": true, + "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer).", + "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", + "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", + "children": [ + { "type": "transition", "subType": "*", "name": "*", "min": 0, "max": null, "description": "Lifecycle moves between this enum's members (ADR-0066). An enum with at least one transition.action is a lifecycle: its states are @values, its initial state @default, its terminal states the members no transition leaves." }, + { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, + { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, + { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer. Justified in ADR-0023 Amendment 1." }, + { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." }, + { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } + ] + }, + { + "type": "field", + "subType": "uuid", + "dataType": "string", + "extendsBase": true, + "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.", + "whenToUse": "A key or external identifier is a UUID. Use it for a typed UUID column instead of a plain string." + }, + { + "type": "field", + "subType": "uri", + "dataType": "string", + "extendsBase": true, + "description": "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.", + "whenToUse": "A field holds a URL or URI. Use it for a typed URI column + URL validation instead of a plain string.", + "children": [ + { "type": "attr", "subType": "boolean", "name": "lenient", "min": 0, "max": 1, "description": "#234: opt this field out of strict well-formedness enforcement. When true, codegen binds a plain string (no URL/IP validator, no native URI/InetAddress type; field.inet uses a text column, not the native inet type) so a not-strictly-valid value round-trips unchanged. Default (absent/false) is strict: an absolute-scheme URI / an IPv4-or-IPv6 literal." } + ] + }, + { + "type": "field", + "subType": "inet", + "dataType": "string", + "extendsBase": true, + "description": "An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native type + behavior, so a subtype not a @stringFormat). Binds to TS string (TS has no native IP type, same as field.uuid); other ports bind to their native IP type (Java java.net.InetAddress, C# System.Net.IPAddress, Python ipaddress, Kotlin java.net.InetAddress). DB column is the Postgres-native inet type. Codegen emits an IPv4-or-IPv6 literal validator (a Zod regex union in TS — z.string().ip() was removed in Zod 4 — native IP-type parsing in the other ports); add @lenient to bind a plain string with no validator. v1 ships WITHOUT @kind — the native type subsumes ipv4/ipv6; @kind is reserved for a later ipv4|ipv6 value-constraint.", + "whenToUse": "A field holds an IPv4 or IPv6 address. Use it for a native Postgres inet column + IP validation instead of a plain string.", + "children": [ + { "type": "attr", "subType": "boolean", "name": "lenient", "min": 0, "max": 1, "description": "#234: opt this field out of strict well-formedness enforcement. When true, codegen binds a plain string (no URL/IP validator, no native URI/InetAddress type; field.inet uses a text column, not the native inet type) so a not-strictly-valid value round-trips unchanged. Default (absent/false) is strict: an absolute-scheme URI / an IPv4-or-IPv6 literal." } + ] + }, + { + "type": "field", + "subType": "duration", + "dataType": "string", + "extendsBase": true, + "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, as many fractional digits as its native type holds, zero is PT0S) and reads that form plus leading week and day counts (nW, exactly 7 days; nD, exactly 24 hours) and a fraction of any length, truncated toward zero. Years and months are refused: a calendar span is not a fixed length. Justified in ADR-0023 Amendment 1.", + "whenToUse": "A field holds an elapsed time, a timeout or a delay. Use it for a native Postgres interval column and a native duration type instead of a string or a number of seconds. A calendar span (\"every 3 months\") is not a duration: model it as an int and a unit." + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/identity.json b/server/rust/metaobjects/data/metamodel/identity.json new file mode 100644 index 0000000000..d7ec0ebec0 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/identity.json @@ -0,0 +1,37 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "identity", + "subType": "primary", + "description": "The primary key — one per entity; @fields names its column(s), @generation the value strategy.", + "whenToUse": "Every entity needs exactly one — names the primary-key field(s) and how the value is generated. Always declare it.", + "maxOccurs": 1, + "defaultName": "primary", + "children": [ + { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 1, "max": 1, "description": "The field name(s) composing this identity. Single-element for a simple PK/index, multiple for a composite." }, + { "type": "attr", "subType": "string", "name": "generation", "min": 0, "max": 1, "allowedValues": ["increment", "uuid", "assigned"], "description": "Primary-key value generation strategy: 'increment' (auto-increment), 'uuid', or 'assigned' (caller-supplied)." } + ] + }, + { + "type": "identity", + "subType": "secondary", + "description": "A secondary unique index on one or more fields. Always enforces uniqueness — use index.lookup for non-unique query-performance indexes.", + "whenToUse": "A column or set of columns must be unique (e.g. email, slug, composite business key). For a plain non-unique index, use index.lookup instead.", + "children": [ + { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 0, "max": 1, "description": "The field name(s) composing this identity. Single-element for a simple unique index, multiple for a composite unique constraint. Required UNLESS @expr is present — a unique index keys off plain columns (@fields) or a key expression (@expr), never both; declaring both is ERR_INVALID_INDEX." } + ] + }, + { + "type": "identity", + "subType": "reference", + "description": "A foreign-key reference to another entity (@references target; @enforce toggles a physical FK).", + "whenToUse": "This entity holds a foreign key to another. Declare it to generate the FK constraint + typed navigation, instead of a loose id field you join on by hand.", + "children": [ + { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 1, "max": 1, "description": "The field name(s) composing this identity. Single-element for a simple PK/index, multiple for a composite." }, + { "type": "attr", "subType": "string", "name": "references", "min": 1, "max": 1, "description": "Target of the reference. Bare entity name (e.g. 'Program') resolves to that entity's primary identity. Dotted forms ('Program.id' or 'Program.fieldA,fieldB') target an explicit field set on the entity." }, + { "type": "attr", "subType": "boolean", "name": "enforce", "min": 0, "max": 1, "description": "When true (default), the backend physically enforces the reference (SQL FK constraint, document validation rule, graph edge guarantee). Set false to declare a logical reference for navigation/typing/codegen only — the value may dangle at the backend level." } + ] + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/index.json b/server/rust/metaobjects/data/metamodel/index.json new file mode 100644 index 0000000000..cfcd0b953a --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/index.json @@ -0,0 +1,14 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "index", + "subType": "lookup", + "description": "A non-unique lookup index on one or more fields. Use for query-performance indexes that do NOT enforce uniqueness — declare identity.secondary for unique constraints instead.", + "whenToUse": "You need a DB index for query performance (fast lookups/sorts) but NOT uniqueness enforcement. @fields names the indexed columns; the db provider adds @orders / @expr / @where / @using for physical tuning.", + "children": [ + { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 0, "max": 1, "description": "The field name(s) this index covers. Required UNLESS @expr is present — an index keys off plain columns (@fields) or a key expression (@expr), never both; declaring both is ERR_INVALID_INDEX." } + ] + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/layout.json b/server/rust/metaobjects/data/metamodel/layout.json new file mode 100644 index 0000000000..0f539bee09 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/layout.json @@ -0,0 +1,15 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "layout", + "subType": "base", + "description": "Abstract base layout — the shared root subtype for object-level UI surfaces. A layout attaches a presentation concern (grids, forms, tabs, cards) to an object. The base carries no attrs of its own; concrete subtypes add their presentation attrs. Not authored directly: a `layout.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." + }, + { + "type": "layout", + "subType": "dataGrid", + "description": "A metadata-driven data grid attached to an object: declares the displayed columns, page size, default sort, and an optional preset filter the generated grid renders." + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/object.json b/server/rust/metaobjects/data/metamodel/object.json new file mode 100644 index 0000000000..eb44fedc67 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/object.json @@ -0,0 +1,81 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "object", + "subType": "base", + "description": "Abstract object base — the shared root subtype that concrete object subtypes (entity/value/projection) specialize. Declares the structural children common to EVERY object subtype (the intersection: field/identity/validator/layout/source); subtype-specific children (relationship, template) and attrs (discriminator) ride their own subtypes. Has no runtime semantics of its own; not authored directly. A `object.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.", + "children": [ + { "type": "field", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "identity", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "validator", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "layout", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "source", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "index", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "attr", "subType": "string", "name": "object", "min": 0, "max": 1, "implementedIn": ["java"], "description": "The native class an object binds to (ADR-0001), in place of its default runtime class: on the JVM, a fully-qualified class name. Cross-port vocabulary only Java implements so far; every port loads and type-checks it, and the others do not act on it yet." }, + { "type": "attr", "subType": "string", "name": "objectAdapter", "min": 0, "max": 1, "ports": ["java", "kotlin"], "description": "JVM-only (ADR-0005): the fully-qualified name of an ObjectAdapter that takes over value access for this object's instances. Every port loads and type-checks it; only Java and Kotlin act on it." } + ] + }, + { + "type": "object", + "subType": "entity", + "extendsBase": true, + "description": "An object that owns its data: own identity, writable sources, and lifecycle. The default object subtype — a bare `object:` key resolves to entity. May co-locate templates (template.prompt and friends) with the owning entity.", + "whenToUse": "The thing owns its own data and lifecycle — a table you create/read/update/delete. The default for any persisted resource.", + "rules": "object.entity owns data — it declares its own identity, its primary source must be a writable @kind (read-only kinds may appear only in a read role), and it carries lifecycle. A field carrying origin.* is derived ⇒ read-only wherever it lives, including on an entity. Templates (template.*) may be nested so a prompt can be co-located with its owning entity. See ADR-0028 (object taxonomy).", + "children": [ + { "type": "relationship", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "template", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "dimension", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "measure", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null }, + { "type": "attr", "subType": "string", "name": "discriminator", "min": 0, "max": 1, "description": "FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string)." }, + { "type": "attr", "subType": "string", "name": "discriminatorValue", "min": 0, "max": 1, "description": "FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } + ] + }, + { + "type": "object", + "subType": "value", + "extendsBase": true, + "description": "A value object — pure shape with NO identity and NO source, ever. Constructed (by caller / embedding), never populated from a store. May `extends` an entity's fields to reuse shape. Equality is by content.", + "whenToUse": "You need a reusable typed shape with NO identity and NO table — an embedded value, a DTO, a prompt/response payload. Constructed in memory, never persisted on its own.", + "rules": "object.value is pure shape: it NEVER declares an identity and NEVER declares a source, in any role. It is constructed — by a caller or by embedding — and is never populated from a backing store. A value-hosted field may carry origin.passthrough (FR-015 parameter lineage) but NEVER an assembly origin (origin.aggregate / origin.computed / origin.first) — passthrough on a value is lineage; assembly origins live on object.projection (#210). It may `extends` an entity's fields to reuse their shape. @normalize is the object-level default ASCII normalization mode applied to this value's enum fields' tolerant extract (each field may still override per-field). See ADR-0028 (object taxonomy, value purity).", + "children": [ + { "type": "relationship", "subType": "*", "name": "*", "min": 0, "max": null } + ] + }, + { + "type": "object", + "subType": "projection", + "extendsBase": true, + "description": "A derived read-only representation of entities. Its fields are extends-bound / origin-derived / self-declared-under-external-assembly, all read-only at the subtype level. Identity is optional and MUST extend an entity identity; sources are restricted to read-only @kinds. The declared field set IS the exposure (inclusive, fail-closed).", + "whenToUse": "You need a derived, read-only view over entities — a report, summary, or joined/aggregated read model. Declare it (with origin.* children) instead of hand-writing the SELECT/joins; it stays read-only and regenerates.", + "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", + "children": [ + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, + { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, + { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, + { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, + { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } + ] + }, + { + "type": "object", + "subType": "report", + "extendsBase": true, + "description": "A declared report (FR-044): a fixed combination of dimensions and measures of ONE entity (@from), compiled to a read-only view. One row per distinct dimension tuple; no dimensions means exactly one row. Fields are DERIVED, not declared: one per dimension (a time dimension's field is , e.g. purchasedAtDay) and one per measure. Every measure must belong to @from (two fact tables are two reports). @filter and @segment scope rows before grouping and combine by AND. Read-only: no writes, no get-by-id.", + "whenToUse": "Dashboard totals, per-day series and per-group summaries that would otherwise be hand-written GROUP BY queries.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "The object.entity whose rows the report aggregates." }, + { "type": "attr", "subType": "string", "name": "dimensions", "isArray": true, "min": 0, "max": 1, "description": "Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row." }, + { "type": "attr", "subType": "string", "name": "measures", "isArray": true, "min": 1, "max": 1, "description": "Measure names of @from." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, + { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } + ] + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/origin.json b/server/rust/metaobjects/data/metamodel/origin.json new file mode 100644 index 0000000000..e2539d6d66 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/origin.json @@ -0,0 +1,74 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "origin", + "subType": "base", + "description": "Abstract base origin — the shared root subtype for field-level provenance. A field carrying any origin.* is derived ⇒ read-only wherever it lives. The base carries no attrs of its own; concrete subtypes add their provenance attrs. Not authored directly: a `origin.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." + }, + { + "type": "origin", + "subType": "passthrough", + "description": "A cross-entity field reference: this projection field passes a source entity's value straight through (@from), optionally reached via a relationship path (@via).", + "whenToUse": "A projection field just surfaces a field from a related entity. Declare the cross-entity passthrough instead of re-joining and re-selecting it by hand.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the source value this projection field passes through (e.g. 'Program.title')." }, + { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Optional dotted relationship path used to reach the source entity (e.g. 'Program.weeks')." }, + { "type": "attr", "subType": "boolean", "name": "convert", "min": 0, "max": 1, "description": "Acknowledges that this field's declared type deliberately differs from its @from source field's type (#185). Absent/false (the default), a passthrough is type-preserving — a differing field. or array-ness fails with ERR_PASSTHROUGH_TYPE_MISMATCH. Set true to opt out. This is an acknowledgement only: it does NOT generate a cast — the value flows through unchanged and the consumer owns any coercion. Real type-converting projections are origin.expression's job (#159)." } + ] + }, + { + "type": "origin", + "subType": "aggregate", + "description": "A value reduced from the related row-set reached along a relationship path (@via) from the base entity: count/sum/avg/min/max over a column (@of); any/all predicate quantifiers over a @filter; or collect (an array rollup — of the @of column, or of the carrying field.object's declared @objectRef value object when @of is omitted).", + "whenToUse": "A projection needs a value derived by reducing related rows — a count/sum/avg/min/max, a 'did any/every related row match' flag, or an array of collected values. Declare it instead of hand-writing the aggregate query — it stays consistent and regenerates.", + "rules": "@via may be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (single-hop-unique inference; FR-024, ADR-0029). Multi-hop paths must always be stated explicitly. @of is required for count/sum/avg/min/max and forbidden for any/all (which quantify over rows via @filter, not a column). @filter is required for any/all. The field must be isArray:true for collect and isArray:false for every other @agg. @distinct and @orderBy are collect-only. On @agg:collect @of is OPTIONAL: omitting it declares a WHOLE-OBJECT rollup, which collects each related row as the carrying field's declared @objectRef value object instead of one scalar column. A whole-object rollup requires a field.object carrying @objectRef, requires that @objectRef to name an object.value, requires an explicit @via (there is no @of entity to infer the path from), and refuses @distinct. Its @orderBy keys resolve against the @via TERMINAL entity, not the head or a middle hop. Its value-object members bind to the terminal entity's fields BY NAME — member name == terminal field name, deliberately NOT extends, so one value object stays collectable from two different entities — and every member must match a terminal field agreeing on BOTH field. and array-ness.", + "children": [ + { "type": "attr", "subType": "string", "name": "agg", "min": 1, "max": 1, "allowedValues": ["count", "sum", "avg", "min", "max", "any", "all", "collect"], "description": "The reducing function applied over the related row-set: count/sum/avg/min/max (numeric/ordinal reduces over @of); any/all (predicate quantifiers over @filter — @of forbidden; empty set → any=false, all=true); collect (array rollup — of the @of column, or of the carrying field.object's declared @objectRef value object when @of is omitted; the field must be isArray)." }, + { "type": "attr", "subType": "string", "name": "of", "min": 0, "max": 1, "description": "Dotted Entity.field reference identifying the column being aggregated (e.g. 'Week.durationMinutes'). Required for count/sum/avg/min/max; OPTIONAL for collect, where absent means a whole-object rollup of the field's declared @objectRef value object; forbidden for any/all (which quantify over rows via @filter, not a column)." }, + { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the aggregated rows (e.g. 'Program.weeks' or 'Program.weeks.workouts'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows the aggregate spans (required for any/all, where it is the quantified predicate). A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time; codegen renders it per target (e.g. SQL FILTER (WHERE ...) or SQLite CASE WHEN for a relational view). A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity, else the @via terminal) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." }, + { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Set (collect-only) to dedupe collected values (set semantics). Not supported on a whole-object collect (@of omitted): it is a guaranteed no-op whenever the value object carries the primary key, and a silent no-op is worse than a refusal." }, + { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 0, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. On @agg:collect sets element order (non-distinct only); on origin.first (required) selects the row. Semantic — carries no SQL syntax." } + ] + }, + { + "type": "origin", + "subType": "computed", + "description": "A row-level value computed from the base entity's own fields via a structured expression tree (@expr). No related rows, no @via. Read-only; the expression's inferred type must equal the field's declared subType.", + "whenToUse": "A projection field is a cheap derived value over the base row itself (e.g. 'payload IS NOT NULL' to avoid shipping a heavy column). Declare the expression tree instead of hand-writing the derived SELECT column.", + "children": [ + { "type": "attr", "subType": "expression", "name": "expr", "min": 1, "max": 1, "description": "The structured expression tree computing this field's value from the base entity's own fields (closed node grammar; shares the filter op vocabulary). Its inferred root type must equal the field's declared subType (ERR_COMPUTED_TYPE_MISMATCH)." } + ] + }, + { + "type": "origin", + "subType": "function", + "implementedIn": ["typescript", "csharp"], + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", + "children": [ + { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, + { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, + { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." }, + { "type": "attr", "subType": "string", "name": "params", "isArray": true, "min": 0, "max": 1, "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." }, + { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc)." } + ] + }, + { + "type": "origin", + "subType": "first", + "description": "The single related row selected by @orderBy along @via, projecting its @of column (argmax then project). Latest = @orderBy desc. Read-only; empty related set (after @filter) → null, so the field must not be @required.", + "whenToUse": "A projection needs one related row's column chosen by an ordering — 'the latest child's status', 'the earliest event's timestamp'. Declare @via + @of + @orderBy instead of hand-writing the correlated ORDER BY … LIMIT 1 subquery.", + "rules": "@via may be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029). The related entity's primary key ascending is always appended as the final ordering tie-breaker so the selection is deterministic.", + "children": [ + { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference identifying the column projected from the selected row (e.g. 'ChildA.label'). Type-preserving: the field's declared subType must equal this column's subType (#185 doctrine)." }, + { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Dotted relationship path from the base entity to the related rows (e.g. 'Parent.childAs'). May be omitted only when exactly one single-hop relationship leads from the base entity to the @of entity (FR-024, ADR-0029)." }, + { "type": "attr", "subType": "string", "name": "orderBy", "isArray": true, "min": 1, "max": 1, "description": "Ordering keys as 'field[:asc|desc]' (default asc) over the related entity's fields; nulls sort last. Selects the single row (the first after ordering). The related PK ascending is appended as the deterministic tie-breaker. Semantic — carries no SQL syntax." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional structured predicate scoping which related rows are eligible for selection. A portable attr.filter object (eq/ne/in/isNull with and/or), desugared to canonical { field: { op: value } } at parse time. A clause value may also be a relative date ({ now: \"\", startOf? }) on a date or timestamp field, or — correlated-filter — { field: \"\" }, the base row's field, compared with eq/ne/gt/gte/lt/lte or the null-safe isDistinctFrom / isNotDistinctFrom (rc.19)." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment.filter declared on the related entity (the @of entity) — rc.19 origin-segment. Its predicate scopes the related rows, ANDed with @filter, exactly as measure.aggregate @segment does; it may use relative dates." } + ] + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/prompt.json b/server/rust/metaobjects/data/metamodel/prompt.json new file mode 100644 index 0000000000..85b17b61b2 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/prompt.json @@ -0,0 +1,99 @@ +{ + "provider": "metaobjects-prompt", + "extends": [ + { + "type": "field", + "subType": "*", + "children": [ + { + "type": "attr", + "subType": "boolean", + "name": "xmlText", + "min": 0, + "max": 1, + "description": "When true, this field receives its element's XML TEXT CONTENT during tolerant extract (JAXB @XmlValue / Jackson @JacksonXmlText / .NET [XmlText]) instead of a same-named child. No effect when the eliciting prompt's @responseFormat is json." + }, + { + "type": "attr", + "subType": "string", + "name": "example", + "min": 0, + "max": 1, + "description": "FR-010: an example value for this field, shown in the generated output-format prompt fragment." + }, + { + "type": "attr", + "subType": "string", + "name": "instruction", + "min": 0, + "max": 1, + "description": "FR-010: a short instruction for this field, shown in the generated output-format prompt fragment." + } + ] + }, + { + "type": "field", + "subType": "enum", + "children": [ + { + "type": "attr", + "subType": "properties", + "name": "enumAlias", + "min": 0, + "max": 1, + "description": "Map of alternate/off-vocabulary tokens to canonical enum members; feeds the FR-010 tolerant extract alias-fold." + }, + { + "type": "attr", + "subType": "properties", + "name": "enumDoc", + "min": 0, + "max": 1, + "description": "Map of enum member to a human-readable description; shown per-member in the FR-010 'guide'-style prompt fragment." + }, + { + "type": "attr", + "subType": "string", + "name": "coerceDefault", + "min": 0, + "max": 1, + "description": "Fallback enum member used by tolerant extract when a present value cannot be coerced; must be one of the field's @values." + }, + { + "type": "attr", + "subType": "string", + "name": "normalize", + "min": 0, + "max": 1, + "default": "strip", + "allowedValues": [ + "none", + "collapse", + "strip" + ], + "description": "ASCII normalization mode for tolerant enum extract (none|collapse|strip, default strip). On field.enum it is per-field; on object.value it is the default for the object's enum fields." + } + ] + }, + { + "type": "object", + "subType": "value", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "normalize", + "min": 0, + "max": 1, + "default": "strip", + "allowedValues": [ + "none", + "collapse", + "strip" + ], + "description": "ASCII normalization mode for tolerant enum extract (none|collapse|strip, default strip). On field.enum it is per-field; on object.value it is the default for the object's enum fields." + } + ] + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/relationship.json b/server/rust/metaobjects/data/metamodel/relationship.json new file mode 100644 index 0000000000..0fd2d5b1a9 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/relationship.json @@ -0,0 +1,68 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "relationship", + "subType": "base", + "description": "Abstract relationship base — shared shape for the concrete association/aggregation/composition subtypes; not authored directly. A `relationship.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.", + "rules": "@cardinality is an open string at the metamodel level ('one'/'many', and Java-canonical composite forms such as 'many-to-one'); @objectRef names the target entity. M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. @onDelete/@onUpdate carry referential actions (cascade/set-null/restrict/no-action).", + "children": [ + { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, + { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, + { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, + { "type": "attr", "subType": "string", "name": "onDelete", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on parent delete. Default derives from subtype (composition→cascade, aggregation→set-null, association→restrict)." }, + { "type": "attr", "subType": "string", "name": "onUpdate", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on key update. Default cascade." } + ] + }, + { + "type": "relationship", + "subType": "association", + "description": "A plain reference to another entity — no ownership; the target has an independent lifecycle (default @onDelete restrict).", + "whenToUse": "A plain directed reference to another entity, no ownership or cascade. The lightest link — when you just need to point at another entity.", + "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Association is a plain reference — the target's lifecycle is independent (default @onDelete restrict).", + "children": [ + { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, + { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, + { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, + { "type": "attr", "subType": "string", "name": "onDelete", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on parent delete. Default derives from subtype (composition→cascade, aggregation→set-null, association→restrict)." }, + { "type": "attr", "subType": "string", "name": "onUpdate", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on key update. Default cascade." } + ] + }, + { + "type": "relationship", + "subType": "aggregation", + "description": "A shared/independent containment — the parent groups the target but does not own its lifecycle (default @onDelete set-null).", + "whenToUse": "One entity groups others it does NOT own (children outlive the parent; delete sets the FK null). Use instead of composition when there is no ownership.", + "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Aggregation is shared/independent — the target outlives the parent (default @onDelete set-null).", + "children": [ + { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, + { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, + { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, + { "type": "attr", "subType": "string", "name": "onDelete", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on parent delete. Default derives from subtype (composition→cascade, aggregation→set-null, association→restrict)." }, + { "type": "attr", "subType": "string", "name": "onUpdate", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on key update. Default cascade." } + ] + }, + { + "type": "relationship", + "subType": "composition", + "description": "An owned containment — the parent owns the target's lifecycle; deleting the parent deletes the children (default @onDelete cascade).", + "whenToUse": "You need a parent that OWNS a child collection (one-to-many, cascade on delete). Declare it to generate the FK + typed navigation instead of a bare FK field + hand-written joins.", + "rules": "M:N is expressed by @cardinality:'many' + @objectRef + @through: @through names a junction entity that MUST declare two identity.reference children (one per FK side), and the relationship's FK fields are DERIVED from those references — never restated. @sourceRefField disambiguates a DIRECTED self-join by naming the source-side FK field on the junction, or on a @cardinality:'one' relationship names which of several identity.reference nodes onto the same target it navigates when name-pairing does not resolve it uniquely; @symmetric marks an UNDIRECTED self-join (union-on-read) valid only when @objectRef == the declaring entity; the two are mutually exclusive. Composition is owned lifecycle — the children do not outlive the parent (default @onDelete cascade).", + "children": [ + { "type": "attr", "subType": "string", "name": "cardinality", "min": 0, "max": 1, "description": "Cardinality of the relationship target (e.g. 'one', 'many', 'many-to-one')." }, + { "type": "attr", "subType": "string", "name": "objectRef", "min": 0, "max": 1, "description": "Name or fully-qualified name of the target object the relationship points to (e.g. 'Week' or 'acme::vehicle::Car')." }, + { "type": "attr", "subType": "string", "name": "through", "min": 0, "max": 1, "description": "Junction (through) entity name for M:N relationships — a third entity declaring two identity.reference children, one per FK side. The relationship's FK fields are derived from those references." }, + { "type": "attr", "subType": "string", "name": "sourceRefField", "min": 0, "max": 1, "description": "Disambiguates which reference/FK field a relationship uses when more than one candidate exists: on a directed self-join M:N it names the junction's source-side reference (mutually exclusive with @symmetric), and on a @cardinality:'one' relationship it names which of several identity.reference nodes onto the same target the relationship navigates when name-pairing does not resolve it uniquely." }, + { "type": "attr", "subType": "boolean", "name": "symmetric", "min": 0, "max": 1, "description": "Undirected self-join flag (union-on-read). Valid only when @objectRef == the declaring entity. Mutually exclusive with @sourceRefField." }, + { "type": "attr", "subType": "string", "name": "onDelete", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on parent delete. Default derives from subtype (composition→cascade, aggregation→set-null, association→restrict)." }, + { "type": "attr", "subType": "string", "name": "onUpdate", "min": 0, "max": 1, "allowedValues": ["cascade", "set-null", "restrict", "no-action"], "description": "Referential action on key update. Default cascade." } + ] + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/reporting.json b/server/rust/metaobjects/data/metamodel/reporting.json new file mode 100644 index 0000000000..adbe87f9ed --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/reporting.json @@ -0,0 +1,51 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { "type": "dimension", "subType": "attribute", + "description": "A named group-by attribute of the entity that declares it (FR-044). Groups report rows by a column value as-is. @of names Entity.field: the owning entity, or the @via terminal. @via may follow only to-one hops, so grouping by a related row's column can never multiply the measured rows.", + "whenToUse": "A column a dashboard groups by: product, status, region. Declare it once on the fact entity and reference it by name from reports.", + "children": [ + { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own." }, + { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Optional dotted to-one relationship path from the owning entity to the entity @of names (e.g. 'Purchase.program'). Every hop must be @cardinality: one or an identity.reference." } + ] }, + { "type": "dimension", "subType": "time", + "description": "A named time dimension (FR-044): groups report rows by a date or timestamp column truncated to a grain. @of names a field.date or field.timestamp. Weeks start on Monday (ISO-8601) in every lowering. A report names it as 'dimension:grain' and the derived report field is (e.g. purchasedAtDay).", + "whenToUse": "Per-day, per-week or per-month series on a dashboard.", + "children": [ + { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object." }, + { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Optional dotted to-one relationship path, as on dimension.attribute." }, + { "type": "attr", "subType": "string", "name": "grains", "isArray": true, "min": 1, "max": 1, "allowedValues": ["hour", "day", "week", "month", "quarter", "year"], "description": "The grains this dimension supports. Weeks start Monday (ISO-8601). 'hour' is refused on a field.date." } + ] }, + { "type": "measure", "subType": "aggregate", + "description": "A named aggregate over the declaring entity's own rows (FR-044). @agg count without @distinct counts rows; with @distinct it counts distinct values of @of (a list in @of is a distinct count of the tuple). Unlike origin.aggregate, count is NOT distinct by default: a measure aggregates its own rows and dimensions reach only to-one paths, so no join inflates it.", + "whenToUse": "A number a dashboard shows: revenue, purchases, distinct buyers, last activity.", + "children": [ + { "type": "attr", "subType": "string", "name": "agg", "min": 1, "max": 1, "allowedValues": ["count", "sum", "avg", "min", "max", "any", "all"], "description": "The aggregate function. sum/avg need a numeric field; min/max refuse boolean, object and map fields; any/all (boolean OR / AND, Postgres bool_or / bool_and) type the measure boolean and take either a field.boolean in @of or no @of, when they ask whether some row (any) or every row (all) passes the measure's @filter / @segment." }, + { "type": "attr", "subType": "string", "name": "of", "isArray": true, "min": 0, "max": 1, "description": "Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows." }, + { "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Count distinct values. Legal only with @agg: count." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope (a portable attr.filter over the declaring entity's fields). May use relative-date values ({ now: \"-P7D\" }). Combines with @segment by AND." }, + { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment declared on the same entity. Combines with @filter by AND." }, + { "type": "attr", "subType": "int", "name": "default", "min": 0, "max": 1, "description": "Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null), on min/max over a field that is not numeric, and on @agg any/all unless it is 0 (false) or 1 (true). A ratio's operand carries its own @default into the ratio." } + ] }, + { "type": "measure", "subType": "ratio", + "description": "A named quotient of two numeric measure.aggregate siblings (FR-044), lowered as numerator / NULLIF(denominator, 0) and typed decimal. A zero denominator yields null.", + "whenToUse": "Averages per unit that are not a plain avg: average days engaged per starter.", + "children": [ + { "type": "attr", "subType": "string", "name": "numerator", "min": 1, "max": 1, "description": "Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field." }, + { "type": "attr", "subType": "string", "name": "denominator", "min": 1, "max": 1, "description": "Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field." }, + { "type": "attr", "subType": "int", "name": "default", "min": 0, "max": 1, "description": "Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null) and on min/max over a field that is not numeric. A ratio's operand carries its own @default into the ratio." } + ] }, + { "type": "measure", "subType": "derived", + "description": "A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.", + "whenToUse": "A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds).", + "children": [ + { "type": "attr", "subType": "expression", "name": "expr", "min": 1, "max": 1, "description": "The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add | subtract | multiply | divide, args: [a, b] } combines two operands." } + ] }, + { "type": "segment", "subType": "filter", + "description": "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.", + "whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.", + "children": [ + { "type": "attr", "subType": "filter", "name": "filter", "min": 1, "max": 1, "description": "The row scope: a portable attr.filter over the declaring entity's fields. May use relative-date values." } + ] } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/requirement.json b/server/rust/metaobjects/data/metamodel/requirement.json new file mode 100644 index 0000000000..f3017fd78d --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/requirement.json @@ -0,0 +1,189 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "requirement", + "subType": "functional", + "description": "What the product does for a user, stated as one violable claim. Its check is EXISTENCE, run by `meta verify`: a live or partial claim with no implementing node anywhere in its subtree is a warning, and a named node that no longer exists is an error. Hierarchy is nesting — an L1 solution contains its L2 segments, which contain L3 services, and so on down to the levels that reference the model.", + "whenToUse": "Something exists because someone asked for it. L1-L3 are levels of ABSTRACTION AND OWNERSHIP in the problem domain — whose need is this, and at what altitude — and are never a directory, package, deployable or module. Binding to technical constructs happens only at L4 (an object) and L5 (a member), which is the allocation step. Test every node: if a refactor that changes no behaviour would force it to move, its level is wrong.", + "children": [ + { + "type": "attr", + "subType": "int", + "name": "level", + "min": 1, + "max": 1, + "description": "1 solution, 2 segment, 3 service, 4 object, 5 member. L1-L3 are levels of abstraction and ownership in the problem domain, NOT of code structure. Nesting depth must agree with it; skipping a level is legal, going back up is not." + }, + { + "type": "attr", + "subType": "string", + "name": "status", + "min": 1, + "max": 1, + "allowedValues": [ + "planned", + "live", + "partial", + "retired" + ], + "description": "planned intended but not built yet; live implemented and in use; partial implemented with known gaps; retired BUILT THEN DELIBERATELY REMOVED — it must not be rebuilt. A requirement is PRESCRIPTIVE: it states what SHOULD be true and never journals what happened, and retired satisfies that because it states a prohibition in force, falsifiable by the capability reappearing. On retired, @implementedBy is REFUSED at load (ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS) — a retired capability has no implementation by definition, so its references cannot dangle because they cannot exist; @supersededBy names the requirement that replaced it. A dangling @implementedBy is an ERROR on live/partial (the model moved, the requirement is stale) and ALLOWED on planned, where the nodes do not exist YET. Neither planned nor retired contributes to object coverage: planning a capability must not silence the warning that nothing implements it, and neither must retiring one." + }, + { + "type": "attr", + "subType": "string", + "name": "disposition", + "min": 0, + "max": 1, + "allowedValues": [ + "accepted", + "deferred" + ], + "description": "What has been DECIDED about outstanding work — a different question from whether the work is done, which is what @status answers. accepted: the gap is understood and deliberately not being closed. deferred: it will be closed, but not now. ABSENT MEANS UNDECIDED, which is a real and useful state — it is what an unreviewed gap looks like, and it is the one a review should be able to find. Meaningful on planned and partial only; on a status with no outstanding work it is a WARNING. Deliberately NOT a workflow vocabulary: which sprint, who owns it and whether it is in progress belong in the tracker named by @trackedBy, because two systems holding that answer will drift and only one of them is refreshed daily." + }, + { + "type": "attr", + "subType": "string", + "name": "trackedBy", + "isArray": true, + "min": 0, + "max": 1, + "description": "Issue or ticket references for outstanding work — a URL, an owner/repo#123 shorthand, or a tracker key. Free-form and NOT resolved by verify, which does not reach the network; nothing here is checked to exist. Its job is to stop a deferred gap becoming invisible, so verify warns when a deferred requirement names no ticket. Also the right place to link the ticket that a planned requirement will be built under." + }, + { + "type": "attr", + "subType": "string", + "name": "statement", + "min": 1, + "max": 1, + "description": "What the capability is, in one sentence." + }, + { + "type": "attr", + "subType": "string", + "name": "counterexample", + "min": 1, + "max": 1, + "description": "What breaking it looks like, in one sentence — a STATIC falsifiability test, authored once, never a state. A requirement MUST be violable: 'every entity has a uuid primary key' is (point at one with a composite string key); 'things are persisted' is not, and is a description rather than a requirement. Renamed from @violation in 0.24.0, which read as a status." + }, + { + "type": "attr", + "subType": "string", + "name": "supersededBy", + "min": 0, + "max": 1, + "description": "The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not." + }, + { + "type": "attr", + "subType": "string", + "name": "implementedBy", + "isArray": true, + "min": 0, + "max": 1, + "description": "FQN references to the model nodes realising this requirement. Legal on level 4 (an object) and level 5 (a field, view or identity) only; an organisational level carrying it is ERR_REQUIREMENT_LINK_ABOVE_FLOOR. Many-to-many by construction — several requirements may name the same node." + }, + { + "type": "requirement", + "subType": "*", + "name": "*", + "min": 0, + "max": null, + "description": "Nested child requirements. Hierarchy IS nesting — an L1 solution contains its L2 segments, which contain L3 services — so regrouping moves a node rather than editing a parent string, and a requirement is addressable by the same dotted child-name path as every other node." + } + ] + }, + { + "type": "requirement", + "subType": "architectural", + "description": "How the system is built, applied uniformly across the model. Its check is UNIVERSALITY, the opposite polarity to a functional requirement. What `meta verify` enforces is that a live or partial policy is applied at all — one claiming nothing is an error — not that each node it claims complies. Flat by default and object-independent; it may optionally sit in a levelled tree when a quality taxonomy is being used to organise non-functional requirements.", + "whenToUse": "Something exists because every entity here looks like this — a uuid primary key, an @autoSet createdAt, a change-attribution column, tenant scoping. The discriminator is mechanical: did this exist because someone asked for something, or because it is the architecture? For a non-functional tree, an established quality taxonomy makes a good fixed upper structure (e.g. an ISO/IEC 25010 characteristic at L1, its sub-characteristic or a control-catalogue category at L2), with the model-binding claims at L4 and L5 as usual.", + "children": [ + { + "type": "attr", + "subType": "int", + "name": "level", + "min": 0, + "max": 1, + "description": "OPTIONAL here, unlike on a functional requirement where it is required. ABSENT means a flat, object-independent policy that may reference the model directly — the original and still the default form. PRESENT means this node sits in a levelled tree, and then the same rules as functional apply: nesting must agree with the level, and only L4/L5 may carry @implementedBy. Levelling is opt-in so that adding a taxonomy on top of existing flat policies does not invalidate them." + }, + { + "type": "attr", + "subType": "string", + "name": "status", + "min": 1, + "max": 1, + "allowedValues": [ + "planned", + "live", + "partial", + "retired" + ], + "description": "As on requirement.functional. A live or partial architectural requirement claimed by NOTHING is an error: a policy declared and applied to nothing. planned is exempt from that check — it is not applied yet by definition — and retired is exempt because a withdrawn policy governs nothing." + }, + { + "type": "attr", + "subType": "string", + "name": "disposition", + "min": 0, + "max": 1, + "allowedValues": [ + "accepted", + "deferred" + ], + "description": "As on requirement.functional. On an architectural requirement, accepted is the common and important case: a policy that is genuinely not universal, where the exceptions are known and tolerated, is more honest as partial+accepted than as a live claim nobody audits." + }, + { + "type": "attr", + "subType": "string", + "name": "trackedBy", + "isArray": true, + "min": 0, + "max": 1, + "description": "As on requirement.functional. Issue or ticket references for outstanding work; free-form, not resolved." + }, + { + "type": "attr", + "subType": "string", + "name": "statement", + "min": 1, + "max": 1, + "description": "The policy, in one sentence." + }, + { + "type": "attr", + "subType": "string", + "name": "counterexample", + "min": 1, + "max": 1, + "description": "What breaking it looks like — the node that would contradict it. A STATIC falsifiability test, not a state. This is what makes universality checkable. Renamed from @violation in 0.24.0, which read as a status." + }, + { + "type": "attr", + "subType": "string", + "name": "supersededBy", + "min": 0, + "max": 1, + "description": "The requirement that REPLACED this one. Legal on @status: retired only (ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED otherwise), and RESOLVED like any other reference, so a dangling one is ERR_REQUIREMENT_DANGLING_REF and a supersession chain stays walkable: A names B, and when B is retired in turn it names C. That resolution is the whole point — 0.24.0 deregistered an unresolved string, and the 2026-08-10 ruling had asked for the resolving form (point 4) which was never built. A prose note in @notes points one hop and goes stale; this does not." + }, + { + "type": "attr", + "subType": "string", + "name": "implementedBy", + "isArray": true, + "min": 0, + "max": 1, + "description": "FQN references to the nodes applying this policy. High fan-out is normal and expected: one uuid-primary-key requirement is claimed by every entity." + }, + { + "type": "requirement", + "subType": "*", + "name": "*", + "min": 0, + "max": null, + "description": "Nested child requirements. Present so a non-functional tree can be organised by a quality taxonomy the same way a functional tree is organised by capability — the absence of this rule, while requirement.functional had it, is what previously made an architectural node nestable UNDER a functional one but never under another architectural one." + } + ] + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/source.json b/server/rust/metaobjects/data/metamodel/source.json new file mode 100644 index 0000000000..5ea328a387 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/source.json @@ -0,0 +1,17 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "source", + "subType": "base", + "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." + }, + { + "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.", + "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/template.json b/server/rust/metaobjects/data/metamodel/template.json new file mode 100644 index 0000000000..e758c47870 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/template.json @@ -0,0 +1,308 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "template", + "subType": "base", + "description": "Abstract base template \u2014 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) \u2014 this subtype is a registry anchor concrete subtypes inherit from, never a node in a document.", + "rules": "A single MetaTemplate node class backs every template subtype (no subType\u2192class dispatch); the subtype selects which reserved-attr set applies. @format (a closed-enum ATTRIBUTE, never a subtype) drives the render engine's escaper/whitespace behavior, so a new format costs one escaper + one enum value rather than a new subtype + cross-language port." + }, + { + "type": "template", + "subType": "prompt", + "description": "An LLM-targeted renderable prompt template (FR-004). Carries the generic reference + governance attrs plus the LLM overlay (@maxTokens / @requiredSlots / @model / @responseRef). Its renderable body is required via @textRef. A prompt declaring @responseRef also owns the INBOUND half (ADR-0052): the parser-on-receipt, the FR-010 response-format fragment (@promptStyle), and the reply syntax (@responseFormat).", + "whenToUse": "You are sending text to an LLM. Declare a prompt template with a typed payload so the prompt is versioned, drift-checked against its fields, and cache-stable \u2014 instead of string-building it in code. Add @responseRef when you also want the reply parsed into a typed shape.", + "rules": "prompt requires @payloadRef (the typed payload it renders against) AND @textRef (the body text, provider-resolved at render time \u2014 enforced in the loader's validateTemplatePayloadRefs pass, not at the attr layer where @textRef is relaxed to optional so template.output email can omit it). @format is the syntax of the rendered PROMPT body, a closed enum keyed by the render engine's escaper; @responseFormat (ADR-0053) is the syntax of the model's REPLY. @responseRef (optional) names the response value-object the prompt expects, drives typed LLM-call trace derivation, and is the sole gate on the inbound codegen tier \u2014 which keys on its presence, never on a format value.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "payloadRef", + "min": 1, + "max": 1, + "description": "Reference to the payload (a view-object / projection) this template renders against." + }, + { + "type": "attr", + "subType": "string", + "name": "textRef", + "min": 0, + "max": 1, + "description": "2-layer logical reference (group/source) to the body text, resolved by a provider at render time." + }, + { + "type": "attr", + "subType": "string", + "name": "format", + "min": 0, + "max": 1, + "default": "text", + "allowedValues": [ + "text", + "html", + "xml", + "csv", + "json", + "markdown", + "spreadsheet" + ], + "description": "Output format; drives the render engine's escaping/whitespace behavior." + }, + { + "type": "attr", + "subType": "int", + "name": "maxChars", + "min": 0, + "max": 1, + "description": "Size budget for the rendered output, in characters." + }, + { + "type": "attr", + "subType": "string", + "name": "owner", + "min": 0, + "max": 1, + "description": "Governance: the owner of this template." + }, + { + "type": "attr", + "subType": "string", + "name": "since", + "min": 0, + "max": 1, + "description": "Governance: the version this template was introduced in." + }, + { + "type": "attr", + "subType": "string", + "name": "requiredTags", + "isArray": true, + "min": 0, + "max": 1, + "description": "Output tags the rendered text must contain (drives the verify output-tag check)." + }, + { + "type": "attr", + "subType": "int", + "name": "maxTokens", + "min": 0, + "max": 1, + "description": "Token budget for the rendered prompt (LLM-specific)." + }, + { + "type": "attr", + "subType": "string", + "name": "requiredSlots", + "isArray": true, + "min": 0, + "max": 1, + "description": "Slots that must resolve at render time (drives the verify check)." + }, + { + "type": "attr", + "subType": "string", + "name": "model", + "min": 0, + "max": 1, + "description": "Target model id (LLM-specific)." + }, + { + "type": "attr", + "subType": "string", + "name": "responseRef", + "min": 0, + "max": 1, + "description": "Optional ref to the response value-object this prompt expects (peer of @payloadRef; drives typed LLM-call trace derivation). Its presence is the sole gate on the inbound codegen tier (ADR-0052): parser-on-receipt, tolerant extract, and the FR-010 response-format fragment." + }, + { + "type": "attr", + "subType": "string", + "name": "promptStyle", + "min": 0, + "max": 1, + "default": "guide", + "allowedValues": [ + "guide", + "inline", + "exampleOnly" + ], + "description": "FR-010 response-format fragment presentation: 'guide' (prose list + example), 'inline' (inline placeholders / enum choices), or 'exampleOnly' (filled skeleton). Guidance is never emitted as comments." + }, + { + "type": "attr", + "subType": "string", + "name": "responseFormat", + "min": 0, + "max": 1, + "default": "json", + "allowedValues": [ + "json", + "xml" + ], + "description": "ADR-0053: the syntax of the model's REPLY, read by the parser-on-receipt and the FR-010 response-format fragment. Distinct from @format, which is the syntax of the rendered PROMPT body. Two members because two is what every shipping consumer dispatches on; the other @format members are reserved-not-registered." + } + ] + }, + { + "type": "template", + "subType": "output", + "description": "An output / serialization template (FR-004): every rendered artifact other than an LLM prompt \u2014 a document (email, export, docs, config) or an email. Carries the generic reference + governance attrs and the @kind + email part-refs. OUTBOUND ONLY (ADR-0052) \u2014 it renders, and generates no parser.", + "whenToUse": "You render a document/email/serialized output from typed data. Declare an output template so the {{fields}} are drift-checked against the payload VO at build time. To parse a model's reply instead, declare @responseRef on the template.prompt that elicits it \u2014 never a template.output.", + "rules": "output is either a document (@kind=\"document\" or absent \u2192 renders @textRef in @format to one string) or an email (@kind=\"email\" \u2192 renders subject + html + optional text to a structured EmailDocument). The cross-field presence rule is enforced in the loader's validateTemplatePayloadRefs pass: document requires @textRef; email requires @subjectRef AND @htmlBodyRef (with @textBodyRef optional) and carries NO @textRef. @format is a closed enum keyed by the render engine's escaper. template.output is OUTBOUND ONLY (ADR-0052): it emits a render helper and nothing that reads a model's reply \u2014 the parser-on-receipt, the tolerant extract and the FR-010 response-format fragment all belong to template.prompt @responseRef.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "payloadRef", + "min": 1, + "max": 1, + "description": "Reference to the payload (a view-object / projection) this template renders against." + }, + { + "type": "attr", + "subType": "string", + "name": "textRef", + "min": 0, + "max": 1, + "description": "2-layer logical reference (group/source) to the body text, resolved by a provider at render time." + }, + { + "type": "attr", + "subType": "string", + "name": "format", + "min": 0, + "max": 1, + "default": "text", + "allowedValues": [ + "text", + "html", + "xml", + "csv", + "json", + "markdown", + "spreadsheet" + ], + "description": "Output format; drives the render engine's escaping/whitespace behavior." + }, + { + "type": "attr", + "subType": "int", + "name": "maxChars", + "min": 0, + "max": 1, + "description": "Size budget for the rendered output, in characters." + }, + { + "type": "attr", + "subType": "string", + "name": "owner", + "min": 0, + "max": 1, + "description": "Governance: the owner of this template." + }, + { + "type": "attr", + "subType": "string", + "name": "since", + "min": 0, + "max": 1, + "description": "Governance: the version this template was introduced in." + }, + { + "type": "attr", + "subType": "string", + "name": "requiredTags", + "isArray": true, + "min": 0, + "max": 1, + "description": "Output tags the rendered text must contain (drives the verify output-tag check)." + }, + { + "type": "attr", + "subType": "string", + "name": "kind", + "min": 0, + "max": 1, + "default": "document", + "allowedValues": [ + "document", + "email" + ], + "description": "Output shape: 'document' (renders @textRef in @format \u2192 one string) or 'email' (renders subject + html + optional text \u2192 a structured EmailDocument)." + }, + { + "type": "attr", + "subType": "string", + "name": "subjectRef", + "min": 0, + "max": 1, + "description": "Email only: 2-layer logical reference (group/source) to the subject-line text. Required when @kind=\"email\"." + }, + { + "type": "attr", + "subType": "string", + "name": "htmlBodyRef", + "min": 0, + "max": 1, + "description": "Email only: 2-layer logical reference (group/source) to the HTML body text. Required when @kind=\"email\"." + }, + { + "type": "attr", + "subType": "string", + "name": "textBodyRef", + "min": 0, + "max": 1, + "description": "Email only: 2-layer logical reference (group/source) to the optional plain-text alternative body." + } + ] + }, + { + "type": "template", + "subType": "toolcall", + "description": "A vendor-agnostic LLM tool-call envelope (ADR-0011). Unlike prompt/output it has NO renderable text body \u2014 the body IS the structured output schema resolved via @payloadRef. This is why toolcall is its own subtype rather than template.output + @toolName. Does NOT inherit the generic attrs.", + "rules": "toolcall requires @toolName (the wire tool name surfaced to the LLM) AND @payloadRef (the output value-object the tool produces). @textRef is intentionally absent \u2014 a tool-call has no renderable text. Core keeps toolcall vendor-agnostic; vendor wire details (retry semantics, fallback shapes, parallel invocation, cache hints) are added by consumer providers via registry.extend(TYPE_TEMPLATE, \"toolcall\", { attributes: [...] }). The LLM-facing tool description reuses the @description documentation common attr (added to every type by docProvider), so it is not redeclared here.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "toolName", + "min": 1, + "max": 1, + "description": "Wire tool name surfaced to the LLM (vendor-specific format)." + }, + { + "type": "attr", + "subType": "string", + "name": "payloadRef", + "min": 1, + "max": 1, + "description": "Output value-object the tool produces (resolved against the metamodel)." + }, + { + "type": "attr", + "subType": "string", + "name": "owner", + "min": 0, + "max": 1, + "description": "Governance: the owner of this toolcall." + }, + { + "type": "attr", + "subType": "string", + "name": "since", + "min": 0, + "max": 1, + "description": "Governance: the version this toolcall was introduced in." + }, + { + "type": "attr", + "subType": "int", + "name": "maxTokens", + "min": 0, + "max": 1, + "description": "Per-call token budget for the tool-call's structured response (LLM-specific). Vendor-agnostic config; peer of @maxTokens on template.prompt (#237)." + } + ] + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/transition.json b/server/rust/metaobjects/data/metamodel/transition.json new file mode 100644 index 0000000000..cbac9d3ef7 --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/transition.json @@ -0,0 +1,27 @@ +{ + "provider": "metaobjects-core-types", + "types": [ + { + "type": "transition", + "subType": "base", + "description": "Registry anchor for the attributes every lifecycle move shares (ADR-0054): not authorable.", + "children": [ + { "type": "attr", "subType": "string", "name": "permission", "min": 0, "max": 1, "description": "As on an operation: the permission name the derived command for this transition will ask the policy about (no command is derived yet). A dotted identifier path, as on an operation. Absent and not @public: the derived name `..`, naming the concrete entity, so two entities' transitions of one name ask about different permissions. Read only when the transition derives its own command; a declared operation that claims it uses its own, and verify warns that this one is never read (WARN_TRANSITION_PERMISSION_SHADOWED)." }, + { "type": "attr", "subType": "boolean", "name": "public", "min": 0, "max": 1, "description": "As on an operation: the derived command will call no permission check (no command is derived yet). Declaring it with @permission is ERR_PERMISSION_PUBLIC_CONFLICT." } + ] + }, + { + "type": "transition", + "subType": "action", + "extendsBase": true, + "description": "An allowed move between two values of a `field.enum`, made by an operation (ADR-0066). A `field.enum` with at least one is a lifecycle, named after the field. Its states are the enum's @values, its initial state the enum's @default, its terminal states the members no transition leaves; none of them has vocabulary of its own. Each transition is held to become a guarded update (`... WHERE id = ? AND IN (@from) [AND @condition]`), its own command when no declared operation claims it, its own permission point and its own wire error. No shell is generated yet: nothing is generated from this vocabulary, and the loader and `verify` only check it. Experimental since 1.3.0: the shape may change in a MINOR, including removals and renames (docs/compatibility-policy.md).", + "whenToUse": "A status field whose values may only change in certain ways: a request is submitted from draft, approved or rejected from submitted. Declare each allowed move here; once a shell is generated, the generic update path will no longer write the field. A move that leaves the state where it was (from submitted to submitted) records an action that changes nothing but still happened, such as a first approval of two.", + "rules": "Legal only under a `field.enum` of an `object.entity` (ERR_TRANSITION_NOT_ON_ENTITY). A concrete entity with a lifecycle and a source needs a writable one (ERR_TRANSITION_NOT_ON_ENTITY); on an entity with no source the lifecycle loads and is inert, deriving no command until a source is added. The field must declare @default (ERR_LIFECYCLE_NO_INITIAL). The field is not an array, and @from names at least one state (ERR_BAD_ATTR_VALUE). Names are unique across every lifecycle of the entity, compared without case, and may not be create, get, list, update or delete in any case (ERR_TRANSITION_NAME_COLLISION). A transition belongs to the entity that declares its field and to every entity extending it, never to an entity whose field merely `extends` that field; an inheritor that redeclares the field without extending it is ERR_LIFECYCLE_REDECLARED.", + "children": [ + { "type": "attr", "subType": "string", "name": "from", "isArray": true, "min": 1, "max": 1, "description": "The states this move may start from: members of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise), at least one (ERR_BAD_ATTR_VALUE when empty). The allowed moves are the business rule itself, so they cannot be computed." }, + { "type": "attr", "subType": "string", "name": "to", "min": 1, "max": 1, "description": "The state this move ends in: one member of the parent enum's @values (ERR_TRANSITION_UNKNOWN_STATE otherwise). May equal a member of @from, which records an action that leaves the state where it was." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "A guard over the entity's own fields, in the attr.expression grammar: the same name, grammar and meaning as on the cross-field validators. The shell will evaluate it against the loaded row and also put it into the guarded update's WHERE (no shell is generated yet). It cannot read the actor; that is the policy's job. A field the entity does not have, or an expression that is not boolean, is ERR_BAD_ATTR_VALUE." } + ] + } + ] +} diff --git a/server/rust/metaobjects/data/metamodel/ui-web.json b/server/rust/metaobjects/data/metamodel/ui-web.json new file mode 100644 index 0000000000..81eb5bfeea --- /dev/null +++ b/server/rust/metaobjects/data/metamodel/ui-web.json @@ -0,0 +1,21 @@ +{ + "provider": "metaobjects-ui-web", + "extends": [ + { + "type": "view", "subType": "textarea", + "children": [ + { "type": "attr", "subType": "int", "name": "rows", "min": 0, "max": 1, "description": "Visible row count for the generated