Skip to content

feat(runtime-ts): make the REST list query a cross-port contract - #634

Merged
dmealing merged 13 commits into
mainfrom
fm/mo-130-lane-ts-2-b2
Nov 21, 2026
Merged

dmealing merged 13 commits into
mainfrom
fm/mo-130-lane-ts-2-b2

Conversation

@dmealing

@dmealing dmealing commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

What Changed

  • The REST list query is now a cross-port contract (ADR-0068). ?search, filter[or] / filter[and], the five-level nesting cap, the bare-field and leading-% refusals, the filter-value format check, and the invalid_json, invalid_id, pagination.invalid_value and constraint_violation responses are specified in docs/features/api-contract.md and checked by the new fixtures/list-query-conformance/ corpus and the list-query/ api-contract sub-corpus. TypeScript passes both; the other ports are pending.
  • runtime-ts parses list requests in one shared parseListQuery, used by the Drizzle, Hono and ObjectManager Fastify mounts. The ObjectManager mount gains filterAllowlist and pagination options and orders by primary key when no sort is given. Fixes in the same change: the nesting cap is reachable, like is case-sensitive on SQLite and MySQL (ADR-0049), and sort and filter allowlist lookups use own keys only, so inherited names such as constructor are refused.
  • Requirements and agent-context pages render from shared Mustache templates, and codegen-ts exports filterAllowlistRules / sortAllowlistRules with byte-identical generated allowlists. init refresh, eject (including --force), and C#, Java and Kotlin ejects and generation leave files whose bytes already match untouched. Java now strips standalone {{! comment }} lines before rendering, so a prompt body containing one changes bytes on upgrade.
Validation

Risk Assessment

✅ Low: The covered runtime, driver, template and eject logic traces correctly: case-sensitive like and case-insensitive ilike per dialect, $or compilation, the Fastify list mount, the Java standalone-comment strip and the idempotent writers. The only issue found is a small documentation gap about ?search wildcard semantics.

Testing

Baseline configured test command passed and was not re-run. Three scenarios driven live against the real runtime-ts Fastify list mount and the ejected showcase parser with synthetic rows: sort ignored without a sort allowlist, sort ordering plus 400 invalid_sort for prototype and unknown fields with an allowlist, and the ejected copy rejecting prototype sort fields. All three pass. The fake ObjectManager does not apply filters, so filter semantics were not exercised live. Ejected advanced-modeling copy checked by byte comparison only. Dynamic-grid bound-value test ran green (10/10). Overall result: pass.

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
List mount with filterAllowlist only (no sortAllowlist): ?sort is ignored, rows keep key order, prototype-key sort names do not error (local Fastify + fake ObjectManager, synthetic rows) ✅ pass live live-sort-current.txt scenario A; driver/live-sort.ts
List mount with sortAllowlist: valid ?sort orders rows; constructor, toString, proto, hasOwnProperty and bad direction return 400 invalid_sort (local Fastify + fake ObjectManager, synthetic rows) ✅ pass live live-sort-current.txt scenario B; driver/live-sort.ts
Ejected examples/showcase list-query parser: prototype and unknown sort fields throw sort.unknown_field, valid sort parses (real example file executed under bun) ✅ pass live live-sort-current.txt scenario C; cmp parity check of showcase and advanced-modeling copies vs runtime-ts source
Evidence: Live probe output: sort scenarios A/B/C against current tree
== scenario A: filterAllowlist only (no sortAllowlist) ==
/parts?sort=name:asc -> 200 [{"id":1,"name":"Zinc","stock":3},{"id":2,"name":"Anvil","stock":1},{"id":3,"name":"Mallet","stock":2}]
/parts?sort=constructor -> 200 [{"id":1,"name":"Zinc","stock":3},{"id":2,"name":"Anvil","stock":1},{"id":3,"name":"Mallet","stock":2}]
/parts?sort=__proto__:desc -> 200 [{"id":1,"name":"Zinc","stock":3},{"id":2,"name":"Anvil","stock":1},{"id":3,"name":"Mallet","stock":2}]
/parts?filter[stock][gte]=2&sort=name:desc -> 200 [{"id":1,"name":"Zinc","stock":3},{"id":2,"name":"Anvil","stock":1},{"id":3,"name":"Mallet","stock":2}]
== scenario B: filterAllowlist + sortAllowlist ==
/parts?sort=name:asc -> 200 [{"id":2,"name":"Anvil","stock":1},{"id":3,"name":"Mallet","stock":2},{"id":1,"name":"Zinc","stock":3}]
/parts?sort=stock:desc -> 200 [{"id":1,"name":"Zinc","stock":3},{"id":3,"name":"Mallet","stock":2},{"id":2,"name":"Anvil","stock":1}]
/parts?sort=constructor -> 400 {"error":"invalid_sort","field":"constructor","expected":"sort=<field>:asc|desc","allowed":["id","name","stock"]}
/parts?sort=toString:desc -> 400 {"error":"invalid_sort","field":"toString","expected":"sort=<field>:asc|desc","allowed":["id","name","stock"]}
/parts?sort=__proto__ -> 400 {"error":"invalid_sort","field":"__proto__","expected":"sort=<field>:asc|desc","allowed":["id","name","stock"]}
/parts?sort=hasOwnProperty -> 400 {"error":"invalid_sort","field":"hasOwnProperty","expected":"sort=<field>:asc|desc","allowed":["id","name","stock"]}
Evidence: Live probe driver script (fastify.inject + ejected parser)
// Live probe: drives the real ObjectManager Fastify list mount (runtime-ts src) via fastify.inject,
// and the ejected example copy of the shared parser, with synthetic rows.
import Fastify from "fastify";
import { mountListRoute } from "{run-worktree}/server/typescript/packages/runtime-ts/src/fastify/index.ts";
import { parseListQuery, parseListQueryString } from "{run-worktree}/examples/showcase/codegen/runtime/drizzle-fastify/list-query.ts";

const ROWS = [
  { id: 1, name: "Zinc", stock: 3 },
  { id: 2, name: "Anvil", stock: 1 },
  { id: 3, name: "Mallet", stock: 2 },
];
const fakeOm = {
  fieldNames: () => ["id", "name", "stock"],
  keyFields: () => ["id"],
  async findMany(_e: string, _f: unknown, o: { orderBy?: [string, "asc" | "desc"] }) {
    const rows = [...ROWS];
    if (o.orderBy) {
      const [f, d] = o.orderBy;
      rows.sort((a: any, b: any) => (a[f] < b[f] ? -1 : a[f] > b[f] ? 1 : 0) * (d === "desc" ? -1 : 1));
    }
    return rows;
  },
  async count() { return ROWS.length; },
};

async function mount(label: string, extra: Record<string, unknown>) {
  const app = Fastify();
  mountListRoute({ fastify: app as any, path: "/parts", entity: "Part", om: async () => fakeOm as any, ...extra } as any);
  await app.ready();
  return { app, label };
}
const show = async (app: any, url: string) => {
  const r = await app.inject({ method: "GET", url });
  console.log(`${url} -> ${r.statusCode} ${r.body}`);
};

const FILTER = { name: { ops: ["eq", "like"], subType: "string", leadingWildcard: false }, stock: { ops: ["eq", "gte"], subType: "int", leadingWildcard: false } } as any;
const SORT = { id: {}, name: {}, stock: {} } as any;

console.log("== scenario A: filterAllowlist only (no sortAllowlist) ==");
{
  const { app } = await mount("A", { filterAllowlist: FILTER });
  for (const u of ["/parts?sort=name:asc", "/parts?sort=constructor", "/parts?sort=__proto__:desc", "/parts?filter[stock][gte]=2&sort=name:desc"]) await show(app, u);
  await app.close();
}
console.log("== scenario B: filterAllowlist + sortAllowlist ==");
{
  const { app } = await mount("B", { filterAllowlist: FILTER, sortAllowlist: SORT });
  for (const u of ["/parts?sort=name:asc", "/parts?sort=stock:desc", "/parts?sort=constructor", "/parts?sort=toString:desc", "/parts?sort=__proto__", "/parts?sort=hasOwnProperty", "/parts?sort=name:sideways"]) await show(app, u);
  await app.close();
}
console.log("== scenario C: ejected example copy (examples/showcase) of shared parser ==");
{
  const cfg = { allowlist: FILTER, sortAllowlist: SORT, isField: (n: string) => ["id", "name", "stock"].includes(n) };
  for (const raw of ["sort=name:asc", "sort=constructor", "sort=toString:desc", "sort=__proto__"]) {
    try {
      const q = parseListQuery({ query: parseListQueryString(raw), ...cfg } as any);
      console.log(`${raw} -> OK ${JSON.stringify(q.sort)}`);
    } catch (e: any) {
      console.log(`${raw} -> THROW ${e.code ?? e.name} ${JSON.stringify(e.details ?? e.message)}`);
    }
  }
}
console.log("== done ==");
  • Outcome: 🔧 3 issues found → auto-fixed ✅ across 2 runs (1h8m2s)

Pipeline

Updates from git push no-mistakes

✅ **Intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 3 infos
  • ⚠️ server/typescript/packages/runtime-ts/src/fastify/index.ts:152 - In the ObjectManager Fastify list mount, ?sort is no longer ignored when sortAllowlist is absent but filterAllowlist is set. Line 152 passes sortAllowlist: opts.sortAllowlist ?? {} into parseListQuery. A request like ?sort=name:asc therefore answers 400 invalid_sort with allowed: []. The sortAllowlist option doc (line ~80) and the no-filterAllowlist branch (line 155, via pageAndSortOnly) both say an absent allowlist means ?sort is ignored. The two branches now disagree. Fix: in the filterAllowlist branch, drop sort from the query when sortAllowlist is undefined (the same pageAndSortOnly idea), or document that setting filterAllowlist makes sort strict.
  • ℹ️ server/typescript/packages/sdk/src/agent-context/scaffold.ts:63 - ScaffoldDecision.unchanged is added and populated in planScaffold but nothing in init.ts reads it. The field is dead outside tests. Either use it, for example to report 'already current', or remove it.

🔧 Fix applied.
5 issues (2 warnings, 3 infos) still open:

  • ℹ️ server/typescript/packages/runtime-ts/src/drivers/in-memory-driver.ts:273 - Moved the // SQL LIKE: % → .* ... comment back above likeMatch; the new foldAscii helper had been inserted between the comment and its function. Comment-only change.
  • ⚠️ server/typescript/packages/runtime-ts/src/drizzle-fastify/list-query.ts:344 - parseSort tests !sortAllowlist[field], which is truthy for any inherited Object property. ?sort=constructor, ?sort=toString or ?sort=__proto__ therefore passes the sort check and returns { field: &#34;constructor&#34;, order: &#34;asc&#34; } instead of 400 invalid_sort. The mount then orders by a non-column: table[&#34;constructor&#34;] in nullsAsLargest on the Drizzle mounts, and an unknown column in the ObjectManager mount (sortAllowlist: opts.sortAllowlist ?? {}). The result is a 5xx or wrong SQL where the shared contract promises a named 400. This was pre-existing (base filter-parser.ts:446) but now lives in the shared parser the change declares cross-port contract, and the ObjectManager mount newly reaches it. Siblings: list-query.ts:206 opts.allowlist[key] has the same lookup shape (qs drops prototype keys today, so it is only reachable from a hand-written transport that builds the query object itself); filter-allowlist.ts:127 allowlist[field]?.defaultOrder has it too. Fix: use Object.hasOwn(...) at both lookups. Also add a sort=constructor case to fixtures/list-query-conformance/cases.json.
  • ⚠️ docs/features/api-contract.md:174 - The change promotes seven TypeScript-only list extensions (?search, filter[or|and], nesting cap, bare-field refusal, leading-% refusal, value-format check, in cap) and five bad-request responses to the cross-port REST contract. The prior text said they were deliberately deferred until consumer demand, and that an adopter "must not assume them on a non-TS backend". That warning is deleted, and the closing line "Neither item blocks adoption on any port today" is softened. Per the project rules (CLAUDE.md, "Record significant cross-cutting decisions as ADRs"), changing a cross-language contract needs an ADR, and the diff adds none. Java, Kotlin, Python and C# run neither new corpus (docs/CONFORMANCE.md marks them planned). So the docs state a contract that four of five ports do not meet yet. This is a product and release decision for the maintainer, not a mechanical fix. Decide whether to add an ADR and keep a "TS-only until the port lands" caveat in the docs, or accept the current wording as the 1.3.0 plan.
  • ℹ️ server/typescript/packages/codegen-ts/src/reference/agent-docs.ts:19 - The header of the ejectable reference still lists the schema page's customization points as lineageOf, cardinalityPhrase, relationshipLines, enumLines and "the loop that builds declaredBy". This change moved all of those into generators/agent-schema-page.ts (modelFacts, lineageOf, relationshipLines, enumRows), and the reference now only calls renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { provider }). An adopter who ejects it will look for functions that are not in the file. docs/features/own-your-codegen.md was updated correctly. Reword the customize: line to say the model walk lives in agent-schema-page, which meta eject copies beside it, and mention the new templates option.
  • ℹ️ server/typescript/packages/integration-tests/test/list-query-conformance.test.ts:57 - Test-quality note. The expected answers in fixtures/list-query-conformance/cases.json (93 cases) and fixtures/docs-page-conformance/**/expected/ are regenerated from the implementation under test (UPDATE_LIST_QUERY_FIXTURES=1 and UPDATE_DOCS_PAGE_FIXTURES=1). The allowlist the list-query runner feeds the parser is also derived by filterAllowlistRules, which is itself changed code. So the oracle is the code, and a shared mistake would pass both sides. This is an intentional cross-port golden-file design; the authored query and why columns and the README's review-on-regenerate rule are the independent part. The oracle for the correct-by-spec cases is independent in the api-contract list-query/ scenarios, which assert row ids against a real Postgres with a hand-written seed. Keep that pairing, and keep reviewing every changed answer in a regeneration diff. No code change required.

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

  • ℹ️ server/typescript/packages/runtime-ts/src/drivers/in-memory-driver.ts:273 - Moved the // SQL LIKE: % → .* ... comment back above likeMatch; the new foldAscii helper had been inserted between the comment and its function. Comment-only change.
  • ℹ️ server/typescript/packages/integration-tests/test/list-query-conformance.test.ts:57 - Test-quality note. The expected answers in fixtures/list-query-conformance/cases.json (93 cases) and fixtures/docs-page-conformance/**/expected/ are regenerated from the implementation under test (UPDATE_LIST_QUERY_FIXTURES=1 and UPDATE_DOCS_PAGE_FIXTURES=1). The allowlist the list-query runner feeds the parser is also derived by filterAllowlistRules, which is itself changed code. So the oracle is the code, and a shared mistake would pass both sides. This is an intentional cross-port golden-file design; the authored query and why columns and the README's review-on-regenerate rule are the independent part. The oracle for the correct-by-spec cases is independent in the api-contract list-query/ scenarios, which assert row ids against a real Postgres with a hand-written seed. Keep that pairing, and keep reviewing every changed answer in a regeneration diff. No code change required.
  • ⚠️ examples/showcase/codegen/runtime/drizzle-fastify/list-query.ts:344 - The round-2 fix (commit 12a53f4, Object.hasOwn allowlist lookups) changed runtime-ts/src/drizzle-fastify/list-query.ts at lines 206 and 344, but the committed ejected runtime copies were not regenerated. Both example copies still hold the old truthiness lookups: const rule = opts.allowlist[key]; at line 206 and if (!sortAllowlist[field]) at line 344. Concrete sequence: an adopter project built from either example answers ?sort=constructor / toString with a 200-path sort on a non-column instead of 400 invalid_sort, which is the exact defect the round fixed. meta verify will also report these owned copies as drifted from the shipped runtime. Sibling sites to update: examples/showcase/codegen/runtime/drizzle-fastify/list-query.ts:206 and :344; examples/advanced-modeling/codegen/runtime/drizzle-fastify/list-query.ts:206 and :344. The other ejected runtime copies (filter-parser, index, list-params, mount-read-only, route-errors) are byte-identical to the source. Fix: re-copy list-query.ts into both example runtime dirs.

🔧 Fix applied.
3 infos still open:

  • ℹ️ server/typescript/packages/runtime-ts/src/drivers/in-memory-driver.ts:273 - Moved the // SQL LIKE: % → .* ... comment back above likeMatch; the new foldAscii helper had been inserted between the comment and its function. Comment-only change.
  • ℹ️ server/typescript/packages/integration-tests/test/list-query-conformance.test.ts:57 - Test-quality note. The expected answers in fixtures/list-query-conformance/cases.json (93 cases) and fixtures/docs-page-conformance/**/expected/ are regenerated from the implementation under test (UPDATE_LIST_QUERY_FIXTURES=1 and UPDATE_DOCS_PAGE_FIXTURES=1). The allowlist the list-query runner feeds the parser is also derived by filterAllowlistRules, which is itself changed code. So the oracle is the code, and a shared mistake would pass both sides. This is an intentional cross-port golden-file design; the authored query and why columns and the README's review-on-regenerate rule are the independent part. The oracle for the correct-by-spec cases is independent in the api-contract list-query/ scenarios, which assert row ids against a real Postgres with a hand-written seed. Keep that pairing, and keep reviewing every changed answer in a regeneration diff. No code change required.
  • ℹ️ docs/features/api-contract.md:180 - The rewritten ?search row calls it a case-insensitive substring match but drops the old (%term%) hint. The corpus case search-wildcards-kept (fixtures/list-query-conformance/cases.json:1394) pins that the term is kept as sent. So % and _ inside the term act as LIKE wildcards on every engine: ?search=_ matches every non-empty text value, and ?search=a_b matches aXb. A port author reading only the doc would escape the term and fail the corpus, or an adopter would expect literal substring matching. Add one sentence to the row: % and _ in the term are LIKE wildcards, not escaped. Same wording for the ADR-0068 search bullet (spec/decisions/ADR-0068-list-query-cross-port-contract.md:25).
🔧 **Test** - 3 issues found → auto-fixed ✅
  • 🚨 configured test command failed with exit code 1
  • ⚠️ The configured test command (scripts/ci-local.sh --affected --strict-toolchains) did not finish, so the failing lane is not identified. The ts lane and java conformance after the reactor are unknown. Re-run to completion with nothing else holding the machine, and read the first red lane.
  • ⚠️ live validation verdict: inconclusive (2 of 3 scenarios were driven live against the product); untested: Ejected example runtime copies (showcase, advanced-modeling) match the source list-query.ts
  • Live validation: ⚠️ inconclusive - 2 of 3 scenarios driven live against the product
Scenario Result Live Evidence
ObjectManager Fastify list mount, filterAllowlist only: ?sort is ignored (200, no 400) for name:asc and constructor; filtered sort still filters ✅ pass live list-sort-live.txt (scenario 1 lines)
ObjectManager Fastify list mount, filterAllowlist + sortAllowlist: prototype-key sorts (constructor, toString, proto, hasOwnProperty) answer 400 invalid_sort; valid sorts order correctly ✅ pass live list-sort-live.txt (scenario 2 lines)
Ejected example runtime copies (showcase, advanced-modeling) match the source list-query.ts ⏸️ untested no File identity only, not a product run. The ejected examples were not executed.
  • scripts/ci-local.sh --affected --strict-toolchains
  • MO_CI_LIST_ONLY=1 scripts/ci-local.sh --affected --strict-toolchains (lane selection)
  • scripts/ci-local.sh --affected --strict-toolchains run in background, log at evidence affected-run.log; stopped by process group after partial results
  • Live driver (transient, removed): ObjectManager + inMemoryDriver + mountCrudRoutes with filterAllowlist only, and with filterAllowlist + sortAllowlist, queried over local HTTP via fetch
  • cmp of runtime-ts src/drizzle-fastify/list-query.ts against examples/showcase and examples/advanced-modeling copies (identical; file identity only, not live)

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

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
List mount with filterAllowlist only (no sortAllowlist): ?sort is ignored, rows keep key order, prototype-key sort names do not error (local Fastify + fake ObjectManager, synthetic rows) ✅ pass live live-sort-current.txt scenario A; driver/live-sort.ts
List mount with sortAllowlist: valid ?sort orders rows; constructor, toString, proto, hasOwnProperty and bad direction return 400 invalid_sort (local Fastify + fake ObjectManager, synthetic rows) ✅ pass live live-sort-current.txt scenario B; driver/live-sort.ts
Ejected examples/showcase list-query parser: prototype and unknown sort fields throw sort.unknown_field, valid sort parses (real example file executed under bun) ✅ pass live live-sort-current.txt scenario C; cmp parity check of showcase and advanced-modeling copies vs runtime-ts source
  • scripts/ci-local.sh --affected --strict-toolchains
  • Baseline (given): scripts/ci-local.sh --affected --strict-toolchains passed at target commit; not re-run (no source changes in this turn).
  • Live: a local driver script (not committed) drives the real runtime-ts Fastify ObjectManager list mount (mountListRoute) via fastify.inject, with synthetic rows and a fake ObjectManager, and the ejected examples/showcase list-query parser.
  • Live scenario A: filterAllowlist only, no sortAllowlist. ?sort=name:asc, ?sort=constructor, ?sort=__proto__:desc all 200 in key order (sort ignored).
  • Live scenario B: filterAllowlist + sortAllowlist. ?sort=name:asc and ?sort=stock:desc order rows; constructor, toString:desc, __proto__, hasOwnProperty, name:sideways all 400 invalid_sort with allowed list.
  • Live scenario C: examples/showcase ejected parser: sort=name:asc OK; constructor, toString:desc, __proto__ throw sort.unknown_field.
  • cmp of examples/showcase and examples/advanced-modeling codegen/runtime/drizzle-fastify/list-query.ts against runtime-ts src: identical. Object.hasOwn present at list-query.ts lines 170, 206, 344.
  • bun test test/no-sql-from-request.test.ts in examples/dynamic-grid: 10 pass, 0 fail (test-1 fix).
  • Worktree git status clean after run; no background processes started; driver and evidence kept under the evidence dir.
🔧 **Document** - 2 issues found → auto-fixed ✅
  • ⚠️ agent-context/skills/metaobjects-audit/references/python.md:162 - Agent skill references still say ?search, filter[or]/filter[and] and leading-wildcard gating are TS-only, and python.md tells the audit to 'do NOT flag its absence in Python'. Same text in java.md:160, capability-checklist.md:352, calibration.md:23 and metaobjects-codegen/references/typescript-mysql.md:126, plus their copies under fixtures/agent-context-conformance/*/expected/. The list contract (ADR-0068, api-contract.md) now states these features for every port, and non-TS ports land them in 1.3.0. Decide: (a) keep the audit silent on non-TS gaps until each port lands, and reword to say so; or (b) have the audit flag them now. Option (a) also needs the skill sources and the six expected copies edited together and the agent-context conformance test re-run.
  • ℹ️ docs/features/contract-emitters.md:203 - The generated OpenAPI document does not describe ?search, filter[or] or filter[and], though they are now list contract (build-openapi.ts header says 'not described yet'). The docs now say 'not yet' accurately. Closing the gap is codegen work in the OpenAPI builder and its conformance, which is a product change, not a doc fix.

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

🔧 **Lint** - 1 issue found → auto-fixed ✅
  • ⚠️ linter found issues (exit code 1)

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

✅ **Push** - passed

✅ No issues found.

Validated in one no-mistakes gate run (01M8002W672DGW0014NNMGMARM), with fix rounds at review, test, document and lint.

…; share the inline object literal

- codegen-ts tests and the docs-site builder create throwaway directories with
  makeScratchDir ($DEV_SCRATCH, else the OS temp dir) and remove them with
  removeTree instead of raw mkdtempSync/tmpdir and Bun's recursive rmSync, which
  has failed with EFAULT under concurrent filesystem use. Directories created
  beside the tests (import.meta.dir) stay there, since their generated code
  resolves packages from the workspace node_modules; only their removal moves.
- view-decl.ts drops its private optionsLiteral and uses drizzle-schema.ts's
  inlineObjectLiteral, which now also quotes a key that is not an identifier.
- replay-engine.ts: correct the comment that said cli depends on
  @libsql/kysely-libsql outright; it is an optional peer now.
…t --force; shared template+docs rerun case

- The agent-context refresh (`meta init --refresh-docs`) compares before writing: an
  identical file is recorded but not rewritten, and the manifest is written only when its
  text changed. A refresh that changes nothing says so.
- `meta eject --force` (generator, templates, runtime, docs-site, library) leaves a file
  whose bytes already match alone and reports it as preserved/identical.
- New shared case `template-and-docs-rerun` in fixtures/codegen-skip-conformance: a
  project with a `template` generator and a docs page reruns, then forces a full render,
  and nothing changes bytes or mtime. Runners in TS, Python, C# and Java; Rust names it
  not applicable (no template or docs generator yet).
- Owned reference-template copies resynced for the shared inlineObjectLiteral.
- The handEdits: overwrite verify integration test gets a budget that fits its six runs.
…agent pages; docs-page and render whitespace conformance (G0)

The requirements page (requirements.md, requirements.toon), agent/requirements.md and
agent/schema.md are now a builder plus a shared Mustache template, like the model pages:
the builders (requirementsLedgerData, requirementsToonData, agentRequirementsPageData,
agentSchemaPageData) compute every cell and line, and templates/requirements/ and
templates/agent/ lay them out. A project overrides a page by dropping a same-named
template under templates/ (requirementsFile/agentDocsFile take a templates option).
The output is byte-identical to the previous renderers over every model in the repo
that loads (266 models, both dialects).

The schema page builder now walks the model itself (column-to-field map, lineage,
relationships, enums) and has a model-only form (physical: false): no SQL type or
default column, no indexes, checks, constraint names or referential actions. That is
the page a port without the expected schema writes (design call 17).

New shared corpus fixtures/docs-page-conformance/ pins each page's data and bytes,
with the TypeScript generators as the source; its README states what a non-TypeScript
schema page contains. Three render-conformance whitespace cases (standalone tags in a
row, at the end of the file, indented) pin the semantics the shared templates rely on;
the Java renderer now strips standalone comment lines, closing its last KNOWN_DRIFT row.
… (R0)

`?search`, `filter[or]`/`filter[and]`, the nesting cap, the bare-field and
leading-`%` refusals, the value format check and the invalid_json, invalid_id,
pagination.invalid_value and constraint_violation responses move out of the
"TS-only" section of docs/features/api-contract.md into the contract, with the
TypeScript wire names unchanged.

- runtime-ts: `parseListQuery` (drizzle-free) reads a list request into a
  neutral ListQuery and raises every refusal; each mount compiles it for its
  store. The ObjectManager Fastify mount takes `filterAllowlist` and
  `pagination`, so it serves filters, or/and and search like the Drizzle and Hono mounts. With no
  sort it orders by the key. The OM Filter gains `$or` and `$ilike`.
- Fix: the nesting cap was unreachable (qs depth 5); every mount now parses
  with `parseListQueryString`. A scalar combinator branch is
  invalid_filter_value with field "or".
- Fix: SQLite `like` through the OM drivers was case-insensitive (ADR-0049).
- Fix: `?search` included int-backed enums (a Postgres 500).
- codegen-ts: `filterAllowlistRules` / `sortAllowlistRules` expose the
  allowlists as data; generated output is byte-identical.
- New shared corpus fixtures/list-query-conformance/ (93 parse cases) and the
  api-contract `list-query/` sub-corpus (20 scenarios, 60-row seed, generated
  lane); TypeScript runners for both, plus an OM mount parity test.
- The examples' owned runtime copies gain list-query.ts and are re-synced.
Resolves the one conflict, CHANGELOG.md's Unreleased list, where both sides added bullets: every
bullet from each side is kept.
@dmealing
dmealing merged commit eadf39e into main Nov 21, 2026
10 checks passed
@dmealing
dmealing deleted the fm/mo-130-lane-ts-2-b2 branch November 21, 2026 23:44
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
dmealing added a commit that referenced this pull request Nov 25, 2026
…634

Main's #634 added render-conformance cases and two corpora while this branch
added two render error cases and a Jinja error case; the counts and the
showcase payload are recomputed from the fixtures on disk.
dmealing added a commit that referenced this pull request Nov 25, 2026
…#632)

* feat: move reporting and requirements into their own provider packs; raise on missing template variables; refuse permission-name collisions

- Reporting (object.report, dimension.*, measure.* incl. measure.derived/@expr,
  segment.filter, the entity's dimension/measure/segment children and @segment on
  origin.aggregate/origin.first) is registered by metaobjects-reporting; requirements
  (requirement.* and the root's requirement child) by metaobjects-requirements. Both
  are in the default bundle of every port (TS, C#, Java/Kotlin, Python, Rust), so
  existing models load and generate identically. A model that uses a left-out pack's
  vocabulary gets a loader error (new error-packs-left-out-*-used fixtures). The
  verify requirements gate reads through the pack.
- A pack subtype declared with extendsBase may fold a base another provider
  registered (object.report folds object.base); folded attributes keep the base's
  owner under ADR-0062.
- Core vocabulary pin, registry manifest (root requirement child gains min 0 /
  max null), metamodel docs, site reference and payload regenerated.
- GOVERNANCE.md: an attribute promoted from a pack into core keeps its name and
  meaning.
- B4: Mustache and Jinja raise ERR_VAR_NOT_ON_PAYLOAD for a variable or dotted path
  absent from the payload, in every port that renders; render runners learn
  expected-error.txt.
- B5: rules rule P3 refuses two permission points whose names resolve equal when at
  least one name is derived (ERR_TRANSITION_NAME_COLLISION), in every port.
- C3: Python checks @union shape and @Grain views at load; both must-fail fixtures
  leave its expected-failures ledger.

* fix(rules): compare P3 permission names exactly, so '::' and '.' are not one name

The P3 collision check rewrote '::' to '.' before comparing, so a derived
p::Order.open counted as a collision with the transition's p.Order.open. They
are different names in the metadata and the policy receives them as written.
Removed the rewrite in TS, C#, Java, Python and Rust. The former
error-rules-permission-name-op-package fixture becomes
rules-permission-name-package-separator-distinct, which every port's
conformance runner now loads clean.

* docs(changelog): drop a leftover rebase marker

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

* no-mistakes(test): Wrap two rustfmt-flagged lines in Rust registry and rules

* no-mistakes(document): sync docs with packs, render errors, P3

* no-mistakes(document): point pack docs at vocabulary owner

* feat: move reporting and requirements into their own provider packs; raise on missing template variables; refuse permission-name collisions

- Reporting (object.report, dimension.*, measure.* incl. measure.derived/@expr,
  segment.filter, the entity's dimension/measure/segment children and @segment on
  origin.aggregate/origin.first) is registered by metaobjects-reporting; requirements
  (requirement.* and the root's requirement child) by metaobjects-requirements. Both
  are in the default bundle of every port (TS, C#, Java/Kotlin, Python, Rust), so
  existing models load and generate identically. A model that uses a left-out pack's
  vocabulary gets a loader error (new error-packs-left-out-*-used fixtures). The
  verify requirements gate reads through the pack.
- A pack subtype declared with extendsBase may fold a base another provider
  registered (object.report folds object.base); folded attributes keep the base's
  owner under ADR-0062.
- Core vocabulary pin, registry manifest (root requirement child gains min 0 /
  max null), metamodel docs, site reference and payload regenerated.
- GOVERNANCE.md: an attribute promoted from a pack into core keeps its name and
  meaning.
- B4: Mustache and Jinja raise ERR_VAR_NOT_ON_PAYLOAD for a variable or dotted path
  absent from the payload, in every port that renders; render runners learn
  expected-error.txt.
- B5: rules rule P3 refuses two permission points whose names resolve equal when at
  least one name is derived (ERR_TRANSITION_NAME_COLLISION), in every port.
- C3: Python checks @union shape and @Grain views at load; both must-fail fixtures
  leave its expected-failures ledger.

* fix(rules): compare P3 permission names exactly, so '::' and '.' are not one name

The P3 collision check rewrote '::' to '.' before comparing, so a derived
p::Order.open counted as a collision with the transition's p.Order.open. They
are different names in the metadata and the policy receives them as written.
Removed the rewrite in TS, C#, Java, Python and Rust. The former
error-rules-permission-name-op-package fixture becomes
rules-permission-name-package-separator-distinct, which every port's
conformance runner now loads clean.

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

* no-mistakes(test): Wrap two rustfmt-flagged lines in Rust registry and rules

* no-mistakes(document): sync docs with packs, render errors, P3

* no-mistakes(document): point pack docs at vocabulary owner

* feat(rust): raise ERR_VAR_NOT_ON_PAYLOAD in the Rust renderer

The rebase onto main brought in the metaobjects-render crate (#630), whose
corpus runner read expected.txt for every render case. This branch adds two
render-conformance cases that expect a missing-variable error instead, so the
Rust renderer now refuses an interpolated name the payload lacks, with the
same message and the same rules as the reference (sections over an absent
name stay legal, null is present, only rendered bodies are checked), and the
runner learns the expected-error.txt convention.

* docs(conformance): recount render and Jinja cases after rebasing onto #634

Main's #634 added render-conformance cases and two corpora while this branch
added two render error cases and a Jinja error case; the counts and the
showcase payload are recomputed from the fixtures on disk.

* fix(render): check missing variables with the reference's whole-path lookup in every port

The B4 missing-variable check follows TypeScript on mustache.js: a dotted
name is tried whole against each context from the innermost outward, and a
list's length is a property. Python and C# now resolve that way; the Java
check pass falls back to a whole-path lookup before raising; the Rust check
pass counts a list's length as present. So no port raises
ERR_VAR_NOT_ON_PAYLOAD on a name TypeScript renders. What the C#, Java and
Rust engines then print for those names is a separate parity question.

* fix(render): treat 0 as falsy in Python sections and the C# check pass, as mustache.js does

An empty list's length now resolves, so {{#items.length}} on an empty list
rendered its body in Python. mustache.js tests sections with JavaScript
falsiness, where 0 and NaN are falsy; Python's section test and the C#
check pass now do the same. Adds a Python test pinning the shadowed-prefix,
length, zero and null-mid-path cases against the TypeScript output.

Also tidies the Java whole-path fallback (imports, a named length constant,
loop-invariant work hoisted) and the C# lookup (using, a redundant assignment).

* no-mistakes(review): Pin render parity with shared fixtures

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

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

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

* no-mistakes(review): Exempt only folded base attrs from Rust ownership check

* no-mistakes(document): Docs: Rust ledger, render parity, pack counts
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