Skip to content

feat(csharp): add rules-names and contract-types generators, warn on unknown config keys - #633

Merged
dmealing merged 6 commits into
mainfrom
fm/mo-130-lane-csharp-4
Nov 21, 2026
Merged

dmealing merged 6 commits into
mainfrom
fm/mo-130-lane-csharp-4

Conversation

@dmealing

@dmealing dmealing commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

What Changed

  • Adds two opt-in C# layer generators for ADR-0067. rules-names writes <Entity>Rules.g.cs per lifecycle entity, <Api>Operations.g.cs per api.operational, and RuleErrorCodes.g.cs once; it writes nothing for a model with no rules vocabulary. contract-types writes sealed <Entity>Create and <Entity>Update records per writable entity, leaving server-owned members off both and recording which keys an update body carried. Permission names come from the same derivation verify's rules gate uses: RulesCheck helpers are now public for that.
  • Moves the entity attribute and wire-converter writers out of EntityGenerator into the ContractMembers companion, which both entity and contract-types use. Both generators are registered in GeneratorRegistry.
  • dotnet meta init now writes a Generators.Configure hook, and codegen/Program.cs passes it to CodegenCli.Run, so every GenConfig option is reachable on the normal path; gen and verify --codegen both apply it. An unknown top-level key in .metaobjects/config.json now warns once per key with the known-key list and is still ignored. Keys inside C#-owned blocks are still refused.

C# estates: an unknown top-level config key now warns (once per key, with the known-key list; the key is still ignored, and gen still exits 0).

F6 (measurement only, no code change). Removing EF Core from MetaObjects.Codegen would shrink:

  • the tool .nupkg from 2,387,072 B to 1,373,400 B (-42%);
  • the installed tool directory from 11.85 MB to 6.86 MB (-4.99 MB, -42%), 14 DLLs to 6;
  • the codegen project's first restore from 27.5 MB / 12 packages to 2.36 MB / 1 package (the EF closure is about 25.1 MB).

This PR keeps the dependency. Whether to remove it is the captain's call.

Gate: 1 no-mistakes run (one review fix round, inside that run).

Validation

Risk Assessment

✅ Low: Changes are C#-only, opt-in generators plus a warn-only config key check and an additive Configure hook. The three fix-round items (JsonException on a non-object body, reserved-member refusal, writeOnce off Update) are correct in the current code and covered by tests that execute the generated binders. I found no source defect. Beyond the doc edits I made inline, the only gap is a stale concept string in the registry fixture.

Testing

Baseline scripts/ci-local.sh --affected --strict-toolchains already passed and no source changed here, so no broad rerun. I built the C# CLI from this worktree and drove three scenarios live against a disposable scratch project (the real dotnet meta gen, output compiled and executed). All three passed: the rules-names and contract-types output is correct and compiles, with the review-1 and review-2 fixes behaving as the fixes require. The unknown top-level config key warns and is still ignored, while an unknown key in the csharp block is refused. A field named fields is refused with a clear message and no uncompilable contracts file is written. Scratch projects were removed and the worktree is clean. The dotnet build servers were shut down.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Lifecycle model generates rules names, operation names, error codes and create/update records that compile and bind correctly (local dotnet meta CLI, synthetic PurchaseRequest model) ✅ pass live dotnet MetaObjects.Cli.dll gen (exit 0, 6 files); check.csproj compiles gen-out and runs behaviour checks, ALL PASS; s1-generated-behavior-check.txt and s1-generated-output
Unknown top-level config key warns once and is still ignored (gen succeeds) ✅ pass live s2-unknown-top-level-key-warns.txt: one warning for futureTopLevel, known pending_in_git not warned, exit 0, 6 files written
Unknown key inside a C#-owned config block is refused (adversarial) ✅ pass live s2-unknown-csharp-key-refused.txt: ERR_BAD_ATTR_VALUE naming csharp.bogusKey, exit 2
Field whose name collides with a fixed update-record member is refused, with no partial contracts file (adversarial, review-2 fix) ✅ pass live s3-adversarial-fields-member-refused.txt: refusal naming PurchaseRequest.fields and member Fields, exit 1, PurchaseRequestContracts.g.cs not written
Evidence: Scenario 1 behaviour check output (generated code compiled and executed, ALL PASS)
PASS update non-object null: JsonException: The update body must be a JSON object.
PASS update non-object []: JsonException: The update body must be a JSON object.
PASS update non-object "x": JsonException: The update body must be a JSON object.
PASS explicit null is present: Has(note)=True Note=null
PASS omitted member is absent: Has(note)=False
PASS case-insensitive binding: Total=42 Note=hi
PASS create omits server key: bound without Id
draft acme::purchasing.PurchaseRequest.submit purchasing.decide state_managed
ALL PASS
s1 exit=0
  • Evidence: Scenario 1 generated output (rules-names, operations, error codes, contract-types)
Evidence: Scenario 2 unknown top-level key warning, gen exit 0
dotnet meta: running the generator list in codegen/Generators.cs — `dotnet run --project codegen -- gen metaobjects --out gen-out2 --namespace Acme.Purchasing`.
warning: <scratch-project>/.metaobjects/config.json: unknown top-level key "futureTopLevel" ignored. A newer MetaObjects may have written it; upgrade this tool, or remove the key if it is a misspelling. Known keys: schema_version, pending_in_git, confidence_thresholds, sources, dependencies, libraries, scope, extract, migrate, verify, requirements, naming, wire, api, enums, rules, csharp.
  written: acme/purchasing/PurchaseRequest.g.cs
  written: acme/purchasing/DecisionInput.g.cs
  written: acme/purchasing/PurchaseRequestRules.g.cs
  written: acme/purchasing/PurchasingOperations.g.cs
  written: RuleErrorCodes.g.cs
  written: acme/purchasing/PurchaseRequestContracts.g.cs
dotnet meta gen: 6 file(s) written
Evidence: Scenario 2 unknown csharp-block key refused
dotnet meta: running the generator list in codegen/Generators.cs — `dotnet run --project codegen -- gen metaobjects --out gen-out3 --namespace Acme.Purchasing`.
warning: <scratch-project>/.metaobjects/config.json: unknown top-level key "futureTopLevel" ignored. A newer MetaObjects may have written it; upgrade this tool, or remove the key if it is a misspelling. Known keys: schema_version, pending_in_git, confidence_thresholds, sources, dependencies, libraries, scope, extract, migrate, verify, requirements, naming, wire, api, enums, rules, csharp.
error: ERR_BAD_ATTR_VALUE: <scratch-project>/.metaobjects/config.json: "csharp" has an unknown key "bogusKey" (expected "outDir", "namespace", "providers", "outputLayout" and/or "packageNamespaces")
Evidence: Scenario 3 adversarial field named fields refused
dotnet meta: running the generator list in codegen/Generators.cs — `dotnet run --project codegen -- gen metaobjects --out gen-out4 --namespace Acme.Purchasing`.
  error: codegen failed: contract-types: PurchaseRequest.fields becomes the C# member "Fields", which PurchaseRequestUpdate already declares (Fields, Present, Has, From, Validate). Rename the field.
dotnet meta gen: FAILED (a generator threw — see the error above)

Pipeline

Updates from git push no-mistakes

✅ **Intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 1 info
  • ⚠️ server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs:135 - The generated &lt;Entity&gt;Update.From throws on a non-object body. With the body null (a valid JSON literal), body.Deserialize&lt;T&gt; returns null and falls back to new T(). Then body.EnumerateObject() throws InvalidOperationException, not JsonException, so a PATCH handler that maps JsonException to 400 returns 500 instead. An array body raises JsonException from Deserialize, which is fine. Smallest fix: in the generated From, check body.ValueKind == JsonValueKind.Object before enumerating, and throw JsonException (or return an empty update) otherwise. The tests in ContractTypesGeneratorTests.cs only bind object bodies.
  • ⚠️ server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs:121 - The generated update record has fixed members Fields, Present, Has, From and Validate, plus the member named after each field. A field named fields, present, has, from or validate becomes a duplicate member (CS0102) in the generated file. fields is a plausible name, for example on a form-template entity. Nothing checks this, unlike the Members collision guard in RulesNamesGenerator that refuses clashes with a clear message. In WriteUpdateRecord, refuse a field whose property name collides with the reserved members, naming the entity and field, or move the reserved members behind names a field cannot take. The create record has no fixed members and is not affected.
  • ℹ️ server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs:74 - ServerOwned excludes only readOnly mutability from the update record. A @mutability: writeOnce field stays on &lt;Entity&gt;Update and is bound, and Has reports it as present. The generated routes strip writeOnce fields from PATCH (RoutesGenerator.cs:297, 929, 1652: "frozen after create"), and the record's doc says it holds "the members a client may change". The intent lists readOnly and derived fields only, so this matches its literal wording. It is still worth confirming whether writeOnce should be off the update record, so the contract and the routes agree.

🔧 Fix applied.
📝 1 wording or comment-placement note left for the author (no fix round spent):

  • ℹ️ docs/ports/csharp.md:829 - Round 1 (user-chosen review-3 fix) moved writeOnce fields off &lt;Entity&gt;Update, but the CHANGELOG entry and the contract-types section of the C# port doc still described the update record as leaving off only server-owned members and keys. I edited both prose passages inline to say a writeOnce field stays on the create record and is off the update record. CHANGELOG.md:53-55 carries the same edit. The contract-types concept string in fixtures/generator-registry-conformance/registry.json:115 still lists only server-owned members; I left it alone because it is a shared data file.
✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Lifecycle model generates rules names, operation names, error codes and create/update records that compile and bind correctly (local dotnet meta CLI, synthetic PurchaseRequest model) ✅ pass live dotnet MetaObjects.Cli.dll gen (exit 0, 6 files); check.csproj compiles gen-out and runs behaviour checks, ALL PASS; s1-generated-behavior-check.txt and s1-generated-output
Unknown top-level config key warns once and is still ignored (gen succeeds) ✅ pass live s2-unknown-top-level-key-warns.txt: one warning for futureTopLevel, known pending_in_git not warned, exit 0, 6 files written
Unknown key inside a C#-owned config block is refused (adversarial) ✅ pass live s2-unknown-csharp-key-refused.txt: ERR_BAD_ATTR_VALUE naming csharp.bogusKey, exit 2
Field whose name collides with a fixed update-record member is refused, with no partial contracts file (adversarial, review-2 fix) ✅ pass live s3-adversarial-fields-member-refused.txt: refusal naming PurchaseRequest.fields and member Fields, exit 1, PurchaseRequestContracts.g.cs not written
  • scripts/ci-local.sh --affected --strict-toolchains
  • Baseline (already passed, not re-run): scripts/ci-local.sh --affected --strict-toolchains. No source or test files changed in this turn, so broad regression not re-run.
  • dotnet build server/csharp/MetaObjects.Cli/MetaObjects.Cli.csproj -c Release -o $DEV_SCRATCH/metacli-out (build succeeded, 0 warnings, 0 errors)
  • Scratch project from dotnet MetaObjects.Cli.dll init --root &lt;scratch&gt;; codegen/Codegen.csproj switched to ProjectReference of the worktree MetaObjects.Codegen; Generators.cs lists EntityGenerator, RulesNamesGenerator, ContractTypesGenerator
  • Scenario 1: dotnet MetaObjects.Cli.dll gen metaobjects --out gen-out --namespace Acme.Purchasing on a lifecycle + api.operational + value model (exit 0, 6 files written)
  • Scenario 1: dotnet run --project check.csproj compiling gen-out/**/*.cs with a behaviour program: Update.From on null/[]/"x" body throws JsonException; {"note": null} gives Has(note)=true and Note=null; {} gives Has(note)=false; case-insensitive binding; Create binds without the generated key; rules and operations constants printed. ALL PASS.
  • Scenario 2: config.json with unknown top-level keys futureTopLevel and pending_in_git (known, must not warn), then gen: one warning for futureTopLevel, exit 0, files written.
  • Scenario 2: config.json with csharp.bogusKey, then gen: ERR_BAD_ATTR_VALUE refusal naming the key, exit 2.
  • Scenario 3 (adversarial): added field.string named fields to PurchaseRequest, then gen: contract-types refused naming PurchaseRequest.fields and the member Fields, exit 1, no PurchaseRequestContracts.g.cs written.
  • Restored the clean model and regenerated: exit 0, 0 files changed (unchanged bytes not rewritten).
  • Read-only checks: codegen/Program.cs and Generators.cs contain Generators.Configure, passed to CodegenCli.Run (T11-CS hook scaffolded by init). ContractTypesGenerator.cs:93 excludes writeOnce from the update record, matching docs/ports/csharp.md (review-3 open question appears resolved in code).
⚠️ **Document** - 1 info
  • ℹ️ docs/recipes/write-your-own-generator.md:187 - docs/recipes/write-your-own-generator.md shows a hand-built codegen project with Program.cs calling CodegenCli.Run(args, Generators.All) and no Configure. Still compiles (the two-argument overload remains) and is a minimal example, so left as is. Init-written projects use Generators.Configure, documented in docs/ports/csharp.md.
✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

…-0067 layer 0)

A layer generator, opt-in like any other. For each entity with a lifecycle it
writes <Entity>Rules.g.cs: each lifecycle field's states, initial and terminal
states, transitions, and the permission each derived command asks the policy
about. For each api.operational it writes <Api>Operations.g.cs: each
operation's name, permission and @errors codes. RuleErrorCodes.g.cs holds the
shell's own codes once. A model with no rules vocabulary gets no file.

Permission names and which transitions derive a command come from the same
derivation verify's rules gate runs (RulesCheck.CommandTransitions and the
permission helpers, now public); the project's rules settings ride on the
loaded root as WireFormat does. SHELL_ERROR_CODES is the single list
RESERVED_ERROR_CODES now spreads.

The flat generators are unchanged: RulesInertTests excludes the layer
generators by name and keeps holding every flat one to identical output. The
shared generator manifest gains rules-names (C# only for now).
…rds (ADR-0067 layer 1)

Each writable entity gets <Entity>Create and <Entity>Update sealed records
with the entity's validation attributes and wire converters. Server-owned
members (generated key, autoSet stamp, readOnly and derived fields, TPH
discriminator) are on neither; keys are off the update record. Update.From
records which keys a body carried, so an omitted member and an explicit
null stay apart, and Validate refuses null on a required member. The
lifecycle field stays so the service shell can refuse it with
409 state_managed.

The validation and converter attribute writers move out of EntityGenerator
into ContractMembers, an eject companion of both generators; the entity's
output is unchanged.
…rn on unknown config keys (T11-CS)

dotnet meta init writes Generators.Configure beside the list, and
codegen/Program.cs passes it to CodegenCli.Run. It receives the GenConfig
a run builds from its flags and .metaobjects/config.json and returns the
one the generators see, so options no flag or key sets (ContextTypeName,
PropertyNaming, ProvidedEnumNamespace, PackageNamespaces, TypeOverrides,
Convention, UnmappedStrategy, ...) are reachable on the normal path. gen
and verify --codegen both apply it. An existing project keeps working.

An unknown top-level key in .metaobjects/config.json now warns once per
key, in TypeScript's words with its known-key list, and is still ignored:
a newer MetaObjects may have written it. Keys inside C#-owned blocks stay
refused.
@dmealing
dmealing merged commit d225677 into main Nov 21, 2026
10 checks passed
@dmealing
dmealing deleted the fm/mo-130-lane-csharp-4 branch November 21, 2026 22:40
dmealing added a commit that referenced this pull request Nov 22, 2026
* feat(codegen-ts,metadata): rules names generator (L-TS-1)

rulesNamesFile() writes one rules.names.ts per metadata package that
declares a lifecycle or an operation (ADR-0067 layer 0): each lifecycle's
states, initial and terminal states and transitions, the commands derived
from unclaimed transitions, the declared operations, the permissions they
ask about and the business errors, as as-const values and literal unions.

The names come from the derivations meta verify's rules gate checks, now
shared in metadata (core/transition/commands.ts) and read by both the
gate and the generator's engine walk (codegen-ts rules-walk.ts). The
generator is ejectable, TypeScript-only for now, and silent for a model
without the rules vocabulary.

* feat(runtime-ts,fixtures): the guarded update and its shared persistence scenario (L-TS-3)

ObjectManager.guardedUpdate makes a lifecycle transition's write in one
statement: UPDATE ... SET state = :to WHERE key = :id AND state IN (:from)
[AND condition]. The condition grammar is attr.expression's CHECK subset,
compiled to new not/compare/nullTest WhereClause kinds on all three bundled
drivers; the in-memory driver follows SQL three-valued logic.

fixtures/persistence-conformance/queries/guarded-update.yaml holds every
store driver to it. TypeScript runs it; Java, Kotlin, C# and Python defer
it to their own rules-layer rows.

* feat(codegen-ts): contract types generator (L-TS-2)

contractTypes() writes ADR-0067's contract types layer: the shapes a
caller and a service exchange, with no persistence mapping in them.
Every module imports zod only.

- <Entity>.contract.ts: the read schema and type, the create and
  update schemas, and the typed create and patch inputs.
- <Projection>.contract.ts: the read shape.
- The value modules those shapes reach, byte-identical to the entity
  generator's, so the two collapse into one file when both run.
- <pkg>/operations.contract.ts: each declared operation's input,
  output and business errors.
- errors.contract.ts: the shell and contract wire codes, their HTTP
  statuses, and the error bodies.

The field schemas come from the entity generator's own renderers, and
the tests hold each entity's contract read type equal to the entity
file's on postgres, sqlite and mysql. Two exceptions are named in the
test: a TPH base, and a physical-only jsonb column.

What it covers is the engine walk (contract-walk.ts), so the generator
is ejectable. It is TypeScript-only for now, and it moves no existing
generator's output.

* docs(conformance): count the guarded-update scenario in the orphaned-fixtures sum

L-TS-3 added a persistence scenario and moved the table's persistence row to 68, but the
prose sum under "Orphaned fixtures" still said 67, which the site counts gate refuses.

* feat(sdk,cli): the static agent files built once for every port; Rust as a server language (G1)

The assembler now also runs at build time, once per stack a port's own agent-docs command
serves: each server language alone and Java with Kotlin, each with no client, React, React with
TanStack or Angular (28 stacks). The result is committed at agent-context-shipped/: a manifest
listing each stack's files by project path, and each distinct file once under files/, named by
its content hash (101 files, about 1.1 MB). A port's package embeds the tree; its command finds
the stack by id, pins the guide links to its release tag with one text replacement, and writes
the files, so a C#, JVM, Python or Rust project needs no Node for them (1.3.0 design call 17,
ADR-0033 Amendment 1). agent-context-shipped/README.md is the contract.

- sdk: buildShippedAgentContext(), materializeShippedStack(), shippedStackId() and
  shippedTreeFiles(), and scripts/build-shipped-agent-context.ts (writes only changed bytes;
  --check exits 1 naming each stale file).
- shipped.test.ts: the committed tree is byte-for-byte what the build writes; every stack,
  materialized as a port would, equals assemble() for it with the release ref; the shared
  agent-context-conformance goldens come out of the tree unchanged; an unshipped stack is
  refused, naming the shipped ones.
- Rust: SERVER_LANGS gains rust; `--server rust` (alias rs) is accepted and a root Cargo.toml
  detects it; servers/rust.meta.json and templates/loops/rust.md give the cargo meta gen loop
  and the cargo meta verify step; a rust case joins fixtures/agent-context-conformance.
  Libraries now list Rust among their ports, and the manifest gate checks the copy Rust's
  build.rs embeds (server/rust/metaobjects/data/library).
- The lane map routes agent-context-shipped/ to every lane.

* docs: name C# beside TypeScript for rules-names and contract-types after rebasing onto #633

#633 shipped C#'s own rules-names and contract-types while this branch shipped TypeScript's,
each saying its port was the only one. The registry keeps one entry per name, listing both
ports; the README, business-rules.md and the CHANGELOG say what each port writes.

* feat(codegen-ts): the OpenAPI document states ?search and the filter[or] / filter[and] combinators (R0)

The list-query contract (ADR-0068) made search and the combinators cross-port, but openapi.json
still listed only the per-field filter parameters. The integration check exempted those names
so it would not refuse them.

- search: offered when the row has a field the runtime searches. That is a @filterable text rule
  with like in its band and no format (isSearchField, which mirrors runtime-ts searchFields). The
  description names those fields.
- filter[or] and filter[and]: one deepObject parameter each, offered when the list has any
  filter. A branch nests, which a parameter schema cannot spell, so the description gives the
  grammar and the five-level cap.
- 400 invalid_id is now listed on item GET and DELETE. The routes already answered it, and the
  list-query lane found the gap as soon as the document checked it.

A new contract case, list-query, documents the list-query model. The list-query lane runs
openApiCheck like the other generated lanes. The check now accepts a key under a deepObject
parameter, and takes the names a scenario sends to show they are ignored (the cb cache-buster),
in place of the blanket exemption. contract-behaviours holds the document to runtime-ts's own
parser:
- the searched fields equal searchFields over the generated allowlist;
- the combinator grammar parses to the stated depth and fails one level past it;
- a list with no filter offers neither.
Goldens regenerated. The CONFORMANCE.md count of contract cases is recounted from disk: 22, which
was already stale at 19 on main.

* chore(sdk): rebuild the shipped agent-context tree and the rust golden after rebasing onto main

The audit skill's calibration and capability-checklist references changed on main (#634),
after G1 built agent-context-shipped/ and added the rust agent-context case. The rebuilt tree
and the rust golden take that text; the other five cases already had it.

* no-mistakes(review): apply reviewer inline fixes

* no-mistakes(review): Fix MySQL guarded-update read-back, document invalid_id on update

* no-mistakes(document): fix docs for guarded update and invalid_id

* no-mistakes(document): guarded-update gates MySQL; two lanes red

* no-mistakes(document): Align guarded-update docs with MySQL gate

* test(persistence): the guarded-update scenario runs green on MySQL

The TypeScript runner maps an entity row's timestamp from MySQL's naive
DATETIME text onto the corpus' wire form, and applies the engine mapping
to single-row results (get, create, update, roundtrip) as well as lists.
Python's per-engine skip now honours the port-wide EXPECTED_FAILURES, so
the deferral of guarded-update to L-PY-2 holds on MySQL too.

* no-mistakes(document): align docs with layer generators and PUT

* no-mistakes(document): add Rust to always-on Node sentence
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant