Repository navigation
feat(csharp): add rules-names and contract-types generators, warn on unknown config keys - #633
Merged
Merged
Conversation
…-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
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What Changed
rules-nameswrites<Entity>Rules.g.csper lifecycle entity,<Api>Operations.g.csperapi.operational, andRuleErrorCodes.g.csonce; it writes nothing for a model with no rules vocabulary.contract-typeswrites sealed<Entity>Createand<Entity>Updaterecords per writable entity, leaving server-owned members off both and recording which keys an update body carried. Permission names come from the same derivationverify's rules gate uses:RulesCheckhelpers are now public for that.EntityGeneratorinto theContractMemberscompanion, which bothentityandcontract-typesuse. Both generators are registered inGeneratorRegistry.dotnet meta initnow writes aGenerators.Configurehook, andcodegen/Program.cspasses it toCodegenCli.Run, so everyGenConfigoption is reachable on the normal path;genandverify --codegenboth apply it. An unknown top-level key in.metaobjects/config.jsonnow 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
genstill exits 0).F6 (measurement only, no code change). Removing EF Core from
MetaObjects.Codegenwould shrink:.nupkgfrom 2,387,072 B to 1,373,400 B (-42%);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-toolchainsalready 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 realdotnet 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 namedfieldsis 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.Evidence: Scenario 1 behaviour check output (generated code compiled and executed, ALL PASS)
Evidence: Scenario 2 unknown top-level key warning, gen exit 0
Evidence: Scenario 2 unknown csharp-block key refused
Evidence: Scenario 3 adversarial field named fields refused
Pipeline
Updates from git push no-mistakes
✅ **Intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
server/csharp/MetaObjects.Codegen/Generators/ContractTypesGenerator.cs:135- The generated<Entity>Update.Fromthrows on a non-object body. With the bodynull(a valid JSON literal),body.Deserialize<T>returns null and falls back tonew T(). Thenbody.EnumerateObject()throwsInvalidOperationException, notJsonException, so a PATCH handler that mapsJsonExceptionto 400 returns 500 instead. An array body raisesJsonExceptionfromDeserialize, which is fine. Smallest fix: in the generatedFrom, checkbody.ValueKind == JsonValueKind.Objectbefore enumerating, and throwJsonException(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 membersFields,Present,Has,FromandValidate, plus the member named after each field. A field namedfields,present,has,fromorvalidatebecomes a duplicate member (CS0102) in the generated file.fieldsis a plausible name, for example on a form-template entity. Nothing checks this, unlike theMemberscollision guard in RulesNamesGenerator that refuses clashes with a clear message. InWriteUpdateRecord, 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-ServerOwnedexcludes only readOnly mutability from the update record. A@mutability: writeOncefield stays on<Entity>Updateand is bound, andHasreports 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) movedwriteOncefields off<Entity>Update, but the CHANGELOG entry and thecontract-typessection 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 awriteOncefield stays on the create record and is off the update record. CHANGELOG.md:53-55 carries the same edit. Thecontract-typesconcept 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.
scripts/ci-local.sh --affected --strict-toolchainsBaseline (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 fromdotnet MetaObjects.Cli.dll init --root <scratch>; codegen/Codegen.csproj switched to ProjectReference of the worktree MetaObjects.Codegen; Generators.cs lists EntityGenerator, RulesNamesGenerator, ContractTypesGeneratorScenario 1:dotnet MetaObjects.Cli.dll gen metaobjects --out gen-out --namespace Acme.Purchasingon a lifecycle + api.operational + value model (exit 0, 6 files written)Scenario 1:dotnet run --project check.csprojcompiling 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), thengen: one warning for futureTopLevel, exit 0, files written.Scenario 2: config.json with csharp.bogusKey, thengen: ERR_BAD_ATTR_VALUE refusal naming the key, exit 2.Scenario 3 (adversarial): added field.string namedfieldsto PurchaseRequest, thengen: 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).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.