Skip to content

feat(csharp): write C# generators through CsWriter; add migrate.foreignKeyTargets - #620

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

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

Conversation

@dmealing

@dmealing dmealing commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

What Changed

  • C# generators write through MetaObjects.Codegen.Writer.CsWriter (ADR-0063, C# amendment). The entity, DbContext, routes, filter allowlist, names, callable, output-prompt, output-parser, extractor, report-export, requirement-tests, reverse-finder, expression-index and render-helper generators no longer type indentation or line breaks by hand. Output is unchanged on the 737 model fixtures except for the layout details the writer now owns (listed in CHANGELOG.md). Owned or subclassed generators must update hook signatures from StringBuilder to CsWriter. A layout ratchet test fails on hand-typed layout, and its allowlist only shrinks.
  • C#: a @sequenceStart whose migrations project lacks [assembly: DesignTimeServicesReference] now fails generation with ERR_DESIGN_TIME_REFERENCE_MISSING when the context's ModelSnapshot.cs is visible in that project. Runs that cannot tell, and projects with no @sequenceStart, still get a warning.
  • New migrate.foreignKeyTargets setting ("refuse" default, or "warn"). Wired through the SDK config schema, migrate-ts, the CLI migrate and verify --db commands, and the Rust config reader. "warn" reports a foreign key onto a non-unique target instead of refusing it. The refusal hint now names the setting. Documented in docs/features/migrations-and-drift.md.
Validation

Risk Assessment

✅ Low: The C# writer conversions trace to unchanged output, apart from the whitespace differences the CHANGELOG lists, and the foreignKeyTargets setting is applied on every migrate, verify and offline-plan path I checked; only a weak test and a minor sort-order gap remain.

Testing

Broad regression came from the configured scripts/ci-local.sh --affected --strict-toolchains, which passed at the target commit; not re-run. Three live scenarios drove the codegen tool built from source on disposable metadata. (1) M:N target with credential: head output compiles; the pre-fix commit reproduces CS0246, so the cov-1 fix is verified. (2) Kitchen-sink fixture, base vs head, 11 generators, 227 files: the only difference is the CHANGELOG-documented ReportExportWriter trailing newline. (3) Package-mapped report: home usings sit contiguous before the namespace and export files compile; the remaining compile errors are a pre-existing DecimalWire ambiguity that also exists on base. Not driven live: the review-2 IValidatableObject override path and the RenderHelper, RequirementTests and ApiDocs generators, which were not in the parity run. Overall result: pass.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
M:N target with credential compiles (cov-1): Author has M:N to Account, Account has view.password; generated AuthorRoutes builds on head ✅ pass live summary.txt S1; AuthorRoutes-head.g.cs; dotnet build of generated app over codegen built from dcca89d -> Build succeeded
Adversarial: same model on pre-fix commit 91e5a68 fails to compile with CS0246 (proves the scenario catches the regression) ✅ pass live AuthorRoutes-prefix.g.cs; dotnet build error CS0246 'CredentialOmittingResult' at AuthorRoutes.g.cs(226)
CsWriter refactor output parity: kitchen-sink fixture (227 files, 11 generators) generated by base 48c344a and head dcca89d is byte-identical except the documented ReportExportWriter trailing newl… ✅ pass live parity-base-vs-head.diff (single hunk, ReportExportWriter.g.cs line 169)
Package-mapped report (cov-2): header usings are contiguous before namespace, and export files compile ✅ pass live package-namespace-base-vs-head.diff; AllTypesBreakdownExport.header-head.txt; compile of generated tree shows no Export-file errors
Evidence: Scenario summary
C# lane live validation (target dcca89d651, base 48c344ad46)
S1 M:N credential route compile (cov-1 fix):
   pre-fix 91e5a68a7e  -> error CS0246 'CredentialOmittingResult' at AuthorRoutes.g.cs(226)
   head dcca89d651     -> Build succeeded (AuthorRoutes-head.g.cs, AuthorRoutes-prefix.g.cs)
S2 Output parity base 48c344ad vs head, 227 files, 11 generators, meta.fitness.json:
   only difference ReportExportWriter.g.cs trailing newline (parity-base-vs-head.diff; documented in CHANGELOG)
S3 Package-mapped report usings (cov-2 fix), config csharp.packageNamespaces fitness->Acme.Parity.Fitness:
   header: System usings, using Acme.Parity.Fitness;, blank line, namespace (AllTypesBreakdownExport.header-head.txt)
   compile: export files compile; only errors are CS0104 DecimalWire ambiguity, same text as base (pre-existing, not this change)
Evidence: Base vs head generated output diff (kitchen-sink)
diff -r parity-base/gen/ReportExportWriter.g.cs parity-head/gen/ReportExportWriter.g.cs
169c169
< }
\ No newline at end of file
---
> }
Evidence: Base vs head diff with package namespace mapping
diff -r pkgns-base/gen/ReportExportWriter.g.cs pkgns-head/gen/ReportExportWriter.g.cs
169c169
< }
\ No newline at end of file
---
> }
Evidence: Head AuthorRoutes (M:N credential, compiles)
// <auto-generated/>
// Generated by MetaObjects routes-generator. Do not edit by hand.
#nullable enable
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using MetaObjects.Codegen.Runtime;

namespace Acme.Authors;

public static class AuthorRoutes
{
    private static readonly global::System.Collections.Generic.HashSet<string> SortAllowlist = new(global::System.StringComparer.OrdinalIgnoreCase)
    {
        "Id",
        "Name",
    };

    private static readonly global::System.Collections.Generic.Dictionary<string, bool> SortDefaultDesc = new(global::System.StringComparer.OrdinalIgnoreCase)
    {
    };

    // api.unknownFields: reject — the declared field names (wire spelling); any other body key is a 400.
    private static readonly global::System.Collections.Generic.HashSet<string> KnownFields = new(global::System.StringComparer.Ordinal)
    {
        "id",
        "name",
    };

    /// <summary>Maps <c>Author</c> REST routes. Unauthenticated — see remarks.</summary>
    /// <remarks>
    /// These endpoints are unauthenticated. Guard them by mapping on a group that requires
    /// authorization, e.g. <c>app.MapGroup("").RequireAuthorization().MapAuthorRoutes();</c>
    /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount:
    /// eject this generator with <c>dotnet meta eject</c> and hand-write those endpoints.
    /// </remarks>
    public static IEndpointRouteBuilder MapAuthorRoutes(this IEndpointRouteBuilder app, string prefix = "/api")
    {
        IEndpointRouteBuilder mount = app;
        app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter());
        app.MapGet(prefix + "/authors", async (HttpContext http, global::Acme.Authors.AppDbContext db) =>
        {
            var qs = http.Request.Query;
            IQueryable<Author> q = db.Authors.AsNoTracking();

            // Filter: ?filter[<field>][<op>]=<value> against the per-entity allowlist.
            var filter = EfCoreFilterDispatch.Validate<Author>(FilterParser.Parse(qs, AuthorFilterAllowlist.Fields, AuthorFilterAllowlist.OpsByField));
            if (filter.ErrorEnvelope is not null)
                return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });
            q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates);

            // Sort: ?sort=field:asc|desc against the static allowlist.
            if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))
            {
                var parts = sortRaw.ToString().Split(':', 2);
                var field = parts[0];
                if (!SortAllowlist.TryGetValue(field, out var resolved))
                    return Results.BadRequest(new { error = "invalid_sort", field });
                var desc = parts.Length > 1
                    ? string.Equals(parts[1], "desc", global::System.StringComparison.OrdinalIgnoreCase)
                    : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd;
                q = ApplySortAuthor(q, resolved, desc);
            }

            // Pagination: ?offset=N first (skip), then ?limit=N (take).
            if (qs.TryGetValue("offset", out var offsetRawBad) && !(int.TryParse(offsetRawBad, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var offsetBad) && offsetBad >= 0))
                return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRawBad.ToString(), expected = "a non-negative integer (0 or more)" });
            if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0)
                q = q.Skip(offset);
            // api.pagination: no limit takes defaultLimit; a limit above maxLimit is refused.
            if (qs.TryGetValue("limit", out var limitRawNeg) && !(long.TryParse(limitRawNeg, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var limitNeg) && limitNeg >= 0))
                return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRawNeg.ToString(), expected = "a non-negative integer (0 or more)" });
            var __take = 50;
            if (qs.TryGetValue("limit", out var limitRaw) && long.TryParse(limitRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit >= 0)
            {
                if (limit > 1000) return Results.BadRequest(new { error = "limit_too_large", maxLimit = 1000 });
                __take = (int)limit;
            }
            q = q.Take(__take);

            var rows = await q.ToListAsync();

            // withCount=1 → { rows, total } envelope; otherwise bare row array.
            var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase));
            if (!withCount) return Results.Ok(rows);
            var totalQ = EfCoreFilterDispatch.ApplyFilter(db.Authors.AsNoTracking(), filter.Predicates);
            var total = await totalQ.CountAsync();
            return Results.Ok(new { rows, total });
        });

        app.MapGet(prefix + "/authors/{id}", async (long id, global::Acme.Authors.AppDbContext db) =>
            await db.Authors.FindAsync(id) is { } found
                ? Results.Ok(found)
                : Results.NotFound(new { error = "not_found" }));

        app.MapPost(prefix + "/authors", async (HttpContext http, global::Acme.Authors.AppDbContext db) =>
        {
            var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions<global::Microsoft.AspNetCore.Http.Json.JsonOptions>)
                http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions<global::Microsoft.AspNetCore.Http.Json.JsonOptions>))!)
                .Value.SerializerOptions;
            global::System.Text.Json.JsonDocument __body;
            try { __body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }
            catch (global::System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }
            using var __bodyScope = __body;
            if (__body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object)
                return ValidationIssues.Unreadable();
            if (UnknownFieldCheck.Reject(__body.RootElement, KnownFields, http) is { } __unknown) return __unknown;
            var __issues = new ValidationIssues();
            var __present = new global::System.Collections.Generic.HashSet<string>(global::System.StringComparer.OrdinalIgnoreCase);
            foreach (var __p in __body.RootElement.EnumerateObject())
                if (__p.Value.ValueKind != global::System.Text.Json.JsonValueKind.Null) __present.Add(__p.Name);
            foreach (var __req in new[] { "name" })
                if (!__present.Contains(__req)) __issues.AddRequired(__req);
            Author? input = null;
            try { input = global::System.Text.Json.JsonSerializer.Deserialize<Author>(__body.RootElement.GetRawText(), jsonOpts); }
            catch (global::System.Exception __e) { __issues.AddReadFailure(__e, typeof(Author)); }
            if (input is null) return __issues.Any ? __issues.ToResult() : ValidationIssues.Unreadable();
            // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored.
            input.Id = default!;
            input.Accounts = new global::System.Collections.Generic.List<global::Acme.Authors.Account>();
            __issues.ValidateObject(input, jsonOpts);
            if (__issues.Any) return __issues.ToResult();
            db.Authors.Add(input);
            try { await db.SaveChangesAsync(); }
            catch (global::System.Exception __save

... [576 bytes truncated] ...

xisting = await db.Authors.FindAsync(id);
            if (existing is null) return Results.NotFound(new { error = "not_found" });
            global::System.Text.Json.JsonDocument body;
            try { body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); }
            catch (global::System.Text.Json.JsonException) { return ValidationIssues.Unreadable(); }
            using var bodyScope = body;
            if (body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object) return ValidationIssues.Unreadable();
            if (UnknownFieldCheck.Reject(body.RootElement, KnownFields, http) is { } __unknown) return __unknown;
            // Deserialize each value with the app's CONFIGURED JSON options, not defaults —
            // a field.timestamp binds to DateTimeOffset via a custom converter registered on
            // ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500.
            var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions<global::Microsoft.AspNetCore.Http.Json.JsonOptions>)
                http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions<global::Microsoft.AspNetCore.Http.Json.JsonOptions>))!)
                .Value.SerializerOptions;
            var entry = db.Entry(existing);
            var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts);
            var __issues = new ValidationIssues();
            foreach (var prop in body.RootElement.EnumerateObject())
            {
                var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null;
                var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr))
                    ?? entry.Metadata.FindProperty(prop.Name)
                    ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase));
                if (target is null) continue;
                var __wire = ValidationIssues.WireName(existing.GetType(), target.Name, jsonOpts);
                if (target.IsPrimaryKey()) continue;                        // PK is route-authoritative
                if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null)
                {
                    // FR-035 PATCH-2: explicit null clears a nullable column; on a
                    // NOT-NULL (@required) column it is a 400 (matching the cross-port contract).
                    if (!target.IsNullable) { __issues.AddRequired(__wire); continue; }
                    entry.CurrentValues[target] = null;
                    continue;
                }
                var clr = global::System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType;
                object? __val;
                try { __val = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); }
                catch (global::System.Exception __e) { __issues.AddReadFailure(__e, clr, __wire); continue; }
                // FR-036 A2 — validate the PRESENT, non-null value with the same per-field
                // DataAnnotations as create. This validates ONLY the present value (never the
                // whole row) so an ABSENT @required field is untouched, not a 400.
                if (!__issues.ValidateProperty(existing, target.Name, __val, jsonOpts)) continue;
                entry.CurrentValues[target] = __val;
            }
            if (__issues.Any) return __issues.ToResult();
            try { await db.SaveChangesAsync(); }
            catch (global::System.Exception __saveError)
            {
                if (ConstraintErrors.Classify(__saveError) is { } __constraint)
                    return Results.Json(
                        new { error = __constraint.Error, constraint = __constraint.Constraint },
                        statusCode: __constraint.Status);
                throw;
            }
            return Results.Ok(existing);
        }
        app.MapPatch(prefix + "/authors/{id}", UpdateAuthor);
        app.MapPut(prefix + "/authors/{id}", UpdateAuthor);

        app.MapDelete(prefix + "/authors/{id}", async (long id, global::Acme.Authors.AppDbContext db) =>
        {
            var existing = await db.Authors.FindAsync(id);
            if (existing is null) return Results.NotFound(new { error = "not_found" });
            db.Authors.Remove(existing);
            try { await db.SaveChangesAsync(); }
            catch (global::System.Exception __saveError)
            {
                if (ConstraintErrors.Classify(__saveError) is { } __constraint)
                    return Results.Json(
                        new { error = __constraint.Error, constraint = __constraint.Constraint },
                        statusCode: __constraint.Status);
                throw;
            }
            return Results.NoContent();
        });

        app.MapGet(prefix + "/authors/{id}/accounts", async (long id, global::Acme.Authors.AppDbContext db) =>
        {
            var relatedIds = (await db.AuthorAccounts.AsNoTracking()
                .Where(j => EF.Property<long>(j, "AuthorId").Equals(id))
                .Select(j => EF.Property<long>(j, "AccountId"))
                .ToListAsync()).ToHashSet();
            if (relatedIds.Count == 0) return Results.Ok(new global::System.Collections.Generic.List<global::Acme.Authors.Account>());
            var rows = await db.Accounts.AsNoTracking()
                .Where(t => relatedIds.Contains(EF.Property<long>(t, "Id")))
                .ToListAsync();
            return (IResult)new CredentialOmittingResult(rows, new string[] { "PinHash" });
        });

        return mount;
    }

    private static IOrderedQueryable<Author> ApplySortAuthor(IQueryable<Author> q, string field, bool desc)
    {
        return field switch
        {
            "Id" => desc ? q.OrderByDescending(x => EF.Property<object>(x!, "Id") == null).ThenByDescending(x => EF.Property<object>(x!, "Id")) : q.OrderBy(x => EF.Property<object>(x!, "Id") == null).ThenBy(x => EF.Property<object>(x!, "Id")),
            "Name" => desc ? q.OrderByDescending(x => EF.Property<object>(x!, "Name") == null).ThenByDescending(x => EF.Property<object>(x!, "Name")) : q.OrderBy(x => EF.Property<object>(x!, "Name") == null).ThenBy(x => EF.Property<object>(x!, "Name")),
            _ => (IOrderedQueryable<Author>)q.OrderBy(x => 0),
        };
    }

    // #484 — a credential (view.password) is never sent: the key is OMITTED from the body, not nulled.
    // Serializes with the app's configured JSON options, then removes the named keys from each row.
    private sealed class CredentialOmittingResult : IResult
    {
        private readonly object _value;
        private readonly string[] _names;
        private readonly bool _envelope;
        private readonly int _status;
        private readonly string? _location;
        public CredentialOmittingResult(object value, string[] names, bool envelope = false, int status = 200, string? location = null)
        { _value = value; _names = names; _envelope = envelope; _status = status; _location = location; }
        public async global::System.Threading.Tasks.Task ExecuteAsync(HttpContext http)
        {
            var opts = ((global::Microsoft.Extensions.Options.IOptions<global::Microsoft.AspNetCore.Http.Json.JsonOptions>)
                http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions<global::Microsoft.AspNetCore.Http.Json.JsonOptions>))!)
                .Value.SerializerOptions;
            var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts);
            // The keys are the serializer's own for these properties and the envelope's rows (naming policy, rename, attribute), never guessed from names.
            SerializerKeys.StripBody(node, _value, _envelope, opts, _names);
            http.Response.StatusCode = _status;
            if (_location is not null) http.Response.Headers.Location = _location;
            await http.Response.WriteAsJsonAsync(node, opts);
        }
    }
}
  • Evidence: Pre-fix AuthorRoutes (CS0246 reproduced) (local file: ~/.no-mistakes/evidence/01M7YM2RYD69PD06RSBHZEB7XM/AuthorRoutes-prefix.g.cs)
Evidence: Package-mapped export file header (head)
// <auto-generated/>
// Generated by MetaObjects report-export. Do not edit by hand.
#nullable enable
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Acme.Parity.Fitness;

namespace Acme.Parity;

/// <summary>The CSV and XML export of the <c>AllTypesBreakdown</c> report: its columns, in derived-field order, over the generated <see cref="AllTypesBreakdown"/> row.</summary>
public static class AllTypesBreakdownExport
  • Outcome: ⚠️ 1 info across 1 run (22m51s)

Pipeline

Updates from git push no-mistakes

✅ **Intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 2 infos
  • ⚠️ server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs:552 - AppendOmitResultClass used to emit the nested CredentialOmittingResult class when the generated text actually contained new CredentialOmittingResult(. It now emits it only when credentials.Count &gt; 0, and that list holds the entity's OWN credentials. Concrete failing case: entity Author has no view.password field but an M:N relationship to Account, which has one. AppendM2mRoute (line 524 -> line 1876) writes OkResult(&#34;rows&#34;, TphUnionCredentialNames(nav.Target, ...)), which is (IResult)new CredentialOmittingResult(...), but AuthorRoutes gets no class because Author's own credentials are empty. The generated code then fails to compile (CS0246). Before this change the text scan caught it. Same gap at the TPH base call site (line 760: baseCredentials covers the base and subtypes, not an M:N target's credentials), via AppendM2mRoute at line 730, and via the TPH subtype M2M mount at line 1761. Fix: make the used argument true whenever any emitted OkResult/CreatedResult had a non-empty list, e.g. also OR in TphUnionCredentialNames(nav.Target, ...) for each M2M nav at 524, 730 and 1761, or have OkResult/CreatedResult record use on the writer.
  • ℹ️ server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs:107 - HomeUsings are written with w.Line(u) into the body, not w.Using(...). When the report's namespace differs from the configured one, the file now reads: using System.Linq;, a blank line, using &lt;home&gt;;, namespace X; directly after, with no blank line. The old output had them together with one blank line before namespace. This compiles, but it contradicts the CHANGELOG claim that output is unchanged, and the pinned hash test uses a model without home usings, so nothing covers it. Fix: write w.Using(...) (the directive text is using ns;, so strip the prefix and the semicolon) or add w.Blank() after the loop.

🔧 Fix applied.
4 issues (1 warning, 3 infos) still open:

  • ℹ️ server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs:107 - HomeUsings are written with w.Line(u) into the body, not w.Using(...). When the report's namespace differs from the configured one, the file now reads: using System.Linq;, a blank line, using &lt;home&gt;;, namespace X; directly after, with no blank line. The old output had them together with one blank line before namespace. This compiles, but it contradicts the CHANGELOG claim that output is unchanged, and the pinned hash test uses a model without home usings, so nothing covers it. Fix: write w.Using(...) (the directive text is using ns;, so strip the prefix and the semicolon) or add w.Blank() after the loop.
  • ℹ️ server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs:107 - The cov-2 fix (HomeUsings now go through w.Using) is correct: PackageBindingResolver.HomeUsings returns using ns;, so the prefix/semicolon strip is right and the home usings print in the same block as using System.Linq;. But no test covers a report whose namespace differs from the configured one. The existing hash-pinned test uses a model without home usings, so a regression to the old w.Line(u) layout would still pass. Add one ReportExportGeneratorTests case with a package-mapped report and assert the generated header has the usings contiguous before namespace. The sibling RoutesGenerator.cs:334 and :650 still emit home usings with w.Line(u) after hand-written using lines; this is safe because the header is not routed through w.Using there.
  • ⚠️ server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs:461 - EntityGenerator now applies , IValidatableObject only through the new validatable parameter on EmitClassHeader / EmitClassDeclarationLine. Before, the base class post-edited the written declaration line (AppendValidatableInterface), so it worked even when a subclass overrode the whole header. Concrete case: an adopter's partial/marker-interface generator, the pattern shown by PartialEntityGenerator in EntityGeneratorExtensibilityTests.cs:50-60, overrides EmitClassHeader and writes public partial class X : IAdopterEntity. If the entity has a cross-field validator (comparison, requiredWhen, atLeastOne, ...), the class still gets Validate(...) but no longer implements IValidatableObject. The code compiles, so DataAnnotations validation silently stops running the rules. The signature change forces the adopter to touch the override, but nothing flags that validatable has to be honoured. CHANGELOG and docs/ports/csharp.md state the new parameter but not this silent-drop consequence. Same sibling: the validatable flag at EmitClassDeclarationLine for TphSubtype (validate is not null &amp;&amp; validatingBase is null). Smallest remedy: say plainly in the docs and hook comments that an override that writes its own declaration must call WithValidatable(decl, validatable); or throw when validatable is true and the written declaration lacks the interface.
  • ℹ️ CHANGELOG.md:13 - CHANGELOG and docs list the renamed or re-shaped hooks, but several public/protected surface changes are unlisted. The first and third entries below are public statics that were made public for owned copies: (1) EntityGenerator.M2mNavProperty(nav, config) returning a string is now WriteM2mNavProperty(CsWriter, nav, config) returning void, and ADR-0034 Amendment 3 made it public for owned copies of other generators. (2) ExtractDelegateEmitter.DelegatingMembers returning a string is now WriteDelegatingMembers(CsWriter, ...). (3) NamesGenerator.Member / MemberGroups became protected. Also, the 'output is unchanged' claims are not exact: a flat-layout shared-enum file with two or more namespaces used to end with an extra blank line after the last } (EntityGenerator.cs, flat.Blank() after the Braced block), and the writer now drops that trailing blank. Stale comments still name the old method at DbContextGenerator.cs:137 and DbContextGenerator.cs:265 (EntityGenerator.M2mNavProperty).

🔧 Fix applied.
2 infos still open:

  • ℹ️ server/csharp/MetaObjects.Codegen.Tests/LayoutRatchet/LayoutRatchetTests.cs:71 - The test An_indentation_unit_hidden_behind_a_constant_is_caught_at_the_repeat has no independent oracle for the constant path it names. Its source also holds new string(&#39; &#39;, 4), which is an IndentRepeat on its own, and .Take(1) hides the second finding. If constant resolution in LayoutAnalyzer.Resolve were broken, Enumerable.Repeat(UNIT, 4) would produce no finding and the test would still pass on the new string call. A plausible wrong behavior it would not reject: the analyzer ignoring same-file constants as the repeat unit. Fix: drop the new string(&#39; &#39;, 4) from the source and assert exactly one IndentRepeat at the Repeat line (no .Take(1)).
  • ℹ️ server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs:144 - With UsingOrder.Sorted, Target() strips only using and ;. using static System.Math; therefore sorts as the target static System.Math, so it is not grouped with System namespaces. using Json = System.Text.Json.JsonSerializer; sorts by Json = .... spec/code-writer.md says Sorted prints System namespaces first, then the rest in ordinal order of the namespace, and the cs-usings-sorted case covers plain usings only. Concrete case: Sorted writer, UsingStatic("System.Math"), Using("Acme") prints using Acme; before using static System.Math;. No reference generator uses Sorted, so nothing shipped is affected. Either sort on the namespace or type a directive names (the text after static or after =), or state the behavior in the spec and add a corpus case.
⚠️ **Test** - 1 info
  • ℹ️ server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs - Pre-existing, not from this change: with csharp.packageNamespaces mapping a package, generated routes import both the generated DecimalWire (package namespace) and MetaObjects.Codegen.Runtime, so references to DecimalWire are CS0104 ambiguous. Identical on base output, so out of scope for this change. Noted for a later fix.
  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
M:N target with credential compiles (cov-1): Author has M:N to Account, Account has view.password; generated AuthorRoutes builds on head ✅ pass live summary.txt S1; AuthorRoutes-head.g.cs; dotnet build of generated app over codegen built from dcca89d -> Build succeeded
Adversarial: same model on pre-fix commit 91e5a68 fails to compile with CS0246 (proves the scenario catches the regression) ✅ pass live AuthorRoutes-prefix.g.cs; dotnet build error CS0246 'CredentialOmittingResult' at AuthorRoutes.g.cs(226)
CsWriter refactor output parity: kitchen-sink fixture (227 files, 11 generators) generated by base 48c344a and head dcca89d is byte-identical except the documented ReportExportWriter trailing newl… ✅ pass live parity-base-vs-head.diff (single hunk, ReportExportWriter.g.cs line 169)
Package-mapped report (cov-2): header usings are contiguous before namespace, and export files compile ✅ pass live package-namespace-base-vs-head.diff; AllTypesBreakdownExport.header-head.txt; compile of generated tree shows no Export-file errors
  • scripts/ci-local.sh --affected --strict-toolchains
  • dotnet build server/csharp/MetaObjects.Cli/MetaObjects.Cli.csproj -c Release -o $DEV_SCRATCH/cs-live/cli
  • Scratch project init + codegen/Codegen.csproj ProjectReference to worktree MetaObjects.Codegen; dotnet run --project codegen -- gen metaobjects --out gen (S1, entity/db-context/routes/filter-allowlist)
  • dotnet build App.csproj (Microsoft.NET.Sdk.Web, EF Core 8.0.10) over generated S1 output at head dcca89d651 -> Build succeeded
  • Same S1 metadata through codegen built from 91e5a68a7e (pre-fix) -> dotnet build -> error CS0246 CredentialOmittingResult at AuthorRoutes.g.cs(226)
  • Base 48c344ad46 vs head dcca89d651 codegen over fixtures/persistence-conformance/canonical/meta.fitness.json, 11 generators, 227 files each; diff -r -> single trailing-newline change in ReportExportWriter.g.cs
  • Package-mapped run (.metaobjects/config.json csharp.packageNamespaces fitness -> Acme.Parity.Fitness, flat layout), base vs head: diff only the same newline; head AllTypesBreakdownExport.g.cs header inspected; compile shows only the pre-existing DecimalWire CS0104 errors, no Export-file errors
  • Configured broad regression: scripts/ci-local.sh --affected --strict-toolchains (baseline, already passed at target commit; not re-run, no source changes this turn)
  • Worktree git status clean after run; all background work stopped (one stuck dotnet run task stopped via TaskStop); scratch under $DEV_SCRATCH/cs-live left in place
🔧 **Document** - 1 issue found → auto-fixed ✅
  • ℹ️ spec/decisions/ADR-0063-generators-own-layout.md:1 - ADR-0063 Status and amendments cover the TypeScript and Python writers but say nothing about the C# writer (CsWriter, six C# conversions, layout ratchet). The authoritative C# writer contract lives in spec/code-writer.md (the C# dialect section) and docs/ports/csharp.md, so the ADR is not wrong, only silent. Left unchanged: ADR is a decision record and a C# section is a judgment call on whether it belongs there.

🔧 Fix applied.
✅ Re-checked - no issues remain.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

… routes (#566)

* fix(python): generated routes hand the repository only the validated input (1.2.1)

The generated FastAPI create, PATCH and PUT handlers validated the body against
<Entity>Create / <Entity>Patch and then passed the RAW body to the repository.
Pydantic ignores undeclared keys and the input models leave out server-owned
fields, so a client-sent id, a readOnly field and a made-up field such as
isAdmin all reached the write. Security fix.

Each handler (plain and TPH per-subtype) now rebinds dto to the keys the input
model validated, at every depth, before any repository call, as the TypeScript
routes do. Undeclared and non-settable keys are dropped silently, never 400'd,
so a client sending an extra harmless field keeps working; values stay the
body's own, so repositories see the same value types as in 1.2.0.

Python package version 1.2.1 only; CHANGELOG entry under Security.
Regression gate: tests/integration/test_generated_router_validated_input.py.

* no-mistakes(document): python routes pass only validated input

* no-mistakes(lint): regenerate showcase site payload for PyPI 1.2.1
…2.x security) (#568)

* fix: generated create routes store only client-settable fields (1.2.x security)

Python 1.2.1 stopped its generated routes from handing raw request input to
the repository. The same audit found related create-path holes in 1.2.0 in
the other four ports; this closes each in its own idiom. Server-owned values
are dropped silently, never answered with 400.

- Java (codegen-spring): create strips a generated id, readOnly and derived
  fields; a TPH per-subtype create also strips the body discriminator and
  sibling-subtype fields.
- Kotlin (codegen-kotlin): create skips readOnly/derived columns; a TPH
  per-subtype create writes only the route subtype's own columns.
- C# (MetaObjects.Codegen): every readOnly property shape gets a private
  setter; create resets a generated id, the TPH discriminator and M:N
  navigations before Add.
- TypeScript (codegen-ts): the update schema omits primary-key fields, so
  PUT/PATCH can no longer re-key a row with an assigned key.

Proof: new shared api-contract scenarios (core + TPH input-server-owned,
TPH foreign discriminator) and a readOnly `role` field in secret-fields, run
in every port's generated lane and the reference lanes; a new `unset`
assertion key in all five harnesses. In-memory test repositories now store
what they are handed, so the scenarios fail on the 1.2.0 generators.

Proposed versions (not published): npm 1.2.2, NuGet 1.2.2, Maven 8.2.2;
PyPI unchanged at 1.2.1. metamodelVersion unchanged.

* fix: keep a @required readOnly field creatable in C# and Java generated create

Pre-gate review follow-ups to the 1.2.x create-input patch:

- C#: the required-key check skips readOnly fields (the private setter
  never binds them), and create validation ignores a violation naming
  only a @required readOnly member, as Java's SERVER_OWNED_ON_CREATE does.
- Java: the create-validation server-owned set covers every DTO component,
  so a nulled readOnly or derived value-object column no longer 400s.
- TypeScript: drop the now-dead PK guard in the update-schema nullable arm
  and list the PK rule in updateSchemaFields' doc comment.

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

* no-mistakes(review): Kotlin readOnly create fix + C# reset skip

* no-mistakes(document): docs: finish stale corpus counts from input fix
…ases from release branches (#578)

* fix(csharp): a frozen node's memoized reads are safe across threads

MetaData.Cached stored derived reads in a plain Dictionary. A loaded model
is shared across threads, so two concurrent first reads of one node could
corrupt it, and every later read then threw "Operations that change
non-concurrent collections must have exclusive access". The cache is now a
ConcurrentDictionary; a racing first read keeps the first stored value.

Brought onto release/1.2 from main's fix (a266a51) for the 1.2.2 patch.

* feat(release): cut a patch from a release/<major>.<minor> maintenance branch

release.mjs and finish-release.mjs refused any branch but main, so a patch
on a line main has moved past could not go through its own guarded scripts.
Both now accept release/<major>.<minor> as well (one shared rule in
scripts/lib/release-branch.mjs): the version must be on that branch's own
line, every push goes to that branch, and finish-release's sync check
compares HEAD with origin/<branch>. Every other gate is unchanged.

docs/RELEASING.md gains the maintenance-branch section, including that the
site deploys from the newest vN.N.N tag wherever it was cut.

* no-mistakes(review): gate latest-regression before npm publish; clean unpushed-branch die

* no-mistakes(review): refuse an rc of an already-shipped version

* no-mistakes(document): docs: fix RELEASING.md main-only release claims
The ts-fast lane (and so --quick, --only ts and the no-mistakes Test step)
ran the full Stryker pass over all six metadata files on every run: 10-45
minutes of CPU per gate round on a loaded host, most of that step's wall time.

The step now diffs the stryker.conf.mjs `mutate` list against the merge base
with the base branch (MO_CI_MUTATION_BASE, else origin/$GITHUB_BASE_REF, else
whichever of origin/main and origin/release/* HEAD is closest to) and runs
`stryker run --mutate` on only the changed files. When none changed it prints
a SKIP naming the base. When no base resolves, or stryker.conf.mjs itself
changed, it says so and runs the full pass. Thresholds and concurrency are
unchanged; the list stays in stryker.conf.mjs only.

The full pass stays: the flagless run's mutation lane, a new
`--only mutation` section for release prep and on demand, and conformance.yml
(tags, nightly, dispatch) via MO_CI_MUTATION_SCOPE=full. Stryker's sandbox goes
under DEV_SCRATCH when that names a directory, and is removed afterwards.
* feat(codegen): skip gen when nothing changed, in every port (ADR-0062)

- gen builds a key from the loaded model (each root node in canonical effective
  form, rolled up per package) plus the generators' identity (built engine code,
  config, owned generators, templates, declared extra inputs, project config,
  output-changing flags), before anything renders. When it matches the last
  successful run and every generated file still holds that run's bytes, gen
  renders and writes nothing. --force (Maven: -Dmetaobjects.force=true) turns it
  off; a generator that cannot declare its inputs opts out (cache: false or the
  port's equivalent).
- verify --codegen always renders in CI; locally it may answer "no drift" from
  the key and the manifest, --full forces a render. When it renders, every port
  compares in memory: no rendered temp tree (Java/Kotlin now capture through
  GeneratedFileWriter).
- The hash manifest is loaded once and written once per run, only when it
  changed (TypeScript, Python, C#). Identical bytes are never rewritten in any
  port. Python gen no longer reports unchanged files as written.
- TypeScript runs git merge-file only for a file edited by hand, and deletes its
  temporaries in a finally, under $DEV_SCRATCH when set.
- fixtures/codegen-skip-conformance/cases.json: 25 shared cases run by every port.

* test(python): non-prompt targets rewrite nothing and save no manifest when unchanged

Two targets, four generators: a forced run over unchanged output keeps every
mtime and saves no manifest; a first run saves it once. Also corrects a stale
comment in verify --codegen, which renders in memory.

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

* no-mistakes(review): Track unrecorded outputs in the skip key

* no-mistakes(review): Track outside-root outputs in TS skip key

* no-mistakes(review): Store no skip key after refused orphan sweep

* no-mistakes(review): Hash YAML sources when docs-site is wired

* no-mistakes(document): document gen skip and in-memory verify

* no-mistakes(document): document gen skip in llms mirror

* no-mistakes(lint): Update corpora count to 35 in site payload and AGENTS.md

* test(agent-context): regenerate conformance expected copies

The skill references in agent-context/ now describe verify --codegen as
rendering in memory. Refresh the byte-for-byte expected mirrors to match.
…, no content change)

Every code fix on release/1.2 already reached main by squash forward-port
(#566, #568, #578, #585 as #590); its three release version bumps and the
patch-identical commit must not land. This merge records the ancestry so
the minor-cut preflight (scripts/release.mjs) stops refusing the 1.3.0 cut.
It changes no file.
…grate.foreignKeyTargets turns the foreign-key refusal into a report

C#: when dotnet meta gen can see the context's migrations in another project and
that project lacks the DesignTimeServicesReference, a context that declares a
@sequenceStart fails with ERR_DESIGN_TIME_REFERENCE_MISSING instead of warning, since
the next scaffold would write RESTART WITH n.

TypeScript: migrate.foreignKeyTargets (refuse | warn) in .metaobjects/config.json.
warn reports a foreign key onto a non-unique target and carries on; the default
refuse keeps the 1.3.0 refusal, and its hint now names the setting. The offline
migrate path now reports ungoverned and unenforced targets too. The Rust config
reader accepts and validates the key.
…rs written on it (ADR-0063)

CsWriter (usings, braced blocks, doc summaries, hanging continuations) runs the shared
writer-conformance core cases plus six C# cases. The filter allowlist, names, callable,
output-prompt, output-parser and extractor generators now write through it as classes with
overridable per-piece methods; their output is unchanged except that an XML-reply parser loses
the blank line after its opening brace. A Roslyn layout check keeps new hand-typed layout out of
the generator source, with an allowlist that only shrinks.
@dmealing dmealing changed the title feat(migrate-ts): let foreign keys target hand-made unique indexes feat(codegen-cs): CsWriter and six generators written on it; C# design-time-services error; migrate.foreignKeyTargets Nov 21, 2026
chore(release): record release/1.2 as merged into main (merge commit, not squash)
* feat(codegen-java): add the Java writer, its shared cases and a layout ratchet; pin the Spring REST surface

W-JV-1: a JavaWriter on a language-neutral CodeWriter in codegen-base, the
nine Java dialect cases in fixtures/writer-conformance, a runner for the
shared cases, and a layout ratchet that parses generator source with javac's
tree API and fails on hand-typed newlines, indents and joins. The allowlist
only shrinks and tags each unconverted file with the conversion step that
will retire it. The TypeScript runner now skips cases for other dialects.

W-JV-2: byte-exact expected files for the Spring controller, repository,
names and report-export generators over one input model, so the later
conversion to the writer is checked against today's output.

* no-mistakes(document): Update writer-conformance README for Java runner
…et (#623)

* docs(changelog): correct the C# namespace and primary-key entries; add the missing upgrade items

* feat(prerelease): staged-candidate log, full-candidate command and the Rust git pin

* feat(prerelease): the estate run sheet and a script for its mechanical steps

* fix(prerelease): restore the estate to its start commit, check every package version, record partial publishes

* no-mistakes(review): record partial publishes, restore estate on failure

* no-mistakes(review): document gitignore blind spot, test restore flags

* no-mistakes(test): Test cut-short registry rows in candidate log

* no-mistakes(document): Fix Stale C# namespace, candidate log docs

* no-mistakes(document): Fix candidate log header and estate help
…options (#624)

* test(python): pin router, names and filter-allowlist output byte for byte (W-PY-0)

* feat(python): code writer, layout check and first generators on it (W-PY-1)

* fix(python): accept every expression function and the cast node at load (C2)

* feat(python): per-generator packages, entities and options in metaobjects.config.yaml (L-PY-0)

* fix(python): keep the selection wrapper out of the generator census (L-PY-0)

* feat(python): split ObjectManager into abstract ObjectManager and ObjectManagerDb, transactions, listeners (L-PY-1)

ObjectManager is now the abstract store-neutral contract (validation, @autoset,
report refusal, persistence listeners); ObjectManagerDb is the DB-API
implementation. Value conversion moves to metaobjects.runtime.values, drivers
gain a transaction() API. Clean break: no shim. Upgrade note in
docs/features/migrations/python-object-manager-split.md.

* feat(python): shared-model publisher, all 15 shared-model cases (D6)

metaobjects.shared_model (build_shared_model, render_shared_model_files) and a
shared-model generator wired in metaobjects.config.yaml: name/include (required),
exclude, requirements, files, version. Options gain a list kind and a required
flag; the build context carries the project root, the project's own files and
the run's providers. The Python conformance test now runs publish bytes,
manifest and the six refusals, not only the serializer arm.

* test(python): record the orphan write in the per-package hash manifest, not the legacy file

* no-mistakes(review): Refuse repeated configured generators and empty required lists

* no-mistakes(review): Emit report export columns as a list

* no-mistakes(test): Refuse per-entity gaps in required generators

* no-mistakes(document): Fix stale Python lane docs

* no-mistakes(document): Fix stale Python ledger notes and view scope

* test(python): pin router, names and filter-allowlist output byte for byte (W-PY-0)

* feat(python): code writer, layout check and first generators on it (W-PY-1)

* fix(python): accept every expression function and the cast node at load (C2)

* feat(python): per-generator packages, entities and options in metaobjects.config.yaml (L-PY-0)

* fix(python): keep the selection wrapper out of the generator census (L-PY-0)

* feat(python): split ObjectManager into abstract ObjectManager and ObjectManagerDb, transactions, listeners (L-PY-1)

ObjectManager is now the abstract store-neutral contract (validation, @autoset,
report refusal, persistence listeners); ObjectManagerDb is the DB-API
implementation. Value conversion moves to metaobjects.runtime.values, drivers
gain a transaction() API. Clean break: no shim. Upgrade note in
docs/features/migrations/python-object-manager-split.md.

* feat(python): shared-model publisher, all 15 shared-model cases (D6)

metaobjects.shared_model (build_shared_model, render_shared_model_files) and a
shared-model generator wired in metaobjects.config.yaml: name/include (required),
exclude, requirements, files, version. Options gain a list kind and a required
flag; the build context carries the project root, the project's own files and
the run's providers. The Python conformance test now runs publish bytes,
manifest and the six refusals, not only the serializer arm.

* test(python): record the orphan write in the per-package hash manifest, not the legacy file

* no-mistakes(review): Refuse repeated configured generators and empty required lists

* no-mistakes(review): Emit report export columns as a list

* no-mistakes(test): Refuse per-entity gaps in required generators

* no-mistakes(document): Fix stale Python lane docs

* no-mistakes(document): Fix stale Python ledger notes and view scope

* fix(python): escape a trailing double quote in a one-line docstring; teach the ObjectManagerDb API in the runtime skill

PyWriter.doc wrote four quotes in a row when a one-line docstring ended in a double
quote, which ends the string early. The trailing run is now escaped, pinned by a new
py-doc-trailing-quote writer-conformance case.

The shipped Python runtime reference still taught ObjectManager(root, PostgresDriver(conn)),
which now raises. It teaches ObjectManagerDb and transaction(); the agent-context
conformance golden moves with it.

* no-mistakes(review): Revert TS runner edit; fix stale ObjectManagerDb docs
…e driver optional (#622)

* feat(codegen-ts): take Biome out of generation

meta gen no longer formats generated TypeScript with Biome. codegen-ts drops
@biomejs/js-api and @biomejs/wasm-nodejs; each generator writes the layout it
means. formatTs stays exported as a pass-through so an owned 1.2 generator copy
still loads. The Hono routes no longer emit biome-ignore lines. Golden files,
the showcase and advanced-modeling output, owned copies and the site payload
are regenerated.

* test(integration-tests): run report arithmetic and money sums on real databases

* feat(codegen-ts): state this release's API behaviour in the OpenAPI document

A list's limit carries the project's api.pagination default and maximum, a write says an undeclared key is refused (or dropped under api.unknownFields: drop), the error envelope carries issues, fields and maxLimit, and a read-only resource says a write answers 405. Also corrects three CHANGELOG wording points and the protobuf line, and closes the finished exactly-one request.

* feat(codegen-ts): make drizzle-orm and zod optional peers, and hold the install to a size budget

A fresh install of the CLI no longer pulls the ORM. scripts/check-install-size.mjs packs the CLI, installs it, refuses a forbidden package in the tree and keeps the size under a budget that can only move down; it runs in the full CI lane.

* perf(cli): load Biome's WebAssembly build on the first owned-copy comparison

* feat(cli): make the SQLite driver an optional peer, and have meta init declare it

libSQL brought an HTTP client, a stream polyfill and a native binary per libc (about 28 MB) to every install. A SQLite project now declares @libsql/kysely-libsql at the CLI's peer range; others install nothing. The install-size budget drops to 51 MB.

* no-mistakes(review): Test Biome lazy-load by subprocess, not source grep

* no-mistakes(test): apply changes made during test validation

* no-mistakes(document): drop stale Biome and optional-peer docs

* no-mistakes(document): reword Biome reason string

* test(sdk): bring the agent-context conformance golden up to the reworded formatTs note

The document step reworded the formatTs line in the bundled TypeScript codegen reference; the ts-react-tanstack expected file still carried the old line, so the sdk conformance corpus failed in the ts-unit lane.

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

* no-mistakes(document): Four stale facts fixed in their owners; nothing left open. Already-correct branch docs (AGENTS.md, cli README, cli.md, contract-emitters.md, ADR-0063, CHANGELOG) were left as they are. - scripts/check-peer-ranges.ts:60: reason string now says the CLI's owned-copy comparison uses the WASM build (user-approved document-1). - agent-context/skills/metaobjects-codegen/references/typescript.md: Install section now says drizzle-orm and zod are optional peers, installed on demand; points to `meta gen --list --format json` and `meta eject` for the install set. - docs/features/migrations/commit-the-gen-state-hash-manifest.md: dropped "formatter" from two sentences; TS generation runs no formatter. Checked and left unchanged: docs/llms mirrors (their install lines remain accurate), docs/recipes/write-your-own-generator.md, codegen-ts README, docs/ports/typescript.md Zod passage (pre-existing, not changed by this branch), and the Python/Java/C# formatter references (different subsystems).

* test(sdk): bring the agent-context conformance golden up to the new install paragraph

Run 2's document step added an install paragraph to the bundled TypeScript codegen reference and left the ts-react-tanstack expected file behind, so the sdk conformance corpus is red again.

* no-mistakes(document): Fix optional peer claim in TS port doc
…grate.foreignKeyTargets turns the foreign-key refusal into a report

C#: when dotnet meta gen can see the context's migrations in another project and
that project lacks the DesignTimeServicesReference, a context that declares a
@sequenceStart fails with ERR_DESIGN_TIME_REFERENCE_MISSING instead of warning, since
the next scaffold would write RESTART WITH n.

TypeScript: migrate.foreignKeyTargets (refuse | warn) in .metaobjects/config.json.
warn reports a foreign key onto a non-unique target and carries on; the default
refuse keeps the 1.3.0 refusal, and its hint now names the setting. The offline
migrate path now reports ungoverned and unenforced targets too. The Rust config
reader accepts and validates the key.
…rs written on it (ADR-0063)

CsWriter (usings, braced blocks, doc summaries, hanging continuations) runs the shared
writer-conformance core cases plus six C# cases. The filter allowlist, names, callable,
output-prompt, output-parser and extractor generators now write through it as classes with
overridable per-piece methods; their output is unchanged except that an XML-reply parser loses
the blank line after its opening brace. A Roslyn layout check keeps new hand-typed layout out of
the generator source, with an allowlist that only shrinks.
Convert the 3,313-line entity generator (mapped entities, TPH subtypes, abstract shapes,
value objects, shared enums, and the decimal, duration and net-validation helper files)
to the code writer. Output matches the previous generator byte for byte over every
model fixture in all four layouts except three layout details the writer owns: an
empty class body has no blank line, a blank before a closing brace is dropped, and a
/// line has no trailing space.

Hooks take a CsWriter instead of a StringBuilder; property emitters are renamed
Write*Property. EntityGenerator.cs leaves the layout ratchet allowlist.
The context, its OnModelCreating and ConfigureModelNN chunks, the enum, map and
duration helpers and the design-time services file are written on a CsWriter.
Output is byte-identical for the 737 model fixtures in all four layouts. The
EmitUsings, EmitDbSetDeclarations and EmitOnModelCreatingBody hooks take the
writer; text hooks return unindented lines. The layout ratchet allowlist loses
the generator's entry.
…and requirement tests write through CsWriter (ADR-0063)

Output is byte-identical on the 737 model fixtures in four layouts, except
that the shared report-export writer now ends with a newline like every
other generated file. The four files leave the layout allowlist.
…sWriter (ADR-0063)

All generators now write through the writer, so the layout check's unconverted
list is empty. Routes output is byte-identical on the 737 model fixtures in
four layouts. The report-export golden gains its final newline.
… One stale-risk fact fixed: docs/ports/csharp.md now states the IValidatableObject last-line rule for hook overrides. All other doc facts verified against code: writer defaults, Using/Sorted/Hanging/Braced/DocSummary, ERR_WRITER_IMPORT_CONFLICT, ERR_DESIGN_TIME_REFERENCE_MISSING gating, hook names and signatures, writer-conformance case counts (67 = 31+10+9+6+11), CONFORMANCE matrix column order, eject table, migrate.foreignKeyTargets config and refusal hint. Stale M2mNavProperty comments in DbContextGenerator.cs were already fixed.
@dmealing dmealing changed the title feat(codegen-cs): CsWriter and six generators written on it; C# design-time-services error; migrate.foreignKeyTargets feat(csharp): write C# generators through CsWriter; add migrate.foreignKeyTargets Nov 21, 2026
@dmealing
dmealing merged commit 8c21d68 into main Nov 21, 2026
10 checks passed
@dmealing
dmealing deleted the fm/mo-130-lane-csharp branch November 21, 2026 09:45
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