diff --git a/agent-context-shipped/files/3708591f7234348e.md b/agent-context-shipped/files/65026d55d54bec5a.md similarity index 97% rename from agent-context-shipped/files/3708591f7234348e.md rename to agent-context-shipped/files/65026d55d54bec5a.md index 086255b208..e72ad3b461 100644 --- a/agent-context-shipped/files/3708591f7234348e.md +++ b/agent-context-shipped/files/65026d55d54bec5a.md @@ -119,11 +119,11 @@ class in a `` element — the plugin loads it from the project classp SHAPE is the thing being iterated on or the same output is wanted in another language; prefer code when the logic is gnarly. See `docs/features/codegen-concepts.md` §3. -To re-scaffold the agent-context into a Java project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a Java project, run the Maven goal. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server java [--out ] +mvn metaobjects:agent-docs -Dmetaobjects.servers=java [-Dmetaobjects.clients=] ``` --- diff --git a/server/python/src/metaobjects/agent_context/shipped/files/a3cd9779195de55f.md b/agent-context-shipped/files/75e6eb82781a5f86.md similarity index 98% rename from server/python/src/metaobjects/agent_context/shipped/files/a3cd9779195de55f.md rename to agent-context-shipped/files/75e6eb82781a5f86.md index af3a11584f..93a0714994 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/a3cd9779195de55f.md +++ b/agent-context-shipped/files/75e6eb82781a5f86.md @@ -329,8 +329,7 @@ consuming fields reference a hand-written/third-party enum, and the C# namespace ## Re-scaffold this context -Agent-context scaffolding is owned by the Node `meta` CLI (ADR-0015). `dotnet meta -agent-docs` only prints a redirect and exits non-zero — it does **not** scaffold. -(Re)scaffold the slim always-on Markdown + these `metaobjects-*` skills with -`npx meta agent-docs --server csharp [--client ] [--out ]`. A C# consumer -needs Node `meta` (npx) for this one scaffold step; codegen + verify stay on `dotnet meta`. +Run `dotnet meta agent-docs` to (re)scaffold the slim always-on Markdown and these +`metaobjects-*` skills into the project. It needs no Node: the files ship inside the +`MetaObjects.Cli` tool. Add `--client ` for a web client and `--out ` for another +project root. diff --git a/server/python/src/metaobjects/agent_context/shipped/files/d6c5d2863183241f.md b/agent-context-shipped/files/91fd9a97e8d84a91.md similarity index 97% rename from server/python/src/metaobjects/agent_context/shipped/files/d6c5d2863183241f.md rename to agent-context-shipped/files/91fd9a97e8d84a91.md index af4334cf67..4ab60b457c 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/d6c5d2863183241f.md +++ b/agent-context-shipped/files/91fd9a97e8d84a91.md @@ -124,11 +124,11 @@ template when the output SHAPE is the thing being iterated on or the same output wanted in another language; prefer code when the logic is gnarly. See `docs/features/codegen-concepts.md` §3. -To re-scaffold the agent-context into a Kotlin project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a Kotlin project, run the Maven goal. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server kotlin [--out ] +mvn metaobjects:agent-docs -Dmetaobjects.servers=kotlin [-Dmetaobjects.clients=] ``` --- diff --git a/agent-context-shipped/files/a978da9641eb06d6.md b/agent-context-shipped/files/a994506de7729cdb.md similarity index 97% rename from agent-context-shipped/files/a978da9641eb06d6.md rename to agent-context-shipped/files/a994506de7729cdb.md index beee7e9340..2fb4a890e8 100644 --- a/agent-context-shipped/files/a978da9641eb06d6.md +++ b/agent-context-shipped/files/a994506de7729cdb.md @@ -120,15 +120,13 @@ hand-written layer the model fully describes, resolves to a generator the projec matters. Recommend it; it is the primary path. Worked template example: `docs/ports/csharp.md`. -To re-scaffold the agent-context into a C# project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a C# project, run the .NET tool. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server csharp [--out ] +dotnet meta agent-docs [--client ] [--out ] ``` -(`dotnet meta agent-docs` is a non-executing stub — it prints this redirect and exits 1.) - --- ## Version-skew check diff --git a/agent-context-shipped/manifest.json b/agent-context-shipped/manifest.json index ca50485056..817d76a054 100644 --- a/agent-context-shipped/manifest.json +++ b/agent-context-shipped/manifest.json @@ -1813,7 +1813,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2007,7 +2007,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2203,7 +2203,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2403,7 +2403,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2604,7 +2604,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2809,7 +2809,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3013,7 +3013,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3209,7 +3209,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3403,7 +3403,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3597,7 +3597,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3793,7 +3793,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3993,7 +3993,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4194,7 +4194,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4399,7 +4399,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4603,7 +4603,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4799,7 +4799,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4989,7 +4989,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5097,7 +5097,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -5183,7 +5183,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5291,7 +5291,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -5379,7 +5379,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5487,7 +5487,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -5579,7 +5579,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5687,7 +5687,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -5780,7 +5780,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5888,7 +5888,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -5985,7 +5985,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6093,7 +6093,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -6189,7 +6189,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6297,7 +6297,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -6385,7 +6385,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6493,7 +6493,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -9604,11 +9604,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -9819,11 +9819,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10036,11 +10036,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10257,11 +10257,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10479,11 +10479,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10705,11 +10705,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10930,11 +10930,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -11147,11 +11147,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", diff --git a/agent-context/skills/metaobjects-audit/references/csharp.md b/agent-context/skills/metaobjects-audit/references/csharp.md index beee7e9340..2fb4a890e8 100644 --- a/agent-context/skills/metaobjects-audit/references/csharp.md +++ b/agent-context/skills/metaobjects-audit/references/csharp.md @@ -120,15 +120,13 @@ hand-written layer the model fully describes, resolves to a generator the projec matters. Recommend it; it is the primary path. Worked template example: `docs/ports/csharp.md`. -To re-scaffold the agent-context into a C# project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a C# project, run the .NET tool. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server csharp [--out ] +dotnet meta agent-docs [--client ] [--out ] ``` -(`dotnet meta agent-docs` is a non-executing stub — it prints this redirect and exits 1.) - --- ## Version-skew check diff --git a/agent-context/skills/metaobjects-audit/references/java.md b/agent-context/skills/metaobjects-audit/references/java.md index 086255b208..e72ad3b461 100644 --- a/agent-context/skills/metaobjects-audit/references/java.md +++ b/agent-context/skills/metaobjects-audit/references/java.md @@ -119,11 +119,11 @@ class in a `` element — the plugin loads it from the project classp SHAPE is the thing being iterated on or the same output is wanted in another language; prefer code when the logic is gnarly. See `docs/features/codegen-concepts.md` §3. -To re-scaffold the agent-context into a Java project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a Java project, run the Maven goal. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server java [--out ] +mvn metaobjects:agent-docs -Dmetaobjects.servers=java [-Dmetaobjects.clients=] ``` --- diff --git a/agent-context/skills/metaobjects-audit/references/kotlin.md b/agent-context/skills/metaobjects-audit/references/kotlin.md index af4334cf67..4ab60b457c 100644 --- a/agent-context/skills/metaobjects-audit/references/kotlin.md +++ b/agent-context/skills/metaobjects-audit/references/kotlin.md @@ -124,11 +124,11 @@ template when the output SHAPE is the thing being iterated on or the same output wanted in another language; prefer code when the logic is gnarly. See `docs/features/codegen-concepts.md` §3. -To re-scaffold the agent-context into a Kotlin project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a Kotlin project, run the Maven goal. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server kotlin [--out ] +mvn metaobjects:agent-docs -Dmetaobjects.servers=kotlin [-Dmetaobjects.clients=] ``` --- diff --git a/agent-context/skills/metaobjects-codegen/references/csharp.md b/agent-context/skills/metaobjects-codegen/references/csharp.md index af3a11584f..93a0714994 100644 --- a/agent-context/skills/metaobjects-codegen/references/csharp.md +++ b/agent-context/skills/metaobjects-codegen/references/csharp.md @@ -329,8 +329,7 @@ consuming fields reference a hand-written/third-party enum, and the C# namespace ## Re-scaffold this context -Agent-context scaffolding is owned by the Node `meta` CLI (ADR-0015). `dotnet meta -agent-docs` only prints a redirect and exits non-zero — it does **not** scaffold. -(Re)scaffold the slim always-on Markdown + these `metaobjects-*` skills with -`npx meta agent-docs --server csharp [--client ] [--out ]`. A C# consumer -needs Node `meta` (npx) for this one scaffold step; codegen + verify stay on `dotnet meta`. +Run `dotnet meta agent-docs` to (re)scaffold the slim always-on Markdown and these +`metaobjects-*` skills into the project. It needs no Node: the files ship inside the +`MetaObjects.Cli` tool. Add `--client ` for a web client and `--out ` for another +project root. diff --git a/changelog.d/agent-docs-native-every-port.md b/changelog.d/agent-docs-native-every-port.md new file mode 100644 index 0000000000..217fe236ca --- /dev/null +++ b/changelog.d/agent-docs-native-every-port.md @@ -0,0 +1,21 @@ +- **`agent-docs` writes the agent files natively in C#, Java, Kotlin and Rust, with no Node.** + `dotnet meta agent-docs`, `mvn metaobjects:agent-docs` (Java and Kotlin) and the new + `cargo meta agent-docs` write `.metaobjects/AGENTS.md`, the `metaobjects-*` skills, the + `.metaobjects/.agent-context.json` manifest and the root `AGENTS.md` / `CLAUDE.md` import, byte + for byte what `meta agent-docs` and Python's `metaobjects agent-docs` write. Before, the C# and + Maven commands printed "run `npx meta agent-docs`" and exited 1, and Rust had no command. Each + copies one stack out of the built `agent-context-shipped/` tree it carries (C# and the Maven + plugin embed it at build time; the Rust crate, like the Python wheel, keeps a committed copy + that `scripts/sync-agent-context-shipped.sh` refreshes, renamed from + `sync-python-agent-context.sh`, and the `gates` lane fails when either copy is stale). The + flags are `--server`, `--client`, `--out` and `--no-wire-root` + (`-Dmetaobjects.servers`/`clients`/`outputDirectory`/`wireRoot` on Maven); with none, the + stack the last run recorded, else the port's own language. The re-run rules are the Node + CLI's: an unchanged file is not rewritten, a hand-edited one gets `.new`, an untouched + orphan is pruned. The Maven goal stamps the npm-line version (`8.3.0` writes `v1.3.0` links + and a `1.3.0` manifest), so the staleness check stays quiet after a native run. The `gen` + and `verify` staleness nudge in C# and Java now names the port's own command. Every port's + tests reproduce every `fixtures/agent-context-conformance/` stack, not only their own, so the + corpus is a cross-port gate. The shipped C#, Java and Kotlin skill references now tell an + agent to run the port's command instead of `npx meta agent-docs`; refresh the agent files to + pick that up. diff --git a/changelog.d/agent-pages-every-port.md b/changelog.d/agent-pages-every-port.md index 69dc1ebe58..be59f2b06c 100644 --- a/changelog.d/agent-pages-every-port.md +++ b/changelog.d/agent-pages-every-port.md @@ -24,8 +24,8 @@ `requirements.md`; delete the committed copy (and its `.hashes/` entry goes with the run). **The always-on agent file points at the agent pages, only when they exist.** `meta init` - (and `--refresh-docs`), `meta agent-docs` (which the C# and Java commands hand off to) and - Python's `metaobjects agent-docs` now add a "Pages + (and `--refresh-docs`) and every port's `agent-docs` command (`meta`, `metaobjects`, + `dotnet meta`, `mvn metaobjects:`, `cargo meta`) now add a "Pages generated for this project" section to `.metaobjects/AGENTS.md`, naming each agent page the project's last `gen` wrote (read from the committed `.metaobjects/.gen-state/.hashes/`) and when to read it. A project that wires none of them gets the file unchanged. Refresh the agent diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 83a2d1a6e8..6aa8b8da6e 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -53,8 +53,8 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/scope-conformance/`](../fixtures/scope-conformance/) | 10 cases | ✓ (reference implementation) | ✓ | inherits via Java | ✓ | ✓ | — | | [`fixtures/dependency-conformance/`](../fixtures/dependency-conformance/) | 47 cases (36 resolution, 7 of them with a ledger arm, + 11 check) + 32 transport cases | ✓ (reference implementation; all four arms) | ✓ (resolution arm, all 36, ledger included; check arm, all 11) | inherits via Java | ✓ (resolution arm, all 36, ledger included; check arm, all 11, as `verify --deps`) | ✓ (resolution arm, all 36 identically, ledger included; check arm, all 11, as `deps check` and `verify --deps`; the transport arm is Node-only) | — | | [`fixtures/shared-model-conformance/`](../fixtures/shared-model-conformance/) | 15 cases (9 publish + 6 refusal) | ✓ (reference implementation) | ✓ (all 15; `SharedModelConformanceTest`) | inherits via Java (`KotlinSharedModelGeneratorTest` pins the generator) | ✓ (all 15; `SharedModelConformanceTests`) | ✓ (all 15; `test_shared_model_conformance.py`) | — | -| [`fixtures/agent-context-conformance/`](../fixtures/agent-context-conformance/) | 6 | ✓ (the emitter is TS-owned) | — | — | — | — | — | -| [`fixtures/agent-pages-pointer/`](../fixtures/agent-pages-pointer/) (the always-on agent file names the agent pages the last `gen` wrote, from the committed `.hashes/`) | 3 cases | ✓ (reference) | — (`metaobjects:agent-docs` runs the Node CLI) | — | — (`dotnet meta agent-docs` runs the Node CLI) | ✓ | — (no agent-context scaffold) | +| [`fixtures/agent-context-conformance/`](../fixtures/agent-context-conformance/) (the static agent files each port's `agent-docs` writes; every port runs all 6 stacks, not only its own) | 6 | ✓ (reference) | ✓ (`metaobjects:agent-docs`) | inherits via Java (the same Maven goal) | ✓ (`dotnet meta agent-docs`) | ✓ | ✓ (`cargo meta agent-docs`) | +| [`fixtures/agent-pages-pointer/`](../fixtures/agent-pages-pointer/) (the always-on agent file names the agent pages the last `gen` wrote, from the committed `.hashes/`) | 3 cases | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | ✓ | | [`fixtures/list-query-conformance/`](../fixtures/list-query-conformance/) (how a list route reads its query string: filter tree, search, sort, page, or the named 400) | 95 cases | ✓ (reference; the source of the expected answers) | planned (R-JV) | planned (R-KT) | ✓ (`ListQueryConformanceTests`) | planned (R-PY) | ✓ (`list_query_conformance.rs`, the parser `meta_http` ships) | | [`fixtures/docs-page-conformance/`](../fixtures/docs-page-conformance/) (the requirement pages and the model-only schema page, built from the docs view: each page's rows, data and bytes) | 4 cases | ✓ (reference; the source of the expected bytes) | ✓ (`DocsPageConformanceTest`) | ✓ (through Java: the Kotlin generators call the JVM page builder) | ✓ | ✓ | ✓ (rows from the view; no requirement ledger, RS-V2) | | [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) (the vocabulary reference pages: each page's data and bytes, shared `templates/metamodel/`) | 1 (23 pages) | ✓ (reference; the source of the expected bytes) | ✓ (`MetamodelDocsCorpusTest`) | ✓ (through Java's builder and emitter) | ✓ (`MetamodelDocsTests`) | ✓ (`test_metamodel_docs_conformance.py`) | ✓ (`tests/metamodel_docs.rs`) | @@ -857,9 +857,13 @@ All 3 cases → [features/cli.md](features/cli.md#agent-context-scaffold). Each root and the section the always-on `.metaobjects/AGENTS.md` gains above `## Rules`: the agent pages the committed `.metaobjects/.gen-state/.hashes/` record, in a fixed order, and nothing at all when none is recorded. **Held to it:** -`server/typescript/packages/sdk/test/agent-context/agent-pages.test.ts` and -`server/python/tests/unit/test_agent_docs.py`, the two ports that write the always-on file. C# -and Java hand `agent-docs` to the Node CLI, and Rust scaffolds no agent context. +`server/typescript/packages/sdk/test/agent-context/agent-pages.test.ts`, +`server/python/tests/unit/test_agent_docs.py`, +`server/csharp/MetaObjects.Cli.Tests/AgentDocsCommandTests.cs`, +`server/java/maven-plugin/src/test/java/com/metaobjects/mojo/AgentDocsWriterTest.java` (Kotlin +runs the same Maven goal) and `server/rust/metaobjects-cli/tests/agent_docs.rs`. The same tests +reproduce every case of `fixtures/agent-context-conformance/` byte for byte, so each port's +`agent-docs` writes the files the TypeScript assembler writes, for any stack. ### `fixtures/requirement-test-identity-conformance/` (27 cases) diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 9ec56c5f17..c77b0c79bd 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -789,7 +789,7 @@ Five packages, version-locked at the C# port version (the `` in | `MetaObjects.Render` | Mustache render + payload-VO + `verify` | | `MetaObjects.Codegen` | EF Core + ASP.NET codegen (writes EF and ASP.NET code as text; depends on neither) | | `MetaObjects.AspNetCore` | The helper runtime generated routes call (filter parser, EF Core filter dispatch, validation, wire forms); the APP references it, the tool does not | -| `MetaObjects.Cli` | The `dotnet meta` .NET tool (`gen` / `verify`; `agent-docs` is a redirect stub to the Node `meta` CLI) | +| `MetaObjects.Cli` | The `dotnet meta` .NET tool (`gen` / `verify` / `agent-docs`; `agent-docs` copies the shipped agent files, no Node) | Shared package metadata lives in [`server/csharp/Directory.Build.props`](../server/csharp/Directory.Build.props); per-package `PackageId`/`Title`/`Description` live in each `.csproj`. Test/integration projects set @@ -922,7 +922,7 @@ Project `metaobjects` → **Settings → Publishing → Add a new GitHub publish (The wheel carries the shipped agent files as a committed copy of `agent-context-shipped/` under `src/metaobjects/agent_context/shipped/`, so `metaobjects agent-docs` needs no Node. - Refresh it with `scripts/sync-python-agent-context.sh`; the `gates` lane and a Python test + Refresh it with `scripts/sync-agent-context-shipped.sh`; the `gates` lane and a Python test fail when it is stale. There is no build hook and no `force-include` of `../../agent-context`.) ## Procedure diff --git a/docs/features/cli.md b/docs/features/cli.md index e70dcb5e27..1457f6e6e6 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -26,7 +26,7 @@ command surface splits in two: | Capability | Tool | Invocation | Notes | |---|---|---|---| | Project scaffold (`init`) | Node `meta` | `meta init` | TS projects; `--dialect sqlite\|postgres\|mysql\|d1` writes the codegen `dialect` in `metaobjects.config.ts` and, for sqlite, postgres and d1, `migrate.dialect` in `.metaobjects/config.json` (d1 is `--d1`; MySQL schema is not `meta migrate`'s). A new `.metaobjects/config.json` also carries `"api": { "pagination": { "defaultLimit": 50, "maxLimit": 1000 }, "unknownFields": "reject" }`, the generated list routes' page size and the refusal of undeclared write keys ([api-contract.md](api-contract.md)); for `--dialect sqlite` it also adds `@libsql/kysely-libsql` to the project's `dependencies`, the SQLite driver the CLI's optional peer names (run your package manager's install afterwards); `--force` over an existing config does not add it. `--with-services` wires the recommended service list ([business-rules.md](business-rules.md#the-service-layer-typescript)) instead of the empty one, and `--with-docs` the two docs generators | -| **Agent-context scaffold** (`agent-docs`) | **Node `meta`** | `npx meta agent-docs --server ` | **any backend** — single assembler (ADR-0033); the Python CLI writes the same files itself (`metaobjects agent-docs`, no Node); the C# and Java/Kotlin CLIs still redirect here | +| **Agent-context scaffold** (`agent-docs`) | **Node `meta`** | `npx meta agent-docs --server ` | **any backend** — single assembler (ADR-0033); every port writes the same files itself with no Node: `metaobjects agent-docs` (Python), `dotnet meta agent-docs` (C#), `mvn metaobjects:agent-docs` (Java/Kotlin), `cargo meta agent-docs` (Rust) | | **Expected schema** (`schema`) | **Node `meta`** | `meta schema [--dialect ] [--as ddl\|json]` | **any backend** — read-only: prints the schema the metadata expects as DDL or as the neutral document ([schema-snapshot-format.md](schema-snapshot-format.md)); reads no database; writes nothing unless `--out` names a file | | **Schema migrate** | **Node `meta`** | `meta migrate` | **any backend** — the reference migration helper, one option beside each language's own tool (ADR-0015) | | **Schema drift** (`verify --db`) | **Node `meta`** | `meta verify --db` | **any backend** — live-DB drift, run by the Node CLI whichever tool built the schema (ADR-0015 Amendment 2) | @@ -920,9 +920,7 @@ The always-on `.metaobjects/AGENTS.md` and the `metaobjects-*` skills (under `.claude/skills/` by default, or wherever `--skills-dir` puts them, such as `.agents/skills/` for assistants that read that) are assembled by **one** tool: the Node `meta agent-docs` command. Per [ADR-0033](../../spec/decisions/ADR-0033-single-agent-context-assembler.md) -the per-port native assemblers (Python/Java/C#) and their byte-identity conformance -gates were removed — that content is effectively one static artifact, and every port -needs no more than the Node `meta` CLI or its binary, and only for the reference migration helper or `verify --db` (ADR-0015 Amendment 2). +the per-port assemblers do not re-derive the content: each port copies a pre-built tree (see below), so no port needs Node for `agent-docs`. Node is needed only for the reference migration helper or `verify --db` (ADR-0015 Amendment 2). ```bash npx meta agent-docs --server # csharp | java | kotlin | python | rust | node @@ -934,19 +932,33 @@ and Java with Kotlin, each with no client, React, React with TanStack or Angular committed at `agent-context-shipped/` (a manifest and each distinct file once), and a port's package embeds it so its command can copy one stack out with no Node on the path. `agent-context-shipped/README.md` is the contract that command follows, and the sdk's -`shipped.test.ts` fails when the tree is stale. **Python's command has landed**: -`metaobjects agent-docs [--server ]... [--client ]... [--out ] [--no-wire-root]` -copies one stack out of a committed copy of the tree inside the wheel (refreshed by -`scripts/sync-python-agent-context.sh`, gated for drift), pins the guide links to the release -tag, and keeps the Node CLI's re-run rules: an identical file is not rewritten, a hand-edited -file gets the fresh text beside it as `.new`, and the `.metaobjects/.agent-context.json` -manifest is rewritten only when its text changed. `--skills-dir` and `--no-skills` stay with -the Node CLI. Until the other ports' commands land, their stubs below still redirect. +`shipped.test.ts` fails when the tree is stale. **Every port's command has landed**: + +```bash +metaobjects agent-docs [--server ]... [--client ]... [--out ] [--no-wire-root] # Python +dotnet meta agent-docs [--server ]... [--client ]... [--out ] [--no-wire-root] # C# +cargo meta agent-docs [--server ]... [--client ]... [--out ] [--no-wire-root] # Rust +mvn metaobjects:agent-docs [-Dmetaobjects.servers=java,kotlin] [-Dmetaobjects.clients=react] \ + [-Dmetaobjects.outputDirectory=] [-Dmetaobjects.wireRoot=false] # Java/Kotlin +``` + +Each copies one stack out of the tree it carries (C# and the Maven plugin embed the repo-root +tree at build time; the Python wheel and the Rust crate keep a committed copy, because a +published sdist or crate holds only its own directory, refreshed by +`scripts/sync-agent-context-shipped.sh` and gated for drift). With no `--server` and no +`--client` it reuses the stack the last run recorded, else the port's own language. It pins +the guide links to the release tag (the Maven plugin stamps the npm-line version, so `8.3.0` +writes `v1.3.0` links), and keeps the Node CLI's re-run rules: an identical file is not +rewritten, a hand-edited file gets the fresh text beside it as `.new`, an orphan this tool +wrote and nobody touched is deleted, and the `.metaobjects/.agent-context.json` manifest is +rewritten only when its text changed. `fixtures/agent-context-conformance/` holds the goldens, +and every port reproduces every case there, whatever its default. `--skills-dir` and +`--no-skills` stay with the Node CLI. **The always-on file points at the agent pages only when they are wired.** When the project's committed `.metaobjects/.gen-state/.hashes/` record an agent page the last `gen` wrote (`agent/schema.md`, `agent/ui.md`, `agent/requirements.md`, `AGENT-API.md`, `requirements.toon`), -both `meta agent-docs` and Python's `metaobjects agent-docs` add a section above `## Rules` in +every port's `agent-docs` command (`meta agent-docs` included) adds a section above `## Rules` in `.metaobjects/AGENTS.md` that names each one by its path. With none recorded the file is exactly as shipped, so it never sends an agent to a page that does not exist. It recognises the pages by those default paths only: an `agent-docs` run with a custom `subDir` (`llm/schema.md`) writes @@ -954,11 +966,9 @@ pages the section does not name, so they get no line rather than a wrong one, an only agent pages are such gets no section. The section's template is the shipped manifest's `agentPagesTemplate`, and `fixtures/agent-pages-pointer/` gates it. -The C# and Java/Kotlin CLIs keep a **non-executing `agent-docs` pointer -stub** that prints `agent-context scaffolding moved to the meta CLI — run: npx meta -agent-docs --server ` to stderr and exits non-zero. The **live staleness check** -in `gen`/`verify` stays per-port (it only *reads* the scaffold to nudge when it drifts); -its message now points at `npx meta agent-docs --server `. In the Node `meta`, `gen` +The **live staleness check** in `gen`/`verify` stays per-port (it only *reads* the scaffold to +nudge when it drifts); its message names the port's own command (`dotnet meta agent-docs`, +`mvn metaobjects:agent-docs`, `metaobjects agent-docs`). In the Node `meta`, `gen` and `verify` also advise (exit code unchanged) when the model declares `requirement.*` nodes and the scaffolded context has no requirements pages, naming `meta init --docs-only --refresh-docs`; `gen` advises separately when no `requirement-tests` generator is wired, diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index e7c92876ad..a114a6786b 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -374,8 +374,8 @@ shared `templates/requirements/` and `templates/agent/` Mustache pages, byte for under `TemplateRoot` overrides a shipped page. `agent-docs`'s `SubDir` is the directory the pages land in, `agent` by default (`"llm"` writes `llm/schema.md`; `""` writes at the root), as in every port. `agent/ui.md` and the physical schema (SQL types, -defaults, indexes) stay TypeScript's. The always-on agent file comes from the Node CLI -(`npx meta agent-docs`), which names these pages once a `gen` has written them. +defaults, indexes) stay TypeScript's. The always-on agent file comes from +`dotnet meta agent-docs` (no Node), which names these pages once a `gen` has written them. **Generators write through a code writer.** `MetaObjects.Codegen.Writer.CsWriter` is where a generator's layout lives (ADR-0063): it owns the indent, the braces, the `using` lines and the diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 933bde7ade..c8313e0147 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -61,6 +61,7 @@ and the same `git` + `rev` on a `metaobjects` dependency). The candidate log | `cargo meta gen [ENTITY...]` | Generates the crates. It skips the whole run when the model, the project config and the generators are unchanged ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)), writes only files whose bytes changed, removes a generated file nothing emits any more, and refuses to overwrite or delete a generated file that was edited by hand. It prints what it created, updated and removed, and the crates to re-check. | | `cargo meta verify [--codegen] [--templates] [--full]` | The codegen drift gate: renders in memory, compares with disk, writes nothing, and exits 1 on drift, naming each file. Locally it may answer from the stored skip key; `--full`, or a set `CI` variable, always renders. `--codegen` runs that gate alone. `--templates` is the template drift gate: each `template.*` body (under `prompts/`, or `--prompts `) against its payload value object, and each prompt's `@responseRef` reply; a bare `verify` runs it too, and a Jinja body is refused (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`). A bare `verify` also runs the business-rules gate ([ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)) on the loaded model, and prints nothing about it when the model declares no operation and no transition; an error-severity finding (a `rules.permissions.names` of `require`, or `verify.lifecycle.unreachable` of `error`) exits 1. `--db` and `--deps` exit 2 with the reason and where that check lives. | | `cargo meta eject ...` | Copies a shipped generator into the project to own. An existing copy is refused; `--force` replaces it with the reference, and leaves a copy that already matches untouched. `--undo` takes back copies still identical to the shipped source; `--list` shows what can be ejected and how each owned copy compares. See [Owning a generator](#owning-a-generator). | +| `cargo meta agent-docs [--server ]... [--client ]... [--out ] [--no-wire-root]` | Writes the static agent files, `.metaobjects/AGENTS.md`, the `metaobjects-*` skills under `.claude/skills/` and the `.metaobjects/.agent-context.json` manifest, byte for byte what every other port's `agent-docs` writes (`fixtures/agent-context-conformance/`), with no Node: the files are embedded in the crate. With no `--server` and no `--client` it reuses the stack the last run recorded, else `rust`. A re-run writes nothing for an unchanged file and puts fresh text beside a hand-edited one as `.new`; it also adds the `@.metaobjects/AGENTS.md` import to the root `AGENTS.md` / `CLAUDE.md` unless `--no-wire-root`. An unknown stack exits 2. | `gen` and `verify` share `--project `, `--out ` (default `generated`), `--generators `, `--strict` and `--timings`. `gen` adds `--force` and `--list`. `cargo meta --help` is the reference. @@ -504,8 +505,8 @@ the explorer shows the ledger. `agent/ui.md` stays a TypeScript page. What is absent here: this port has no requirement ledger of its own (no `requirements.inherit` collection and no requirement gate in `cargo meta verify`, the RS-V2 work), so the pages list every requirement the view carries, an imported package's included, where a port with the ledger lists -only those the collection counts. The project has no always-on agent file to point at the pages -either: `cargo meta` scaffolds no agent context. +only those the collection counts. The always-on agent file comes from +`cargo meta agent-docs` (no Node), which names these pages once a `gen` has written them. ### `docs-site`: the model explorer diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/csharp.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/csharp.md index beee7e9340..2fb4a890e8 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/csharp.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/csharp.md @@ -120,15 +120,13 @@ hand-written layer the model fully describes, resolves to a generator the projec matters. Recommend it; it is the primary path. Worked template example: `docs/ports/csharp.md`. -To re-scaffold the agent-context into a C# project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a C# project, run the .NET tool. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server csharp [--out ] +dotnet meta agent-docs [--client ] [--out ] ``` -(`dotnet meta agent-docs` is a non-executing stub — it prints this redirect and exits 1.) - --- ## Version-skew check diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md index af3a11584f..93a0714994 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/references/csharp.md @@ -329,8 +329,7 @@ consuming fields reference a hand-written/third-party enum, and the C# namespace ## Re-scaffold this context -Agent-context scaffolding is owned by the Node `meta` CLI (ADR-0015). `dotnet meta -agent-docs` only prints a redirect and exits non-zero — it does **not** scaffold. -(Re)scaffold the slim always-on Markdown + these `metaobjects-*` skills with -`npx meta agent-docs --server csharp [--client ] [--out ]`. A C# consumer -needs Node `meta` (npx) for this one scaffold step; codegen + verify stay on `dotnet meta`. +Run `dotnet meta agent-docs` to (re)scaffold the slim always-on Markdown and these +`metaobjects-*` skills into the project. It needs no Node: the files ship inside the +`MetaObjects.Cli` tool. Add `--client ` for a web client and `--out ` for another +project root. diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/java.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/java.md index 086255b208..e72ad3b461 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/java.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/java.md @@ -119,11 +119,11 @@ class in a `` element — the plugin loads it from the project classp SHAPE is the thing being iterated on or the same output is wanted in another language; prefer code when the logic is gnarly. See `docs/features/codegen-concepts.md` §3. -To re-scaffold the agent-context into a Java project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a Java project, run the Maven goal. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server java [--out ] +mvn metaobjects:agent-docs -Dmetaobjects.servers=java [-Dmetaobjects.clients=] ``` --- diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/kotlin.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/kotlin.md index af4334cf67..4ab60b457c 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/kotlin.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/kotlin.md @@ -124,11 +124,11 @@ template when the output SHAPE is the thing being iterated on or the same output wanted in another language; prefer code when the logic is gnarly. See `docs/features/codegen-concepts.md` §3. -To re-scaffold the agent-context into a Kotlin project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a Kotlin project, run the Maven goal. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server kotlin [--out ] +mvn metaobjects:agent-docs -Dmetaobjects.servers=kotlin [-Dmetaobjects.clients=] ``` --- diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/java.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/java.md index 086255b208..e72ad3b461 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/java.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/java.md @@ -119,11 +119,11 @@ class in a `` element — the plugin loads it from the project classp SHAPE is the thing being iterated on or the same output is wanted in another language; prefer code when the logic is gnarly. See `docs/features/codegen-concepts.md` §3. -To re-scaffold the agent-context into a Java project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a Java project, run the Maven goal. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server java [--out ] +mvn metaobjects:agent-docs -Dmetaobjects.servers=java [-Dmetaobjects.clients=] ``` --- diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 817784948d..a49c616125 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -1130,9 +1130,17 @@ gate_doc_template_drift() { return 1 fi } -# The Python wheel's copy of the shipped agent files must equal the repo-root tree. -gate_python_agent_context_drift() { - diff -r -x README.md agent-context-shipped server/python/src/metaobjects/agent_context/shipped +# The Python wheel's and the Rust crate's copies of the shipped agent files must equal the +# repo-root tree (scripts/sync-agent-context-shipped.sh refreshes them). +gate_agent_context_copy_drift() { + local copy rc=0 + # Keep this list in step with the dests in scripts/sync-agent-context-shipped.sh. + for copy in \ + server/python/src/metaobjects/agent_context/shipped \ + server/rust/metaobjects-cli/agent-context-shipped; do + diff -r -x README.md agent-context-shipped "$copy" || { echo " stale copy: $copy (run scripts/sync-agent-context-shipped.sh)"; rc=1; } + done + return $rc } # The explorer app (explorer-app/) must be what its TypeScript sources build, and every port's # copy must equal it (scripts/sync-explorer-app.sh refreshes the copies). @@ -1523,7 +1531,7 @@ run_gates_offline() { if want gates; then step "positioning claims" gate_positioning_claims; fi if want gates; then step "hosted assess prompt builds" gate_assess_prompt; fi if want gates; then step "migration guides vs registry" gate_migration_guides; fi - if want gates; then step "python agent-context copy" gate_python_agent_context_drift; fi + if want gates; then step "agent-context copies" gate_agent_context_copy_drift; fi } # Every gate below runs bun over workspace TypeScript, and on a FRESH CI checkout there is # no node_modules — so a bare `@metaobjectsdev/*` specifier either fails to resolve (what diff --git a/scripts/sync-agent-context-shipped.sh b/scripts/sync-agent-context-shipped.sh new file mode 100755 index 0000000000..c93539d24d --- /dev/null +++ b/scripts/sync-agent-context-shipped.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Refresh each package's committed copy of the shipped agent files from the repo-root tree +# (agent-context-shipped/, built by TypeScript). The Python wheel and the Rust crate carry a +# copy, because a published sdist or crate holds only files inside its own directory, so +# `metaobjects agent-docs` and `cargo meta agent-docs` need no Node. (C# and the Maven plugin +# embed the repo-root tree at build time and keep no copy.) Run after rebuilding the tree; the +# `gates` lane and each port's test fail when a copy is stale. +set -euo pipefail +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +src="$root/agent-context-shipped" +# Keep this list in step with gate_agent_context_copy_drift in scripts/ci-local.sh. +dests=( + "$root/server/python/src/metaobjects/agent_context/shipped" + "$root/server/rust/metaobjects-cli/agent-context-shipped" +) +for dst in "${dests[@]}"; do + mkdir -p "$dst" + # --delete drops stored files a rebuild renamed away; the README stays at the root only. + rsync -a --delete --exclude README.md "$src/" "$dst/" + echo "synced: agent-context-shipped/ -> ${dst#"$root"/}" +done diff --git a/scripts/sync-python-agent-context.sh b/scripts/sync-python-agent-context.sh deleted file mode 100755 index 0ce6644308..0000000000 --- a/scripts/sync-python-agent-context.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bash -# Refresh the Python package's committed copy of the shipped agent files from the repo-root -# tree (agent-context-shipped/, built by TypeScript). The wheel carries the copy, so -# `metaobjects agent-docs` needs no Node. Run after rebuilding the tree; the `gates` lane and -# a Python test fail when the copy is stale. -set -euo pipefail -root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -src="$root/agent-context-shipped" -dst="$root/server/python/src/metaobjects/agent_context/shipped" -mkdir -p "$dst" -# --delete drops stored files a rebuild renamed away; the README stays at the root only. -rsync -a --delete --exclude README.md "$src/" "$dst/" diff --git a/server/csharp/MetaObjects.Cli.Tests/AgentContextStalenessTests.cs b/server/csharp/MetaObjects.Cli.Tests/AgentContextStalenessTests.cs index 235c53b0ec..6958d6b1a7 100644 --- a/server/csharp/MetaObjects.Cli.Tests/AgentContextStalenessTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/AgentContextStalenessTests.cs @@ -5,11 +5,10 @@ // 1. The pure decision — AgentContextScaffold.AgentContextStaleness(manifest, current): // null manifest -> null (no agent context here) // manifest.GeneratedBy == cur -> null (in sync; exact equality on purpose) -// differs / null GeneratedBy -> a one-line nudge naming both versions + npx meta agent-docs +// differs / null GeneratedBy -> a one-line nudge naming both versions + dotnet meta agent-docs // 2. The version source — the installed-assembly version is read, never hardcoded. // -// The stamp test (agent-docs writes generatedBy into the manifest) is removed: agent-docs -// is now a redirect to the Node meta CLI and no longer writes the manifest. +// The stamp (agent-docs writes generatedBy into the manifest) is covered in AgentDocsCommandTests. using MetaObjects.AgentContext; using MetaObjects.Cli; @@ -42,7 +41,7 @@ public void Differing_generatedBy_nudges_naming_both_versions() Assert.NotNull(msg); Assert.Contains("1.0.0", msg); Assert.Contains("2.0.0", msg); - Assert.Contains("npx meta agent-docs", msg); + Assert.Contains("dotnet meta agent-docs", msg); Assert.DoesNotContain("--server", msg); // an explicit --server replaces the recorded stack } @@ -54,7 +53,7 @@ public void Null_generatedBy_nudges_with_older_phrasing() Assert.NotNull(msg); Assert.Contains("an older MetaObjects", msg); Assert.Contains("2.0.0", msg); - Assert.Contains("npx meta agent-docs", msg); + Assert.Contains("dotnet meta agent-docs", msg); Assert.DoesNotContain("--server", msg); // an explicit --server replaces the recorded stack } diff --git a/server/csharp/MetaObjects.Cli.Tests/AgentDocsCommandTests.cs b/server/csharp/MetaObjects.Cli.Tests/AgentDocsCommandTests.cs new file mode 100644 index 0000000000..d2042189cf --- /dev/null +++ b/server/csharp/MetaObjects.Cli.Tests/AgentDocsCommandTests.cs @@ -0,0 +1,334 @@ +// AgentDocsCommandTests — `dotnet meta agent-docs` writes the shipped agent files itself. +// +// The contract is agent-context-shipped/README.md; the reference is Python's +// tests/unit/test_agent_docs.py. Every case of fixtures/agent-context-conformance/ (any port can +// write any stack) and of fixtures/agent-pages-pointer/ is reproduced byte for byte. + +using System.Text; +using System.Text.Json; +using MetaObjects.AgentContext; +using MetaObjects.Cli; +using Xunit; + +namespace MetaObjects.Cli.Tests; + +public sealed class AgentDocsCommandTests : IDisposable +{ + private const string Release = "1.3.0"; + private readonly string _tmp = Path.Combine( + Environment.GetEnvironmentVariable("DEV_SCRATCH") is { Length: > 0 } s ? s : Path.GetTempPath(), + "mo-agent-docs-cs-" + Guid.NewGuid().ToString("N")); + + public AgentDocsCommandTests() => Directory.CreateDirectory(_tmp); + + public void Dispose() + { + if (Directory.Exists(_tmp)) Directory.Delete(_tmp, recursive: true); + } + + private static string RepoRoot() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && !Directory.Exists(Path.Combine(dir.FullName, "agent-context-shipped"))) + dir = dir.Parent; + return dir?.FullName ?? throw new InvalidOperationException("repo root not found"); + } + + private static readonly string Shipped = Path.Combine(RepoRoot(), "agent-context-shipped"); + + private static SortedDictionary Tree(string root) + { + var outTree = new SortedDictionary(StringComparer.Ordinal); + if (!Directory.Exists(root)) return outTree; + foreach (var f in Directory.GetFiles(root, "*", SearchOption.AllDirectories)) + outTree[Path.GetRelativePath(root, f).Replace('\\', '/')] = File.ReadAllText(f, Encoding.UTF8); + return outTree; + } + + private static SortedDictionary WithoutManifest(SortedDictionary t) + { + t.Remove(AgentContextScaffold.ManifestPath); + t.Remove(".metaobjects/config.json"); + return t; + } + + private string Dir(string name) + { + var d = Path.Combine(_tmp, name); + Directory.CreateDirectory(d); + return d; + } + + private static void ChooseMigrate(string root) + { + Directory.CreateDirectory(Path.Combine(root, ".metaobjects")); + File.WriteAllText(Path.Combine(root, ".metaobjects", "config.json"), + "{\"schema_version\": 1, \"migrate\": {\"dialect\": \"postgres\"}}\n"); + } + + public static IEnumerable CorpusCases() => + Directory.GetDirectories(Path.Combine(RepoRoot(), "fixtures", "agent-context-conformance")) + .Where(d => File.Exists(Path.Combine(d, "stack.json"))) + .Select(d => new object[] { Path.GetFileName(d) }) + .OrderBy(a => (string)a[0], StringComparer.Ordinal); + + [Theory] + [MemberData(nameof(CorpusCases))] + public void Every_corpus_case_is_reproduced_byte_for_byte(string name) + { + var caseDir = Path.Combine(RepoRoot(), "fixtures", "agent-context-conformance", name); + using var stack = JsonDocument.Parse(File.ReadAllText(Path.Combine(caseDir, "stack.json"))); + var r = stack.RootElement; + var outDir = Dir(name); + if (r.TryGetProperty("migrate", out var m) && m.GetBoolean()) ChooseMigrate(outDir); + // The goldens are written by a prerelease-or-main build, so their links stay on main. + AgentDocsCommand.Run( + r.GetProperty("servers").EnumerateArray().Select(e => e.GetString()!), + r.GetProperty("clients").EnumerateArray().Select(e => e.GetString()!), + outDir, wireRoot: false, version: "1.3.0-rc.1"); + Assert.Equal(Tree(Path.Combine(caseDir, "expected")), WithoutManifest(Tree(outDir))); + } + + [Fact] + public void Every_csharp_stack_equals_the_tree_after_link_pinning() + { + using var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(Shipped, "manifest.json"))); + var prefix = doc.RootElement.GetProperty("docsLinkPrefix").GetString(); + var docsRef = doc.RootElement.GetProperty("docsRef").GetString(); + var count = 0; + foreach (var s in doc.RootElement.GetProperty("stacks").EnumerateArray()) + { + var servers = s.GetProperty("servers").EnumerateArray().Select(e => e.GetString()!).ToList(); + if (!servers.Contains("csharp")) continue; + var outDir = Dir(s.GetProperty("id").GetString()!); + if (s.GetProperty("migration").GetBoolean()) ChooseMigrate(outDir); + AgentDocsCommand.Run(servers, s.GetProperty("clients").EnumerateArray().Select(e => e.GetString()!), + outDir, wireRoot: false, version: Release); + var expected = new SortedDictionary(StringComparer.Ordinal); + foreach (var f in s.GetProperty("files").EnumerateArray()) + expected[f.GetProperty("path").GetString()!] = + File.ReadAllText(Path.Combine(Shipped, "files", f.GetProperty("file").GetString()!)) + .Replace($"{prefix}{docsRef}/", $"{prefix}v{Release}/"); + Assert.Equal(expected, WithoutManifest(Tree(outDir))); + count++; + } + Assert.Equal(8, count); + } + + [Fact] + public void A_prerelease_or_unresolvable_version_keeps_main() + { + Assert.Equal("v1.3.0", AgentDocsCommand.DocsRefForVersion("1.3.0")); + foreach (var v in new[] { "1.3.0rc1", "1.3.0-rc.1", "0.0.0", "dev", "" }) + Assert.Equal("main", AgentDocsCommand.DocsRefForVersion(v)); + } + + [Fact] + public void Stack_id_orders_servers_then_clients_canonically() + { + Assert.Equal("java-kotlin-react-tanstack", + AgentDocsCommand.ShippedStackId(["kotlin", "java"], ["tanstack", "react"])); + } + + [Fact] + public void An_unknown_stack_is_refused_naming_the_shipped_ids() + { + var outDir = Dir("refused"); + var e = Assert.Throws(() => + AgentDocsCommand.Run(["csharp"], ["tanstack"], outDir, version: Release)); + Assert.Contains("csharp-tanstack", e.Message); + Assert.Contains("csharp-react-tanstack", e.Message); + Assert.Empty(Directory.EnumerateFileSystemEntries(outDir)); + var bad = Assert.Throws(() => + AgentDocsCommand.Run(["cobol"], [], outDir, version: Release)); + Assert.Contains("--server cobol", bad.Message); + } + + [Fact] + public void The_default_server_is_csharp_and_the_manifest_is_stamped() + { + var outDir = Dir("default"); + AgentDocsCommand.Run([], [], outDir, wireRoot: false, version: Release); + var text = File.ReadAllText(Path.Combine(outDir, AgentContextScaffold.ManifestPath)); + using var doc = JsonDocument.Parse(text); + Assert.Equal("csharp", doc.RootElement.GetProperty("servers")[0].GetString()); + Assert.Equal(0, doc.RootElement.GetProperty("clients").GetArrayLength()); + Assert.Equal(Release, doc.RootElement.GetProperty("generatedBy").GetString()); + Assert.StartsWith("{\n \"version\": 1,\n \"generatedBy\": \"1.3.0\",\n \"servers\": [\n \"csharp\"\n ],\n \"clients\": [],\n \"files\": {\n", text); + // The native stamp satisfies the staleness check of this same build. + var manifest = new AgentContextScaffold.Manifest(1, Release, [], [], new Dictionary()); + Assert.Null(AgentContextScaffold.AgentContextStaleness(manifest, Release)); + } + + [Fact] + public void A_client_alone_takes_the_recorded_server_else_csharp() + { + static string Stack(string dir) + { + using var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(dir, AgentContextScaffold.ManifestPath))); + string Names(string key) => string.Join(",", doc.RootElement.GetProperty(key).EnumerateArray().Select(e => e.GetString())); + return Names("servers") + "|" + Names("clients"); + } + var fresh = Dir("client-fresh"); + AgentDocsCommand.Run([], ["react"], fresh, wireRoot: false, version: Release); + Assert.Equal("csharp|react", Stack(fresh)); + var recorded = Dir("client-recorded"); + AgentDocsCommand.Run(["java"], [], recorded, wireRoot: false, version: Release); + AgentDocsCommand.Run([], ["react"], recorded, wireRoot: false, version: Release); + Assert.Equal("java|react", Stack(recorded)); + } + + [Fact] + public void A_rerun_writes_nothing_and_keeps_the_recorded_stack() + { + var outDir = Dir("rerun"); + AgentDocsCommand.Run(["csharp"], ["react"], outDir, version: Release); + var stamp = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc); + var files = Directory.GetFiles(outDir, "*", SearchOption.AllDirectories); + foreach (var f in files) File.SetLastWriteTimeUtc(f, stamp); + var (created, notes) = AgentDocsCommand.Run([], [], outDir, version: Release); + Assert.Empty(created); + Assert.Empty(notes); + Assert.All(files, f => Assert.Equal(stamp, File.GetLastWriteTimeUtc(f))); + } + + [Fact] + public void A_project_with_its_own_skills_dir_is_refused_untouched() + { + var outDir = Dir("skills"); + AgentDocsCommand.Run(["csharp"], [], outDir, wireRoot: false, version: Release); + var mPath = Path.Combine(outDir, AgentContextScaffold.ManifestPath); + File.WriteAllText(mPath, File.ReadAllText(mPath).TrimEnd().TrimEnd('}') + ",\n \"skillsDir\": \".agents/skills\"\n}\n"); + var before = Tree(outDir); + var e = Assert.Throws(() => + AgentDocsCommand.Run([], [], outDir, wireRoot: false, version: Release)); + Assert.Contains("npx meta agent-docs --skills-dir .agents/skills", e.Message); + Assert.Equal(before, Tree(outDir)); + } + + [Fact] + public void A_hand_edited_file_is_kept_and_the_fresh_text_goes_beside_it() + { + var outDir = Dir("edited"); + AgentDocsCommand.Run(["csharp"], [], outDir, wireRoot: false, version: Release); + var agents = Path.Combine(outDir, ".metaobjects", "AGENTS.md"); + var pristine = File.ReadAllText(agents); + File.WriteAllText(agents, pristine + "\nmine\n"); + var (created, notes) = AgentDocsCommand.Run(["csharp"], [], outDir, wireRoot: false, version: Release); + Assert.EndsWith("mine\n", File.ReadAllText(agents)); + Assert.Equal(pristine, File.ReadAllText(agents + ".new")); + Assert.Equal([".metaobjects/AGENTS.md.new"], created); + Assert.Contains(notes, n => n.Contains("hand-edited")); + File.WriteAllText(agents, pristine); + var (again, _) = AgentDocsCommand.Run(["csharp"], [], outDir, wireRoot: false, version: Release); + Assert.Empty(again); + } + + [Fact] + public void An_unedited_file_is_refreshed_when_the_release_moves() + { + var outDir = Dir("moved"); + AgentDocsCommand.Run(["csharp"], [], outDir, wireRoot: false, version: "1.2.0"); + var (created, _) = AgentDocsCommand.Run(["csharp"], [], outDir, wireRoot: false, version: Release); + Assert.NotEmpty(created); + Assert.DoesNotContain(created, c => c.EndsWith(".new")); + var pinned = string.Concat(Directory.GetFiles(outDir, "*.md", SearchOption.AllDirectories).Select(File.ReadAllText)); + Assert.Contains("/blob/v1.3.0/", pinned); + Assert.DoesNotContain("/blob/v1.2.0/", pinned); + } + + [Fact] + public void A_changed_stack_prunes_untouched_orphans_and_keeps_edited_ones() + { + var outDir = Dir("prune"); + AgentDocsCommand.Run(["csharp"], ["react", "tanstack"], outDir, wireRoot: false, version: Release); + var alone = AgentDocsCommand.Materialize(AgentDocsCommand.LoadShipped(), ["csharp"], [], "main") + .Select(kv => kv.Key).ToHashSet(); + var reactOnly = Tree(outDir).Keys.Where(k => !alone.Contains(k) && k != AgentContextScaffold.ManifestPath).ToList(); + Assert.True(reactOnly.Count > 1); + var edited = reactOnly.Order(StringComparer.Ordinal).First(); + File.WriteAllText(Path.Combine(outDir, edited), "mine"); + AgentDocsCommand.Run([], [], outDir, wireRoot: false, version: Release); + Assert.All(reactOnly, p => Assert.True(File.Exists(Path.Combine(outDir, p)))); + var (_, notes) = AgentDocsCommand.Run(["csharp"], [], outDir, wireRoot: false, version: Release); + Assert.Equal("mine", File.ReadAllText(Path.Combine(outDir, edited))); + Assert.Contains(notes, n => n.Contains(edited) && n.Contains("hand-edited")); + Assert.All(reactOnly.Where(p => p != edited), p => Assert.False(File.Exists(Path.Combine(outDir, p)))); + } + + [Fact] + public void Root_files_are_wired_once() + { + var outDir = Path.Combine(_tmp, "proj"); + AgentDocsCommand.Run(["csharp"], [], outDir, version: Release); + AgentDocsCommand.Run(["csharp"], [], outDir, version: Release); + foreach (var name in new[] { "AGENTS.md", "CLAUDE.md" }) + { + var body = File.ReadAllText(Path.Combine(outDir, name)); + Assert.Equal(1, body.Split("@.metaobjects/AGENTS.md").Length - 1); + } + } + + [Fact] + public void The_command_writes_into_out_and_refuses_an_unknown_stack() + { + var outDir = Path.Combine(_tmp, "ctx"); + var stdout = new StringWriter(); + var stderr = new StringWriter(); + Assert.Equal(0, AgentDocsCommand.Execute(["--server", "dotnet", "--client", "react", "--out", outDir, "--no-wire-root"], stdout, stderr)); + Assert.True(File.Exists(Path.Combine(outDir, ".metaobjects", "AGENTS.md"))); + Assert.False(File.Exists(Path.Combine(outDir, "AGENTS.md"))); + var no = Path.Combine(_tmp, "no"); + Assert.Equal(2, AgentDocsCommand.Execute(["--server", "csharp", "--client", "tanstack", "--out", no], stdout, stderr)); + Assert.Contains("csharp-react-tanstack", stderr.ToString()); + Assert.False(Directory.Exists(no)); + Assert.Equal(2, AgentDocsCommand.Execute(["--bogus"], stdout, stderr)); + } + + // ---- the always-on pointer at the agent pages (fixtures/agent-pages-pointer/) -------- + + private static readonly string PointerCases = Path.Combine(RepoRoot(), "fixtures", "agent-pages-pointer", "cases"); + + public static IEnumerable PointerCaseNames() => + Directory.GetDirectories(PointerCases).Select(d => new object[] { Path.GetFileName(d) }); + + private static string PagesTemplate() + { + var tree = AgentDocsCommand.LoadShipped(); + return tree.File(tree.Manifest.GetProperty("agentPagesTemplate").GetString()!); + } + + [Theory] + [MemberData(nameof(PointerCaseNames))] + public void Agent_pages_section_matches_the_corpus(string name) + { + var expected = File.ReadAllText(Path.Combine(PointerCases, name, "expected-section.md")); + Assert.Equal(expected, AgentDocsCommand.RenderAgentPagesSection( + PagesTemplate(), AgentDocsCommand.WiredAgentPages(Path.Combine(PointerCases, name)))); + } + + [Fact] + public void The_pointer_lands_above_the_rules() + { + var plain = Dir("plain"); + AgentDocsCommand.Run(["csharp"], [], plain, version: Release); + var wired = Dir("wired"); + CopyTree(Path.Combine(PointerCases, "wired", ".metaobjects"), Path.Combine(wired, ".metaobjects")); + AgentDocsCommand.Run(["csharp"], [], wired, version: Release); + var before = File.ReadAllText(Path.Combine(plain, ".metaobjects", "AGENTS.md")); + var after = File.ReadAllText(Path.Combine(wired, ".metaobjects", "AGENTS.md")); + var section = File.ReadAllText(Path.Combine(PointerCases, "wired", "expected-section.md")); + var at = before.IndexOf("\n## Rules\n", StringComparison.Ordinal) + 1; + Assert.Equal(before[..at] + section + before[at..], after); + } + + private static void CopyTree(string src, string dst) + { + foreach (var f in Directory.GetFiles(src, "*", SearchOption.AllDirectories)) + { + var target = Path.Combine(dst, Path.GetRelativePath(src, f)); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.Copy(f, target); + } + } +} diff --git a/server/csharp/MetaObjects.Cli/AgentDocsCommand.cs b/server/csharp/MetaObjects.Cli/AgentDocsCommand.cs new file mode 100644 index 0000000000..7926203f21 --- /dev/null +++ b/server/csharp/MetaObjects.Cli/AgentDocsCommand.cs @@ -0,0 +1,606 @@ +// AgentDocsCommand — `dotnet meta agent-docs`: write the shipped agent files into a project, +// with no Node on the path. +// +// The C# side of Python's `metaobjects.agent_context.agent_docs` (the reference). The files +// are the repo-root `agent-context-shipped/` tree, embedded in this tool; its README is the +// contract a port follows: find the stack, pin the guide links to the release tag, write each +// file at its path. Around that, the same scaffolder rules as every other port: the stack +// comes from --server/--client, else the stack the last run recorded in the sidecar manifest, +// else `csharp`; a re-run writes nothing for a file that is already right, parks fresh text +// at `.new` beside a hand-edited file, deletes only orphans it wrote and nobody touched, +// and rewrites the manifest only when its text changed. `fixtures/agent-context-conformance/` +// and `fixtures/agent-pages-pointer/` pin the output across the ports. + +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using MetaObjects.AgentContext; + +namespace MetaObjects.Cli; + +/// The shipped tree cannot serve the request (unknown stack, unknown schema, bad flag). +public sealed class ShippedContextException(string message) : Exception(message); + +/// `dotnet meta agent-docs`: the shipped agent files for a stack, written natively. +public static class AgentDocsCommand +{ + /// Server language of a project that names none and has no earlier manifest. + public const string DefaultServer = "csharp"; + + /// The manifest shape this port understands. + public const int ShippedSchema = 2; + + /// Canonical order of server languages inside a stack id. + public static readonly string[] ServerLangs = ["typescript", "java", "kotlin", "csharp", "python", "rust"]; + + /// Canonical order of client frameworks inside a stack id. + public static readonly string[] ClientFrameworks = ["react", "tanstack", "angular"]; + + /// The ref a prerelease or an unresolvable version keeps. + public const string DocsDefaultRef = "main"; + + /// The id suffix of a stack shipped with the reference migration helper's steps. + public const string MigrationSuffix = "-migrate"; + + /// The always-on file, relative to the project root. + public const string AlwaysOnPath = ".metaobjects/AGENTS.md"; + + /// The heading the agent-pages section is inserted above. + public const string AgentPagesAnchor = "\n## Rules\n"; + + private const string RootImportLine = "@.metaobjects/AGENTS.md"; + private const string RootImportBlock = + "Read `.metaobjects/AGENTS.md` before changing this project's metadata, generated code " + + "or schema.\n" + RootImportLine + "\n"; + private const string NewRootBody = "# Project memory\n\n" + RootImportBlock; + private const string ResourcePrefix = "agent-context-shipped/"; + + private static readonly Dictionary ServerAliases = new() + { + ["node"] = "typescript", ["nodejs"] = "typescript", ["ts"] = "typescript", + ["c#"] = "csharp", ["dotnet"] = "csharp", ["py"] = "python", ["rs"] = "rust", + }; + + private static readonly Dictionary ClientAliases = new() + { + ["reactjs"] = "react", ["react-query"] = "tanstack", + }; + + private static readonly Regex ReleaseVersion = new(@"^\d+\.\d+\.\d+$", RegexOptions.CultureInvariant); + + /// Each agent page, by the path it ends with, and when to read it. In list order. + public static readonly (string Suffix, string When)[] AgentPages = + [ + ("agent/schema.md", "before you touch persistence: tables, columns, keys and views"), + ("agent/ui.md", "before you touch a form or a grid"), + ("agent/requirements.md", "before you add or change a capability"), + ("AGENT-API.md", "before you call or change the generated API"), + ("requirements.toon", "the requirement ledger, in the form a tool reads"), + ]; + + private static readonly UTF8Encoding Utf8 = new(encoderShouldEmitUTF8Identifier: false); + + // ---- the shipped tree ---------------------------------------------------------------- + + /// The embedded tree's manifest, parsed once. + public sealed record ShippedTree(JsonElement Manifest) + { + public string SkillsDir => Manifest.GetProperty("skillsDir").GetString()!; + + public IEnumerable StackIds() => + Manifest.GetProperty("stacks").EnumerateArray().Select(s => s.GetProperty("id").GetString()!); + + public JsonElement? StackEntry(string id) + { + foreach (var s in Manifest.GetProperty("stacks").EnumerateArray()) + if (s.GetProperty("id").GetString() == id) return s; + return null; + } + + /// A stored file under files/, by its name. + public string File(string name) => ReadResource(ResourcePrefix + "files/" + name); + } + + /// Read the embedded tree's manifest; refuse a schema this port does not know. + public static ShippedTree LoadShipped() + { + using var doc = JsonDocument.Parse(ReadResource(ResourcePrefix + "manifest.json")); + var manifest = doc.RootElement.Clone(); + var schema = manifest.TryGetProperty("schema", out var s) && s.ValueKind == JsonValueKind.Number ? s.GetInt32() : -1; + if (schema != ShippedSchema) + throw new ShippedContextException( + $"agent-context: unknown shipped manifest schema {schema} (this dotnet meta understands {ShippedSchema}); upgrade MetaObjects.Cli"); + return new ShippedTree(manifest); + } + + private static string ReadResource(string name) + { + using var stream = typeof(AgentDocsCommand).Assembly.GetManifestResourceStream(name) + ?? throw new ShippedContextException($"agent-context: the embedded shipped tree has no {name}"); + using var ms = new MemoryStream(); + stream.CopyTo(ms); + return Utf8.GetString(ms.ToArray()); + } + + /// v<version> for a release; main for a prerelease, 0.0.0 or non-version text. + public static string DocsRefForVersion(string version) + { + var v = version.Trim(); + return ReleaseVersion.IsMatch(v) && v != "0.0.0" ? "v" + v : DocsDefaultRef; + } + + private static string? Canonical(string raw, string[] valid, Dictionary aliases) + { + var v = raw.Trim().ToLowerInvariant(); + if (valid.Contains(v)) return v; + return aliases.TryGetValue(v, out var a) ? a : null; + } + + /// Canonicalize --server/--client values; refuse one that names nothing known. + public static (List Servers, List Clients) CanonicalStack( + IEnumerable servers, IEnumerable clients) + { + var bad = new List(); + var outServers = new List(); + var outClients = new List(); + foreach (var s in servers) + { + var c = Canonical(s, ServerLangs, ServerAliases); + if (c is null) bad.Add($"--server {s} (known: {string.Join(", ", ServerLangs)})"); + else outServers.Add(c); + } + foreach (var s in clients) + { + var c = Canonical(s, ClientFrameworks, ClientAliases); + if (c is null) bad.Add($"--client {s} (known: {string.Join(", ", ClientFrameworks)})"); + else outClients.Add(c); + } + if (bad.Count > 0) throw new ShippedContextException("unknown stack value: " + string.Join("; ", bad)); + return (outServers, outClients); + } + + /// Server languages then clients, each in canonical order, joined by -; then + /// -migrate when the project chose a meta migrate dialect. + public static string ShippedStackId(IReadOnlyCollection servers, IReadOnlyCollection clients, bool migration = false) + { + var parts = ServerLangs.Where(servers.Contains).Concat(ClientFrameworks.Where(clients.Contains)); + var id = string.Join("-", parts); + return migration ? id + MigrationSuffix : id; + } + + /// The stack's files, in manifest order, with every guide link pinned to . + public static List> Materialize( + ShippedTree tree, IReadOnlyCollection servers, IReadOnlyCollection clients, + string docsRef, bool migration = false) + { + var id = ShippedStackId(servers, clients, migration); + var entry = tree.StackEntry(id) ?? throw new ShippedContextException( + $"no shipped agent files for the stack \"{id}\" (shipped: {string.Join(", ", tree.StackIds())})"); + var prefix = tree.Manifest.GetProperty("docsLinkPrefix").GetString()!; + var src = prefix + tree.Manifest.GetProperty("docsRef").GetString() + "/"; + var dst = prefix + docsRef + "/"; + var outFiles = new List>(); + foreach (var f in entry.GetProperty("files").EnumerateArray()) + { + var text = tree.File(f.GetProperty("file").GetString()!); + outFiles.Add(new(f.GetProperty("path").GetString()!, text.Replace(src, dst, StringComparison.Ordinal))); + } + return outFiles; + } + + // ---- the always-on file's pointer at the agent pages --------------------------------- + + private static int PageIndex(string path) + { + for (int i = 0; i < AgentPages.Length; i++) + { + var suffix = AgentPages[i].Suffix; + if (path == suffix || path.EndsWith("/" + suffix, StringComparison.Ordinal)) return i; + } + return -1; + } + + /// The agent pages the project's last gen wrote, read off the committed + /// .metaobjects/.gen-state/.hashes/, in page order and then by path. + public static List WiredAgentPages(string root) + { + var dir = Path.Combine(root, ".metaobjects", ".gen-state", ".hashes"); + var found = new HashSet(StringComparer.Ordinal); + if (Directory.Exists(dir)) + { + foreach (var file in Directory.GetFiles(dir, "*.json")) + { + try + { + using var doc = JsonDocument.Parse(File.ReadAllText(file)); + if (doc.RootElement.ValueKind != JsonValueKind.Object) continue; + foreach (var p in doc.RootElement.EnumerateObject()) + if (PageIndex(p.Name) >= 0) found.Add(p.Name); + } + catch (Exception e) when (e is IOException or JsonException or UnauthorizedAccessException) + { + // An unreadable hashes file is `gen`'s to report, not this pointer's. + } + } + } + return found.OrderBy(PageIndex).ThenBy(p => p, StringComparer.Ordinal).ToList(); + } + + /// The section for , from ; empty when there are none. + public static string RenderAgentPagesSection(string template, IReadOnlyList pages) + { + if (pages.Count == 0) return ""; + var lines = string.Join("\n", pages.Select(p => $"- `{p}`: {AgentPages[PageIndex(p)].When}.")); + return template.Replace("{{pageList}}", lines, StringComparison.Ordinal); + } + + /// with inserted above its rules. + public static string WithAgentPagesSection(string alwaysOn, string section) + { + if (section.Length == 0) return alwaysOn; + var at = alwaysOn.IndexOf(AgentPagesAnchor, StringComparison.Ordinal); + if (at < 0) + throw new ShippedContextException( + $"agent-context: the always-on file has no \"{AgentPagesAnchor.Trim()}\" heading to place the agent pages above"); + return alwaysOn[..(at + 1)] + section + alwaysOn[(at + 1)..]; + } + + // ---- the sidecar manifest and the write plan ----------------------------------------- + + /// What the scaffolder last wrote: the stack, and a sha256 per path, in order. + public sealed record Manifest( + int Version, + string? GeneratedBy, + List Servers, + List Clients, + List> Files, + string? SkillsDir = null) + { + public string? HashOf(string path) + { + foreach (var kv in Files) if (kv.Key == path) return kv.Value; + return null; + } + + /// The manifest's text, as every port writes it (two-space JSON, trailing newline). + public string ToJson() + { + var sb = new StringBuilder(); + sb.Append("{\n \"version\": ").Append(Version); + if (GeneratedBy is not null) sb.Append(",\n \"generatedBy\": ").Append(Quote(GeneratedBy)); + sb.Append(",\n \"servers\": ").Append(Array(Servers)); + sb.Append(",\n \"clients\": ").Append(Array(Clients)); + sb.Append(",\n \"files\": "); + if (Files.Count == 0) sb.Append("{}"); + else + { + sb.Append("{\n"); + sb.Append(string.Join(",\n", Files.Select(kv => $" {Quote(kv.Key)}: {Quote(kv.Value)}"))); + sb.Append("\n }"); + } + if (SkillsDir is not null) sb.Append(",\n \"skillsDir\": ").Append(Quote(SkillsDir)); + sb.Append("\n}\n"); + return sb.ToString(); + } + + private static string Array(List items) => + items.Count == 0 ? "[]" : "[\n" + string.Join(",\n", items.Select(i => " " + Quote(i))) + "\n ]"; + + public static Manifest? Parse(string text) + { + JsonDocument doc; + try { doc = JsonDocument.Parse(text); } + catch (JsonException) { return null; } + using (doc) + { + var r = doc.RootElement; + if (r.ValueKind != JsonValueKind.Object) return null; + var files = new List>(); + if (r.TryGetProperty("files", out var f) && f.ValueKind == JsonValueKind.Object) + foreach (var p in f.EnumerateObject()) files.Add(new(p.Name, Str(p.Value))); + return new Manifest( + r.TryGetProperty("version", out var v) && v.ValueKind == JsonValueKind.Number ? v.GetInt32() : 1, + r.TryGetProperty("generatedBy", out var g) && g.ValueKind != JsonValueKind.Null ? Str(g) : null, + StrList(r, "servers"), + StrList(r, "clients"), + files, + r.TryGetProperty("skillsDir", out var s) && s.ValueKind != JsonValueKind.Null ? Str(s) : null); + } + } + + private static string Str(JsonElement e) => e.ValueKind == JsonValueKind.String ? e.GetString()! : e.GetRawText(); + + private static List StrList(JsonElement r, string name) => + r.TryGetProperty(name, out var a) && a.ValueKind == JsonValueKind.Array + ? a.EnumerateArray().Select(Str).ToList() + : []; + } + + /// A JSON string literal, escaped as Python's json.dumps(ensure_ascii=False) escapes it. + internal static string Quote(string s) + { + var sb = new StringBuilder(s.Length + 2).Append('"'); + foreach (var c in s) + { + switch (c) + { + case '"': sb.Append("\\\""); break; + case '\\': sb.Append("\\\\"); break; + case '\n': sb.Append("\\n"); break; + case '\r': sb.Append("\\r"); break; + case '\t': sb.Append("\\t"); break; + case '\b': sb.Append("\\b"); break; + case '\f': sb.Append("\\f"); break; + default: + if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4")); + else sb.Append(c); + break; + } + } + return sb.Append('"').ToString(); + } + + /// sha256 hex of a file's text, as every scaffolder records it. + public static string HashContents(string text) => + Convert.ToHexString(SHA256.HashData(Utf8.GetBytes(text))).ToLowerInvariant(); + + /// What a (re-)scaffold does, decided before anything is written. + public sealed class ScaffoldDecision + { + public List> Writes { get; } = []; + public List> Conflicts { get; } = []; + public List Prunes { get; } = []; + public List Removed { get; } = []; + public Manifest Manifest { get; set; } = null!; + } + + /// Decide what to write. A file is safe to overwrite iff it is absent, or its + /// on-disk hash still equals the hash the prior manifest recorded. The manifest records + /// what was WRITTEN: a declined path keeps its prior hash. + public static ScaffoldDecision PlanScaffold( + List> assembled, Manifest? prior, Func readCurrent, + string generatedBy, List servers, List clients) + { + var d = new ScaffoldDecision(); + var files = new List>(); + foreach (var (path, contents) in assembled) + { + var current = readCurrent(path); + if (current is null) + { + files.Add(new(path, HashContents(contents))); + d.Writes.Add(new(path, contents)); + continue; + } + if (current == contents) + { + files.Add(new(path, HashContents(contents))); + continue; + } + var priorHash = prior?.HashOf(path); + if (priorHash is not null && HashContents(current) == priorHash) + { + files.Add(new(path, HashContents(contents))); + d.Writes.Add(new(path, contents)); + } + else + { + if (priorHash is not null) files.Add(new(path, priorHash)); + d.Conflicts.Add(new(path, contents)); + } + } + var assembledPaths = assembled.Select(kv => kv.Key).ToHashSet(StringComparer.Ordinal); + foreach (var (path, hash) in prior?.Files ?? []) + { + if (assembledPaths.Contains(path)) continue; + var current = readCurrent(path); + if (current is null) continue; + if (HashContents(current) == hash) d.Prunes.Add(path); + else d.Removed.Add(path); + } + d.Manifest = new Manifest(1, generatedBy, servers, clients, files); + return d; + } + + // ---- the command --------------------------------------------------------------------- + + private static string? Read(string root, string rel) + { + var p = Path.Combine(root, rel); + return File.Exists(p) ? Utf8.GetString(File.ReadAllBytes(p)) : null; + } + + private static void Write(string root, string rel, string text) + { + var p = Path.Combine(root, rel); + Directory.CreateDirectory(Path.GetDirectoryName(p)!); + File.WriteAllBytes(p, Utf8.GetBytes(text)); + } + + /// Whether the project chose a meta migrate dialect: migrate.dialect is + /// set in its .metaobjects/config.json. A config that does not parse is refused, so a + /// typo never reads as "no dialect" and quietly drops the migrate steps. + public static bool ChoseMigrateDialect(string root) + { + var path = Path.Combine(root, ".metaobjects", "config.json"); + if (!File.Exists(path)) return false; + try + { + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + return doc.RootElement.ValueKind == JsonValueKind.Object + && doc.RootElement.TryGetProperty("migrate", out var m) + && m.ValueKind == JsonValueKind.Object + && m.TryGetProperty("dialect", out var dialect) + && dialect.ValueKind != JsonValueKind.Null; + } + catch (JsonException e) + { + throw new ShippedContextException($"{path}: not valid JSON ({e.Message})"); + } + } + + private static void WireRoot(string root, List created, List notes, bool refresh) + { + var claude = Path.Combine(root, "CLAUDE.md"); + var agents = Path.Combine(root, "AGENTS.md"); + if (!File.Exists(claude) && !File.Exists(agents)) + { + foreach (var name in new[] { "AGENTS.md", "CLAUDE.md" }) + { + Write(root, name, NewRootBody); + created.Add($"{name} (created with MetaObjects @import)"); + } + return; + } + if (File.Exists(claude) && !File.Exists(agents)) + { + if (!refresh) + { + Write(root, "AGENTS.md", NewRootBody); + created.Add("AGENTS.md (created with MetaObjects @import)"); + } + else + { + notes.Add("no root AGENTS.md: assistants other than Claude Code will not load " + + ".metaobjects/AGENTS.md; add a root AGENTS.md containing @.metaobjects/AGENTS.md"); + } + } + foreach (var name in new[] { "CLAUDE.md", "AGENTS.md" }) + { + if (!File.Exists(Path.Combine(root, name))) continue; + var body = Read(root, name) ?? ""; + if (body.Contains(RootImportLine, StringComparison.Ordinal)) continue; + Write(root, name, body.TrimEnd('\n') + "\n\n" + RootImportBlock); + notes.Add($"wired {RootImportLine} into {name} so the MetaObjects context loads"); + } + } + + /// Write the stack's files under ; return the created paths and notes. + /// An unknown stack value or stack. + public static (List Created, List Notes) Run( + IEnumerable servers, IEnumerable clients, string outDir, + bool wireRoot = true, string? version = null) + { + version ??= EjectCommand.ToolVersion(); + var (srv, cli) = CanonicalStack(servers, clients); + var prior = Read(outDir, AgentContextScaffold.ManifestPath) is { } priorText ? Manifest.Parse(priorText) : null; + if (srv.Count == 0) + { + // No --server: reuse the recorded stack, so a refresh keeps it without repeating it. + if (cli.Count == 0 && prior is not null) cli = [.. prior.Clients]; + srv = prior is not null && prior.Servers.Count > 0 ? [.. prior.Servers] : [DefaultServer]; + } + var tree = LoadShipped(); + var shippedSkills = tree.SkillsDir; + if (prior?.SkillsDir is { } own && own != shippedSkills) + throw new ShippedContextException( + $"agent-context: this project keeps its skills under '{own}' (meta init --skills-dir); " + + $"dotnet meta agent-docs writes only '{shippedSkills}'. Refresh with: npx meta agent-docs --skills-dir {own}"); + var migration = ChoseMigrateDialect(outDir); + var assembled = Materialize(tree, srv, cli, DocsRefForVersion(version), migration); + var alwaysOn = assembled.FindIndex(kv => kv.Key == AlwaysOnPath); + if (alwaysOn >= 0) + { + // The always-on file points at the agent pages only when the project's last `gen` wrote one. + var template = tree.File(tree.Manifest.GetProperty("agentPagesTemplate").GetString()!); + var section = RenderAgentPagesSection(template, WiredAgentPages(outDir)); + assembled[alwaysOn] = new(AlwaysOnPath, WithAgentPagesSection(assembled[alwaysOn].Value, section)); + } + var decision = PlanScaffold(assembled, prior, p => Read(outDir, p), version, srv, cli); + var created = new List(); + var notes = new List(); + foreach (var (path, text) in decision.Writes) + { + Write(outDir, path, text); + created.Add(path); + } + foreach (var (path, text) in decision.Conflicts) + { + Write(outDir, path + ".new", text); + created.Add(path + ".new"); + notes.Add($"{path} appears hand-edited; refreshed version written to {path}.new"); + } + var manifestText = decision.Manifest.ToJson(); + if (Read(outDir, AgentContextScaffold.ManifestPath) != manifestText) + { + Write(outDir, AgentContextScaffold.ManifestPath, manifestText); + created.Add(AgentContextScaffold.ManifestPath); + } + var skills = Path.GetFullPath(Path.Combine(outDir, shippedSkills)); + var top = Path.GetFullPath(outDir); + foreach (var orphan in decision.Prunes) + { + var full = Path.GetFullPath(Path.Combine(outDir, orphan)); + File.Delete(full); + // Drop a skill directory this just emptied, never the skills directory itself. + var parent = Path.GetDirectoryName(full); + while (parent is not null && parent != skills && parent != top + && Directory.Exists(parent) && !Directory.EnumerateFileSystemEntries(parent).Any()) + { + Directory.Delete(parent); + parent = Path.GetDirectoryName(parent); + } + } + foreach (var orphan in decision.Removed) + notes.Add($"{orphan} is no longer part of this stack but appears hand-edited, so it was " + + "kept; delete it yourself once you have salvaged anything you want from it."); + if (wireRoot) WireRoot(outDir, created, notes, refresh: prior is not null); + return (created, notes); + } + + /// The usage line `dotnet meta agent-docs --help` prints. + public const string Usage = + "usage: dotnet meta agent-docs [--server ]... [--client ]... [--out ] [--no-wire-root]\n" + + " write .metaobjects/AGENTS.md and the metaobjects-* skills for this stack (default --server csharp);\n" + + " needs no Node. --server: typescript|java|kotlin|csharp|python|rust (repeatable);\n" + + " --client: react|tanstack|angular (repeatable); with neither, the stack the last run recorded.\n" + + " --out: the project directory (default: the current one); --no-wire-root: do not add the\n" + + " @import to the root AGENTS.md / CLAUDE.md"; + + /// The command line: parse, run, report. 0 written, 2 refused. + public static int Execute(string[] args, TextWriter stdout, TextWriter stderr) + { + var servers = new List(); + var clients = new List(); + string? outDir = null; + var wireRoot = true; + for (int i = 0; i < args.Length; i++) + { + var a = args[i]; + if (a is "--server" or "--client" or "--out") + { + if (i + 1 >= args.Length || args[i + 1].StartsWith("--", StringComparison.Ordinal)) + { + stderr.WriteLine($"dotnet meta agent-docs: {a} needs a value\n{Usage}"); + return 2; + } + var value = args[++i]; + if (a == "--server") servers.Add(value); + else if (a == "--client") clients.Add(value); + else outDir = value; + } + else if (a == "--no-wire-root") wireRoot = false; + else + { + stderr.WriteLine($"unknown flag {a} for `dotnet meta agent-docs`. Valid flags: --client, --no-wire-root, --out, --server (also accepted everywhere: --help)"); + return 2; + } + } + try + { + var (created, notes) = Run(servers, clients, Path.GetFullPath(outDir ?? Directory.GetCurrentDirectory()), wireRoot); + stdout.WriteLine($"Wrote the MetaObjects agent context ({created.Count} files changed): " + + ".metaobjects/AGENTS.md + the metaobjects-* skills."); + foreach (var n in notes) stdout.WriteLine($" {n}"); + stdout.WriteLine("Re-run agent-docs to update; --no-wire-root skips the root AGENTS.md/CLAUDE.md @import."); + return 0; + } + catch (ShippedContextException e) + { + stderr.WriteLine($"dotnet meta agent-docs: {e.Message}"); + return 2; + } + } +} diff --git a/server/csharp/MetaObjects.Cli/MetaObjects.Cli.csproj b/server/csharp/MetaObjects.Cli/MetaObjects.Cli.csproj index 0a367f7f06..8bcc8bdeba 100644 --- a/server/csharp/MetaObjects.Cli/MetaObjects.Cli.csproj +++ b/server/csharp/MetaObjects.Cli/MetaObjects.Cli.csproj @@ -23,6 +23,13 @@ + + + + + + diff --git a/server/csharp/MetaObjects.Cli/Program.cs b/server/csharp/MetaObjects.Cli/Program.cs index 83c49575cd..6b9d2dc8b3 100644 --- a/server/csharp/MetaObjects.Cli/Program.cs +++ b/server/csharp/MetaObjects.Cli/Program.cs @@ -71,7 +71,9 @@ " and `gen --list` show identical copies\n" + " fmt [] [--check] rewrite metadata into canonical form (#304);\n" + " --check lists drift, exits non-zero, changes nothing\n" + - " agent-docs see `npx meta agent-docs`\n" + + " agent-docs [--server ]... [--client ]... [--out ] [--no-wire-root]\n" + + " write .metaobjects/AGENTS.md and the metaobjects-*\n" + + " skills for this stack (default --server csharp); no Node\n" + " --version, -v, -V print the version\n" + " --help that command's usage"); return helpRequested ? 0 : 2; @@ -93,7 +95,7 @@ "init" => RunInit(args[1..]), "fmt" => RunFmt(args[1..]), "eject" => RunEject(args[1..]), - "agent-docs" => AgentDocsRedirect(), + "agent-docs" => AgentDocsCommand.Execute(args[1..], Console.Out, Console.Error), _ => Unknown(args[0]), }; @@ -367,13 +369,6 @@ static int Unknown(string cmd) return 2; } -static int AgentDocsRedirect() -{ - Console.Error.WriteLine("agent-context scaffolding moved to the meta CLI — run: " - + "npx meta agent-docs --server csharp [--client ] [--out ]"); - return 1; -} - // `dotnet meta verify` — ADR-0021 D2 explicit subverbs. Parses --templates / // --codegen / --db, dispatches each requested gate via VerifyCommand.RunSubverbs // (pure logic), and aggregates the exit code (max; non-zero on any drift). A bare @@ -772,6 +767,7 @@ partial class Program ["verify"] = "usage: dotnet meta verify [--templates [--prompts ]] [--codegen --out [--namespace ] [--generators ] [--entities ] [--template-root ]] [--deps] [--db] [--lax] [--no-field-lint] [--no-overlay-lint] [--no-name-lint] [--no-deprecation-lint] [--require-implementers] [--full]\n" + " --full: render and compare even when a local run could answer from the stored key (CI always renders)", ["fmt"] = "usage: dotnet meta fmt [] [--check]", + ["agent-docs"] = AgentDocsCommand.Usage, ["eject"] = "usage: dotnet meta eject ... [--force] [--root ]\n" + " dotnet meta eject --undo [...] [--force] [--root ]\n" + " --undo drops owned copies identical to the shipped generators (every one, or the names given);\n" + diff --git a/server/csharp/MetaObjects/AgentContext/AgentContextScaffold.cs b/server/csharp/MetaObjects/AgentContext/AgentContextScaffold.cs index 8044917f02..8f2096f55b 100644 --- a/server/csharp/MetaObjects/AgentContext/AgentContextScaffold.cs +++ b/server/csharp/MetaObjects/AgentContext/AgentContextScaffold.cs @@ -1,9 +1,9 @@ // AgentContextScaffold — sidecar manifest descriptor + staleness decision. // -// The scaffold-WRITE path (Plan/assemble/write) has moved to the Node meta CLI -// (ADR-0015). This file retains only the manifest shape and the pure staleness -// decision so the live `gen`/`verify` commands can nudge a re-scaffold when the -// installed agent context predates the current MetaObjects build. +// The write path is `dotnet meta agent-docs` (MetaObjects.Cli/AgentDocsCommand.cs), which +// copies the shipped agent files with no Node. This file holds the manifest shape and the +// pure staleness decision so the live `gen`/`verify` commands can nudge a re-scaffold when +// the installed agent context predates the current MetaObjects build. namespace MetaObjects.AgentContext; @@ -50,7 +50,7 @@ public sealed record Manifest( var from = manifest.GeneratedBy ?? "an older MetaObjects"; return $"MetaObjects agent context was generated by {from}; you're on {currentVersion}. " + - "Re-run 'npx meta agent-docs' to refresh the agent context and its skills (it keeps the stack and skills directory recorded in .metaobjects/)."; + "Re-run 'dotnet meta agent-docs' to refresh the agent context and its skills (it keeps the stack and skills directory recorded in .metaobjects/)."; } /// without its +build suffix, or null. diff --git a/server/csharp/README.md b/server/csharp/README.md index f089f04c37..66c9772711 100644 --- a/server/csharp/README.md +++ b/server/csharp/README.md @@ -25,15 +25,14 @@ Upgrading from 1.0.x: [upgrading-1.0-to-1.1.md](../../docs/features/migrations/u To scaffold MetaObjects context files (`.metaobjects/AGENTS.md` and the `metaobjects-*` skills) into your project so your AI assistant understands how to author metadata and run codegen, use -the Node `meta` CLI. The skills go to `.claude/skills/` unless you pass `--skills-dir` (for -example `.agents/skills` for assistants that read that directory): +the .NET tool. It needs no Node: the files ship inside it. The skills go to `.claude/skills/` +(a different directory, such as `.agents/skills`, stays with the Node CLI's +`npx meta agent-docs --skills-dir`): ```bash -npx meta agent-docs --server csharp +dotnet meta agent-docs [--client react] [--out ] ``` -(Running `dotnet meta agent-docs` prints this redirect and exits.) - ## Running ```bash diff --git a/server/java/README.md b/server/java/README.md index ee5b15cea5..7cd02df7a1 100644 --- a/server/java/README.md +++ b/server/java/README.md @@ -150,17 +150,16 @@ Releases to Maven Central: see [docs/RELEASING-java.md](../../docs/RELEASING-jav To scaffold MetaObjects context files (`.metaobjects/AGENTS.md` and the `metaobjects-*` skills) into your project so your AI assistant understands how to author metadata and run codegen, use -the Node `meta` CLI. The skills go to `.claude/skills/` unless you pass `--skills-dir` (for -example `.agents/skills` for assistants that read that directory): +the Maven goal. It needs no Node: the files ship inside the plugin. The skills go to +`.claude/skills/` (a different directory, such as `.agents/skills`, stays with the Node CLI's +`npx meta agent-docs --skills-dir`): ```bash -npx meta agent-docs --server java -# or for a Kotlin project: -npx meta agent-docs --server kotlin +mvn metaobjects:agent-docs +# for a Kotlin project, or one with a web client: +mvn metaobjects:agent-docs -Dmetaobjects.servers=kotlin -Dmetaobjects.clients=react ``` -(Running `mvn metaobjects:agent-docs` in the Maven plugin prints this redirect and exits.) - ## License [Apache License 2.0](LICENSE). diff --git a/server/java/maven-plugin/pom.xml b/server/java/maven-plugin/pom.xml index f024ee03cd..d23b46f167 100644 --- a/server/java/maven-plugin/pom.xml +++ b/server/java/maven-plugin/pom.xml @@ -40,6 +40,33 @@ + + + org.apache.maven.plugins + maven-resources-plugin + + + bundle-agent-context-shipped + generate-resources + + copy-resources + + + ${project.build.outputDirectory}/metaobjects/agent-context-shipped + + + ${project.basedir}/../../../agent-context-shipped + + README.md + + false + + + + + + org.apache.maven.plugins maven-site-plugin diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AgentDocsMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AgentDocsMojo.java index ed7527a114..572b72adb0 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AgentDocsMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AgentDocsMojo.java @@ -1,21 +1,27 @@ package com.metaobjects.mojo; +import com.metaobjects.agentcontext.AgentContextScaffold; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; +import java.io.File; import java.util.List; /** - * {@code metaobjects:agent-docs} — scaffolds the MetaObjects Claude Code agent context. + * {@code metaobjects:agent-docs} — writes {@code .metaobjects/AGENTS.md} and the + * {@code metaobjects-*} skills for the project's stack, with no Node on the path. * - *

This goal is no longer implemented in the Maven plugin. Agent-context - * scaffolding has moved to the {@code meta} CLI. Run: *

- *   npx meta agent-docs --server java [--client <fw>] [--out <dir>]
+ *   mvn metaobjects:agent-docs [-Dmetaobjects.servers=java,kotlin] [-Dmetaobjects.clients=react]
+ *       [-Dmetaobjects.outputDirectory=<dir>] [-Dmetaobjects.wireRoot=false]
  * 
+ * + *

With no servers and no clients it reuses the stack the last run recorded, else + * {@code java}. A Kotlin project names {@code kotlin} (or {@code java,kotlin}). See + * {@link AgentDocsWriter} for what a re-run writes, keeps and prunes. */ @Mojo(name = "agent-docs", requiresProject = false, defaultPhase = LifecyclePhase.NONE) public class AgentDocsMojo extends AbstractMojo { @@ -30,13 +36,31 @@ public class AgentDocsMojo extends AbstractMojo { /** Output directory; defaults to the project basedir (or cwd for a project-less run). */ @Parameter(property = "metaobjects.outputDirectory", defaultValue = "${project.basedir}") - private java.io.File outputDirectory; + private File outputDirectory; + + /** Add the {@code @import} to the root {@code AGENTS.md} / {@code CLAUDE.md}. */ + @Parameter(property = "metaobjects.wireRoot", defaultValue = "true") + private boolean wireRoot = true; @Override public void execute() throws MojoExecutionException { - getLog().warn("agent-context scaffolding moved to the meta CLI — run: " - + "npx meta agent-docs --server java [--client ] [--out

]"); - throw new MojoExecutionException( - "agent-docs is no longer implemented in the Maven plugin; use the meta CLI."); + File out = outputDirectory != null ? outputDirectory : new File(System.getProperty("user.dir")); + String version = AgentDocsWriter.npmLineVersion(AgentContextScaffold.installedVersion()); + AgentDocsWriter.Result result; + try { + result = AgentDocsWriter.run( + servers != null ? servers : List.of(), + clients != null ? clients : List.of(), + out.toPath().toAbsolutePath().normalize(), wireRoot, version); + } catch (AgentDocsWriter.ShippedContextException e) { + throw new MojoExecutionException("metaobjects:agent-docs: " + e.getMessage(), e); + } + getLog().info("Wrote the MetaObjects agent context (" + result.created().size() + + " files changed): .metaobjects/AGENTS.md + the metaobjects-* skills."); + for (String note : result.notes()) { + getLog().info(" " + note); + } + getLog().info("Re-run agent-docs to update; -Dmetaobjects.wireRoot=false skips the root " + + "AGENTS.md/CLAUDE.md @import."); } } diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AgentDocsWriter.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AgentDocsWriter.java new file mode 100644 index 0000000000..9da861013e --- /dev/null +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AgentDocsWriter.java @@ -0,0 +1,651 @@ +package com.metaobjects.mojo; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; +import com.metaobjects.agentcontext.AgentContextScaffold; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * {@code metaobjects:agent-docs}: write the shipped agent files into a project, with no Node. + * + *

The JVM side of Python's {@code metaobjects.agent_context.agent_docs} (the reference), + * serving Java and Kotlin alike. The files are the repo-root {@code agent-context-shipped/} + * tree, bundled in this plugin; its README is the contract a port follows: find the stack, pin + * the guide links to the release tag, write each file at its path. Around that, the scaffolder + * rules every port shares: the stack comes from the servers/clients given, else the stack the + * last run recorded in the sidecar manifest, else {@code java}; a re-run writes nothing for a + * file that is already right, parks fresh text at {@code .new} beside a hand-edited file, + * deletes only orphans it wrote and nobody touched, and rewrites the manifest only when its text + * changed. {@code fixtures/agent-context-conformance/} and {@code fixtures/agent-pages-pointer/} + * pin the output across the ports. + */ +public final class AgentDocsWriter { + + /** Server language of a project that names none and has no earlier manifest. */ + public static final String DEFAULT_SERVER = "java"; + /** The manifest shape this port understands. */ + public static final int SHIPPED_SCHEMA = 2; + /** Canonical order of server languages inside a stack id. */ + public static final List SERVER_LANGS = + List.of("typescript", "java", "kotlin", "csharp", "python", "rust"); + /** Canonical order of client frameworks inside a stack id. */ + public static final List CLIENT_FRAMEWORKS = List.of("react", "tanstack", "angular"); + /** The ref a prerelease or an unresolvable version keeps. */ + public static final String DOCS_DEFAULT_REF = "main"; + /** The id suffix of a stack shipped with the reference migration helper's steps. */ + public static final String MIGRATION_SUFFIX = "-migrate"; + /** The always-on file, relative to the project root. */ + public static final String ALWAYS_ON_PATH = ".metaobjects/AGENTS.md"; + /** The heading the agent-pages section is inserted above. */ + public static final String AGENT_PAGES_ANCHOR = "\n## Rules\n"; + + private static final String ROOT_IMPORT_LINE = "@.metaobjects/AGENTS.md"; + private static final String ROOT_IMPORT_BLOCK = + "Read `.metaobjects/AGENTS.md` before changing this project's metadata, generated code " + + "or schema.\n" + ROOT_IMPORT_LINE + "\n"; + private static final String NEW_ROOT_BODY = "# Project memory\n\n" + ROOT_IMPORT_BLOCK; + private static final String RESOURCE_ROOT = "/metaobjects/agent-context-shipped/"; + + private static final Map SERVER_ALIASES = Map.of( + "node", "typescript", "nodejs", "typescript", "ts", "typescript", + "c#", "csharp", "dotnet", "csharp", "py", "python", "rs", "rust"); + private static final Map CLIENT_ALIASES = Map.of( + "reactjs", "react", "react-query", "tanstack"); + private static final Pattern RELEASE_VERSION = Pattern.compile("^\\d+\\.\\d+\\.\\d+$"); + private static final Pattern LEADING_MAJOR = Pattern.compile("^(\\d+)(\\..*)$"); + /** Maven Central carries the npm major plus 7 (8.3.0 is the npm line's 1.3.0). */ + private static final int MAVEN_MAJOR_OFFSET = 7; + + /** Each agent page, by the path it ends with, and when to read it. In list order. */ + public static final List AGENT_PAGES = List.of( + new String[] {"agent/schema.md", "before you touch persistence: tables, columns, keys and views"}, + new String[] {"agent/ui.md", "before you touch a form or a grid"}, + new String[] {"agent/requirements.md", "before you add or change a capability"}, + new String[] {"AGENT-API.md", "before you call or change the generated API"}, + new String[] {"requirements.toon", "the requirement ledger, in the form a tool reads"}); + + private AgentDocsWriter() { + } + + /** The shipped tree cannot serve the request (unknown stack, unknown schema, bad flag). */ + public static final class ShippedContextException extends RuntimeException { + public ShippedContextException(String message) { + super(message); + } + } + + /** The created paths and the notes a run reports. */ + public record Result(List created, List notes) { + } + + // ---- the shipped tree ---------------------------------------------------------------- + + /** The bundled tree's manifest. */ + public record ShippedTree(JsonObject manifest) { + public String skillsDir() { + return manifest.get("skillsDir").getAsString(); + } + + public List stackIds() { + List ids = new ArrayList<>(); + for (JsonElement s : manifest.getAsJsonArray("stacks")) { + ids.add(s.getAsJsonObject().get("id").getAsString()); + } + return ids; + } + + public JsonObject stackEntry(String id) { + for (JsonElement s : manifest.getAsJsonArray("stacks")) { + if (s.getAsJsonObject().get("id").getAsString().equals(id)) { + return s.getAsJsonObject(); + } + } + return null; + } + + /** A stored file under {@code files/}, by its name. */ + public String file(String name) { + return readResource("files/" + name); + } + } + + /** Read the bundled tree's manifest; refuse a schema this port does not know. */ + public static ShippedTree loadShipped() { + JsonObject manifest = JsonParser.parseString(readResource("manifest.json")).getAsJsonObject(); + JsonElement schema = manifest.get("schema"); + if (schema == null || !schema.isJsonPrimitive() || schema.getAsInt() != SHIPPED_SCHEMA) { + throw new ShippedContextException("agent-context: unknown shipped manifest schema " + schema + + " (this metaobjects-maven-plugin understands " + SHIPPED_SCHEMA + + "); upgrade the plugin"); + } + return new ShippedTree(manifest); + } + + private static String readResource(String rel) { + try (InputStream in = AgentDocsWriter.class.getResourceAsStream(RESOURCE_ROOT + rel)) { + if (in == null) { + throw new ShippedContextException("agent-context: the bundled shipped tree has no " + rel); + } + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** {@code v} for a release; {@code main} for a prerelease, {@code 0.0.0} or non-version text. */ + public static String docsRefForVersion(String version) { + String v = version.trim(); + return RELEASE_VERSION.matcher(v).matches() && !v.equals("0.0.0") ? "v" + v : DOCS_DEFAULT_REF; + } + + /** + * The npm-line spelling of a Maven version: its major less 7, so {@code 8.3.0} is + * {@code 1.3.0} and {@code 8.3.0-rc.2} is {@code 1.3.0-rc.2}. The manifest is stamped and the + * guide links are pinned on that line, the one every port's release tag names. A version + * below the offset (the {@code 0.0.0} sentinel, a local build) is returned unchanged. + */ + public static String npmLineVersion(String mavenVersion) { + Matcher m = LEADING_MAJOR.matcher(mavenVersion.trim()); + if (!m.matches()) { + return mavenVersion; + } + int major = Integer.parseInt(m.group(1)); + return major >= MAVEN_MAJOR_OFFSET ? (major - MAVEN_MAJOR_OFFSET) + m.group(2) : mavenVersion; + } + + private static String canonical(String raw, List valid, Map aliases) { + String v = raw.trim().toLowerCase(Locale.ROOT); + return valid.contains(v) ? v : aliases.get(v); + } + + /** Canonicalize servers/clients; refuse a value that names nothing known. */ + public static List> canonicalStack(List servers, List clients) { + List bad = new ArrayList<>(); + List outServers = new ArrayList<>(); + List outClients = new ArrayList<>(); + for (String s : servers) { + String c = canonical(s, SERVER_LANGS, SERVER_ALIASES); + if (c == null) { + bad.add("--server " + s + " (known: " + String.join(", ", SERVER_LANGS) + ")"); + } else { + outServers.add(c); + } + } + for (String s : clients) { + String c = canonical(s, CLIENT_FRAMEWORKS, CLIENT_ALIASES); + if (c == null) { + bad.add("--client " + s + " (known: " + String.join(", ", CLIENT_FRAMEWORKS) + ")"); + } else { + outClients.add(c); + } + } + if (!bad.isEmpty()) { + throw new ShippedContextException("unknown stack value: " + String.join("; ", bad)); + } + return List.of(outServers, outClients); + } + + /** Servers then clients, each in canonical order, joined by {@code -}; then {@code -migrate}. */ + public static String shippedStackId(List servers, List clients, boolean migration) { + String id = Stream.concat( + SERVER_LANGS.stream().filter(servers::contains), + CLIENT_FRAMEWORKS.stream().filter(clients::contains)) + .collect(Collectors.joining("-")); + return migration ? id + MIGRATION_SUFFIX : id; + } + + /** The stack's files, in manifest order, with every guide link pinned to {@code docsRef}. */ + public static LinkedHashMap materialize(ShippedTree tree, List servers, + List clients, String docsRef, boolean migration) { + String id = shippedStackId(servers, clients, migration); + JsonObject entry = tree.stackEntry(id); + if (entry == null) { + throw new ShippedContextException("no shipped agent files for the stack \"" + id + + "\" (shipped: " + String.join(", ", tree.stackIds()) + ")"); + } + String prefix = tree.manifest().get("docsLinkPrefix").getAsString(); + String src = prefix + tree.manifest().get("docsRef").getAsString() + "/"; + String dst = prefix + docsRef + "/"; + LinkedHashMap out = new LinkedHashMap<>(); + for (JsonElement f : entry.getAsJsonArray("files")) { + JsonObject o = f.getAsJsonObject(); + out.put(o.get("path").getAsString(), tree.file(o.get("file").getAsString()).replace(src, dst)); + } + return out; + } + + // ---- the always-on file's pointer at the agent pages --------------------------------- + + private static int pageIndex(String path) { + for (int i = 0; i < AGENT_PAGES.size(); i++) { + String suffix = AGENT_PAGES.get(i)[0]; + if (path.equals(suffix) || path.endsWith("/" + suffix)) { + return i; + } + } + return -1; + } + + /** The agent pages the project's last {@code gen} wrote, in page order and then by path. */ + public static List wiredAgentPages(Path root) { + Path dir = root.resolve(".metaobjects").resolve(".gen-state").resolve(".hashes"); + Set found = new TreeSet<>(); + if (Files.isDirectory(dir)) { + try (DirectoryStream files = Files.newDirectoryStream(dir, "*.json")) { + for (Path file : files) { + try { + JsonElement parsed = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8)); + if (!parsed.isJsonObject()) { + continue; + } + for (String path : parsed.getAsJsonObject().keySet()) { + if (pageIndex(path) >= 0) { + found.add(path); + } + } + } catch (IOException | JsonSyntaxException e) { + // An unreadable hashes file is `gen`'s to report, not this pointer's. + } + } + } catch (IOException e) { + return List.of(); + } + } + return found.stream() + .sorted(Comparator.comparingInt(AgentDocsWriter::pageIndex).thenComparing(Comparator.naturalOrder())) + .toList(); + } + + /** The section for {@code pages}, from {@code template}; empty when there are none. */ + public static String renderAgentPagesSection(String template, List pages) { + if (pages.isEmpty()) { + return ""; + } + String lines = pages.stream() + .map(p -> "- `" + p + "`: " + AGENT_PAGES.get(pageIndex(p))[1] + ".") + .collect(Collectors.joining("\n")); + return template.replace("{{pageList}}", lines); + } + + /** {@code alwaysOn} with {@code section} inserted above its rules. */ + public static String withAgentPagesSection(String alwaysOn, String section) { + if (section.isEmpty()) { + return alwaysOn; + } + int at = alwaysOn.indexOf(AGENT_PAGES_ANCHOR); + if (at < 0) { + throw new ShippedContextException("agent-context: the always-on file has no \"" + + AGENT_PAGES_ANCHOR.strip() + "\" heading to place the agent pages above"); + } + return alwaysOn.substring(0, at + 1) + section + alwaysOn.substring(at + 1); + } + + // ---- the sidecar manifest and the write plan ----------------------------------------- + + /** What the scaffolder last wrote: the stack, and a sha256 per path, in order. */ + public record Manifest(int version, String generatedBy, List servers, List clients, + LinkedHashMap files, String skillsDir) { + + /** The manifest's text, as every port writes it (two-space JSON, trailing newline). */ + public String toJson() { + StringBuilder sb = new StringBuilder("{\n \"version\": ").append(version); + if (generatedBy != null) { + sb.append(",\n \"generatedBy\": ").append(quote(generatedBy)); + } + sb.append(",\n \"servers\": ").append(array(servers)); + sb.append(",\n \"clients\": ").append(array(clients)); + sb.append(",\n \"files\": "); + if (files.isEmpty()) { + sb.append("{}"); + } else { + sb.append("{\n").append(files.entrySet().stream() + .map(e -> " " + quote(e.getKey()) + ": " + quote(e.getValue())) + .collect(Collectors.joining(",\n"))).append("\n }"); + } + if (skillsDir != null) { + sb.append(",\n \"skillsDir\": ").append(quote(skillsDir)); + } + return sb.append("\n}\n").toString(); + } + + private static String array(List items) { + return items.isEmpty() ? "[]" + : "[\n" + items.stream().map(i -> " " + quote(i)).collect(Collectors.joining(",\n")) + "\n ]"; + } + + /** The manifest in {@code text}, or {@code null} when it is not a JSON object. */ + public static Manifest parse(String text) { + JsonElement parsed; + try { + parsed = JsonParser.parseString(text); + } catch (JsonSyntaxException e) { + return null; + } + if (!parsed.isJsonObject()) { + return null; + } + JsonObject r = parsed.getAsJsonObject(); + LinkedHashMap files = new LinkedHashMap<>(); + if (r.has("files") && r.get("files").isJsonObject()) { + for (Map.Entry e : r.getAsJsonObject("files").entrySet()) { + files.put(e.getKey(), str(e.getValue())); + } + } + return new Manifest( + r.has("version") && r.get("version").isJsonPrimitive() ? r.get("version").getAsInt() : 1, + optional(r, "generatedBy"), strList(r, "servers"), strList(r, "clients"), files, + optional(r, "skillsDir")); + } + + private static String optional(JsonObject r, String name) { + return r.has(name) && !r.get(name).isJsonNull() ? str(r.get(name)) : null; + } + + private static String str(JsonElement e) { + return e.isJsonPrimitive() ? e.getAsString() : e.toString(); + } + + private static List strList(JsonObject r, String name) { + List out = new ArrayList<>(); + if (r.has(name) && r.get(name).isJsonArray()) { + for (JsonElement e : (JsonArray) r.get(name)) { + out.add(str(e)); + } + } + return out; + } + } + + /** A JSON string literal, escaped as Python's {@code json.dumps(ensure_ascii=False)} escapes it. */ + static String quote(String s) { + StringBuilder sb = new StringBuilder(s.length() + 2).append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + switch (c) { + case '"' -> sb.append("\\\""); + case '\\' -> sb.append("\\\\"); + case '\n' -> sb.append("\\n"); + case '\r' -> sb.append("\\r"); + case '\t' -> sb.append("\\t"); + case '\b' -> sb.append("\\b"); + case '\f' -> sb.append("\\f"); + default -> { + if (c < 0x20) { + sb.append(String.format("\\u%04x", (int) c)); + } else { + sb.append(c); + } + } + } + } + return sb.append('"').toString(); + } + + /** sha256 hex of a file's text, as every scaffolder records it. */ + public static String hashContents(String text) { + try { + return HexFormat.of().formatHex( + MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + /** What a (re-)scaffold does, decided before anything is written. */ + public static final class ScaffoldDecision { + public final LinkedHashMap writes = new LinkedHashMap<>(); + public final LinkedHashMap conflicts = new LinkedHashMap<>(); + public final List prunes = new ArrayList<>(); + public final List removed = new ArrayList<>(); + public Manifest manifest; + } + + /** + * Decide what to write. A file is safe to overwrite iff it is absent, or its on-disk hash + * still equals the hash the prior manifest recorded. The manifest records what was WRITTEN: + * a declined path keeps its prior hash. + */ + public static ScaffoldDecision planScaffold(Map assembled, Manifest prior, + Function readCurrent, String generatedBy, List servers, List clients) { + ScaffoldDecision d = new ScaffoldDecision(); + LinkedHashMap files = new LinkedHashMap<>(); + for (Map.Entry e : assembled.entrySet()) { + String path = e.getKey(); + String contents = e.getValue(); + String current = readCurrent.apply(path); + if (current == null) { + files.put(path, hashContents(contents)); + d.writes.put(path, contents); + continue; + } + if (current.equals(contents)) { + files.put(path, hashContents(contents)); + continue; + } + String priorHash = prior != null ? prior.files().get(path) : null; + if (priorHash != null && hashContents(current).equals(priorHash)) { + files.put(path, hashContents(contents)); + d.writes.put(path, contents); + } else { + if (priorHash != null) { + files.put(path, priorHash); + } + d.conflicts.put(path, contents); + } + } + if (prior != null) { + for (Map.Entry e : prior.files().entrySet()) { + if (assembled.containsKey(e.getKey())) { + continue; + } + String current = readCurrent.apply(e.getKey()); + if (current == null) { + continue; + } + if (hashContents(current).equals(e.getValue())) { + d.prunes.add(e.getKey()); + } else { + d.removed.add(e.getKey()); + } + } + } + d.manifest = new Manifest(1, generatedBy, servers, clients, files, null); + return d; + } + + // ---- the run ------------------------------------------------------------------------- + + private static String read(Path root, String rel) { + Path p = root.resolve(rel); + if (!Files.isRegularFile(p)) { + return null; + } + try { + return new String(Files.readAllBytes(p), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static void write(Path root, String rel, String text) { + Path p = root.resolve(rel); + try { + Files.createDirectories(p.getParent()); + Files.write(p, text.getBytes(StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * Whether the project chose a {@code meta migrate} dialect: {@code migrate.dialect} is set in + * its {@code .metaobjects/config.json}. A config that does not parse is refused, so a typo + * never reads as "no dialect" and quietly drops the migrate steps. + */ + public static boolean choseMigrateDialect(Path root) { + Path path = root.resolve(".metaobjects").resolve("config.json"); + String text = read(root, ".metaobjects/config.json"); + if (text == null) { + return false; + } + JsonElement parsed; + try { + parsed = JsonParser.parseString(text); + } catch (JsonSyntaxException e) { + throw new ShippedContextException(path + ": not valid JSON (" + e.getMessage() + ")"); + } + if (!parsed.isJsonObject()) { + return false; + } + JsonElement migrate = parsed.getAsJsonObject().get("migrate"); + return migrate != null && migrate.isJsonObject() + && migrate.getAsJsonObject().has("dialect") + && !migrate.getAsJsonObject().get("dialect").isJsonNull(); + } + + private static void wireRoot(Path root, List created, List notes, boolean refresh) { + boolean claude = Files.exists(root.resolve("CLAUDE.md")); + boolean agents = Files.exists(root.resolve("AGENTS.md")); + if (!claude && !agents) { + for (String name : List.of("AGENTS.md", "CLAUDE.md")) { + write(root, name, NEW_ROOT_BODY); + created.add(name + " (created with MetaObjects @import)"); + } + return; + } + if (claude && !agents) { + if (!refresh) { + write(root, "AGENTS.md", NEW_ROOT_BODY); + created.add("AGENTS.md (created with MetaObjects @import)"); + } else { + notes.add("no root AGENTS.md: assistants other than Claude Code will not load " + + ".metaobjects/AGENTS.md; add a root AGENTS.md containing @.metaobjects/AGENTS.md"); + } + } + for (String name : List.of("CLAUDE.md", "AGENTS.md")) { + if (!Files.exists(root.resolve(name))) { + continue; + } + String body = read(root, name); + body = body == null ? "" : body; + if (body.contains(ROOT_IMPORT_LINE)) { + continue; + } + write(root, name, body.replaceAll("\n+$", "") + "\n\n" + ROOT_IMPORT_BLOCK); + notes.add("wired " + ROOT_IMPORT_LINE + " into " + name + " so the MetaObjects context loads"); + } + } + + /** + * Write the stack's files under {@code out}. + * + * @param version the npm-line version to stamp and pin the links to + * @throws ShippedContextException an unknown stack value or stack + */ + public static Result run(List servers, List clients, Path out, boolean wireRoot, + String version) { + List> stack = canonicalStack(servers, clients); + List srv = stack.get(0); + List cli = stack.get(1); + String priorText = read(out, AgentContextScaffold.MANIFEST_PATH); + Manifest prior = priorText != null ? Manifest.parse(priorText) : null; + if (srv.isEmpty()) { + // No server values: reuse the recorded stack, so a refresh keeps it without repeating it. + if (cli.isEmpty() && prior != null) { + cli = new ArrayList<>(prior.clients()); + } + srv = prior != null && !prior.servers().isEmpty() + ? new ArrayList<>(prior.servers()) + : List.of(DEFAULT_SERVER); + } + ShippedTree tree = loadShipped(); + String shippedSkills = tree.skillsDir(); + if (prior != null && prior.skillsDir() != null && !prior.skillsDir().equals(shippedSkills)) { + throw new ShippedContextException("agent-context: this project keeps its skills under '" + + prior.skillsDir() + "' (meta init --skills-dir); mvn metaobjects:agent-docs writes only '" + + shippedSkills + "'. Refresh with: npx meta agent-docs --skills-dir " + prior.skillsDir()); + } + boolean migration = choseMigrateDialect(out); + LinkedHashMap assembled = materialize(tree, srv, cli, docsRefForVersion(version), migration); + if (assembled.containsKey(ALWAYS_ON_PATH)) { + // The always-on file points at the agent pages only when the project's last `gen` wrote one. + String template = tree.file(tree.manifest().get("agentPagesTemplate").getAsString()); + String section = renderAgentPagesSection(template, wiredAgentPages(out)); + assembled.put(ALWAYS_ON_PATH, withAgentPagesSection(assembled.get(ALWAYS_ON_PATH), section)); + } + ScaffoldDecision decision = planScaffold(assembled, prior, p -> read(out, p), version, srv, cli); + List created = new ArrayList<>(); + List notes = new ArrayList<>(); + decision.writes.forEach((path, text) -> { + write(out, path, text); + created.add(path); + }); + decision.conflicts.forEach((path, text) -> { + write(out, path + ".new", text); + created.add(path + ".new"); + notes.add(path + " appears hand-edited; refreshed version written to " + path + ".new"); + }); + String manifestText = decision.manifest.toJson(); + if (!manifestText.equals(read(out, AgentContextScaffold.MANIFEST_PATH))) { + write(out, AgentContextScaffold.MANIFEST_PATH, manifestText); + created.add(AgentContextScaffold.MANIFEST_PATH); + } + Path top = out.toAbsolutePath().normalize(); + Path skills = top.resolve(shippedSkills).normalize(); + for (String orphan : decision.prunes) { + Path full = top.resolve(orphan).normalize(); + try { + Files.deleteIfExists(full); + // Drop a skill directory this just emptied, never the skills directory itself. + Path parent = full.getParent(); + while (parent != null && !parent.equals(skills) && !parent.equals(top) + && Files.isDirectory(parent) && isEmpty(parent)) { + Files.delete(parent); + parent = parent.getParent(); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + for (String orphan : decision.removed) { + notes.add(orphan + " is no longer part of this stack but appears hand-edited, so it was " + + "kept; delete it yourself once you have salvaged anything you want from it."); + } + if (wireRoot) { + wireRoot(out, created, notes, prior != null); + } + return new Result(created, notes); + } + + private static boolean isEmpty(Path dir) throws IOException { + try (Stream entries = Files.list(dir)) { + return entries.findAny().isEmpty(); + } + } +} diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/AgentDocsWriterTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/AgentDocsWriterTest.java new file mode 100644 index 0000000000..4fa4f84d9c --- /dev/null +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/AgentDocsWriterTest.java @@ -0,0 +1,327 @@ +package com.metaobjects.mojo; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.agentcontext.AgentContextScaffold; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/** + * {@code metaobjects:agent-docs} writes the shipped agent files itself, for Java and Kotlin. + * + *

The contract is {@code agent-context-shipped/README.md}; the reference is Python's + * {@code tests/unit/test_agent_docs.py}. Every case of {@code fixtures/agent-context-conformance/} + * (any port can write any stack) and of {@code fixtures/agent-pages-pointer/} is reproduced byte + * for byte. + */ +public class AgentDocsWriterTest { + + private static final String RELEASE = "1.3.0"; + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + private static Path repoRoot() { + Path dir = Path.of("").toAbsolutePath(); + while (dir != null && !Files.isDirectory(dir.resolve("agent-context-shipped"))) { + dir = dir.getParent(); + } + if (dir == null) { + throw new IllegalStateException("repo root not found"); + } + return dir; + } + + private static final Path SHIPPED = repoRoot().resolve("agent-context-shipped"); + private static final Path CORPUS = repoRoot().resolve("fixtures/agent-context-conformance"); + private static final Path POINTER_CASES = repoRoot().resolve("fixtures/agent-pages-pointer/cases"); + + private static TreeMap tree(Path root) throws IOException { + TreeMap out = new TreeMap<>(); + if (!Files.isDirectory(root)) { + return out; + } + try (Stream walk = Files.walk(root)) { + for (Path p : walk.filter(Files::isRegularFile).toList()) { + out.put(root.relativize(p).toString().replace('\\', '/'), Files.readString(p, StandardCharsets.UTF_8)); + } + } + return out; + } + + private static TreeMap withoutManifest(TreeMap t) { + t.remove(AgentContextScaffold.MANIFEST_PATH); + t.remove(".metaobjects/config.json"); + return t; + } + + private static void chooseMigrate(Path root) throws IOException { + Files.createDirectories(root.resolve(".metaobjects")); + Files.writeString(root.resolve(".metaobjects/config.json"), + "{\"schema_version\": 1, \"migrate\": {\"dialect\": \"postgres\"}}\n"); + } + + private static List strings(JsonElement array) { + List out = new ArrayList<>(); + array.getAsJsonArray().forEach(e -> out.add(e.getAsString())); + return out; + } + + private static AgentDocsWriter.Result run(List servers, List clients, Path out, + boolean wireRoot, String version) { + return AgentDocsWriter.run(servers, clients, out, wireRoot, version); + } + + @Test + public void everyCorpusCaseIsReproducedByteForByte() throws IOException { + int cases = 0; + try (Stream dirs = Files.list(CORPUS)) { + for (Path dir : dirs.filter(d -> Files.isRegularFile(d.resolve("stack.json"))).sorted().toList()) { + JsonObject stack = JsonParser.parseString(Files.readString(dir.resolve("stack.json"))).getAsJsonObject(); + Path out = tmp.newFolder(dir.getFileName().toString()).toPath(); + if (stack.has("migrate") && stack.get("migrate").getAsBoolean()) { + chooseMigrate(out); + } + // The goldens are written by a prerelease-or-main build, so their links stay on main. + run(strings(stack.get("servers")), strings(stack.get("clients")), out, false, "1.3.0-rc.1"); + assertEquals(dir.getFileName().toString(), tree(dir.resolve("expected")), withoutManifest(tree(out))); + cases++; + } + } + assertTrue(cases >= 6); + } + + @Test + public void everyJavaAndKotlinStackEqualsTheTreeAfterLinkPinning() throws IOException { + JsonObject manifest = JsonParser.parseString(Files.readString(SHIPPED.resolve("manifest.json"))).getAsJsonObject(); + String prefix = manifest.get("docsLinkPrefix").getAsString(); + String ref = manifest.get("docsRef").getAsString(); + int count = 0; + for (JsonElement e : manifest.getAsJsonArray("stacks")) { + JsonObject s = e.getAsJsonObject(); + List servers = strings(s.get("servers")); + if (!servers.contains("java") && !servers.contains("kotlin")) { + continue; + } + Path out = tmp.newFolder(s.get("id").getAsString()).toPath(); + if (s.get("migration").getAsBoolean()) { + chooseMigrate(out); + } + run(servers, strings(s.get("clients")), out, false, RELEASE); + TreeMap expected = new TreeMap<>(); + for (JsonElement f : s.getAsJsonArray("files")) { + JsonObject o = f.getAsJsonObject(); + expected.put(o.get("path").getAsString(), + Files.readString(SHIPPED.resolve("files").resolve(o.get("file").getAsString())) + .replace(prefix + ref + "/", prefix + "v" + RELEASE + "/")); + } + assertEquals(s.get("id").getAsString(), expected, withoutManifest(tree(out))); + count++; + } + assertEquals(24, count); + } + + @Test + public void theMavenVersionIsWrittenOnTheNpmLine() { + assertEquals("1.3.0", AgentDocsWriter.npmLineVersion("8.3.0")); + assertEquals("1.3.0-rc.2", AgentDocsWriter.npmLineVersion("8.3.0-rc.2")); + assertEquals("0.0.0", AgentDocsWriter.npmLineVersion("0.0.0")); + assertEquals("v1.3.0", AgentDocsWriter.docsRefForVersion(AgentDocsWriter.npmLineVersion("8.3.0"))); + for (String v : List.of("1.3.0rc1", "1.3.0-rc.1", "0.0.0", "dev", "")) { + assertEquals("main", AgentDocsWriter.docsRefForVersion(v)); + } + } + + @Test + public void theNativeStampSatisfiesTheStalenessCheck() throws IOException { + Path out = tmp.newFolder("stamp").toPath(); + run(List.of(), List.of(), out, false, AgentDocsWriter.npmLineVersion("8.3.0")); + String text = Files.readString(out.resolve(AgentContextScaffold.MANIFEST_PATH)); + assertTrue(text.startsWith("{\n \"version\": 1,\n \"generatedBy\": \"1.3.0\",\n \"servers\": [\n" + + " \"java\"\n ],\n \"clients\": [],\n \"files\": {\n")); + AgentContextScaffold.Manifest m = new AgentContextScaffold.Manifest(1, "1.3.0", List.of(), List.of(), Map.of()); + assertNull(AgentContextScaffold.stalenessAcrossVersionLines(m, "8.3.0")); + } + + @Test + public void stackIdOrdersServersThenClientsCanonically() { + assertEquals("java-kotlin-react-tanstack", + AgentDocsWriter.shippedStackId(List.of("kotlin", "java"), List.of("tanstack", "react"), false)); + } + + @Test + public void anUnknownStackIsRefusedNamingTheShippedIds() throws IOException { + Path out = tmp.newFolder("refused").toPath(); + AgentDocsWriter.ShippedContextException e = assertThrows(AgentDocsWriter.ShippedContextException.class, + () -> run(List.of("java"), List.of("tanstack"), out, true, RELEASE)); + assertTrue(e.getMessage().contains("java-tanstack")); + assertTrue(e.getMessage().contains("java-react-tanstack")); + try (Stream l = Files.list(out)) { + assertEquals(0, l.count()); + } + assertTrue(assertThrows(AgentDocsWriter.ShippedContextException.class, + () -> run(List.of("cobol"), List.of(), out, true, RELEASE)).getMessage().contains("--server cobol")); + } + + @Test + public void aClientAloneTakesTheRecordedServerElseJava() throws IOException { + Path fresh = tmp.newFolder("client-fresh").toPath(); + run(List.of(), List.of("react"), fresh, false, RELEASE); + JsonObject m = JsonParser.parseString(Files.readString(fresh.resolve(AgentContextScaffold.MANIFEST_PATH))) + .getAsJsonObject(); + assertEquals(List.of("java"), strings(m.getAsJsonArray("servers"))); + assertEquals(List.of("react"), strings(m.getAsJsonArray("clients"))); + Path recorded = tmp.newFolder("client-recorded").toPath(); + run(List.of("kotlin"), List.of(), recorded, false, RELEASE); + run(List.of(), List.of("react"), recorded, false, RELEASE); + m = JsonParser.parseString(Files.readString(recorded.resolve(AgentContextScaffold.MANIFEST_PATH))) + .getAsJsonObject(); + assertEquals(List.of("kotlin"), strings(m.getAsJsonArray("servers"))); + assertEquals(List.of("react"), strings(m.getAsJsonArray("clients"))); + } + + @Test + public void aRerunWritesNothingAndKeepsTheRecordedStack() throws IOException { + Path out = tmp.newFolder("rerun").toPath(); + run(List.of("kotlin"), List.of("react"), out, true, RELEASE); + FileTime stamp = FileTime.fromMillis(1_000_000_000L); + List files; + try (Stream walk = Files.walk(out)) { + files = walk.filter(Files::isRegularFile).toList(); + } + for (Path f : files) { + Files.setLastModifiedTime(f, stamp); + } + AgentDocsWriter.Result r = run(List.of(), List.of(), out, true, RELEASE); + assertEquals(List.of(), r.created()); + assertEquals(List.of(), r.notes()); + for (Path f : files) { + assertEquals(stamp, Files.getLastModifiedTime(f)); + } + assertTrue(Files.readString(out.resolve(AgentContextScaffold.MANIFEST_PATH)).contains("\"kotlin\"")); + } + + @Test + public void aProjectWithItsOwnSkillsDirIsRefusedUntouched() throws IOException { + Path out = tmp.newFolder("skills").toPath(); + run(List.of("java"), List.of(), out, false, RELEASE); + Path m = out.resolve(AgentContextScaffold.MANIFEST_PATH); + String text = Files.readString(m).stripTrailing(); + Files.writeString(m, text.substring(0, text.length() - 1) + ",\n \"skillsDir\": \".agents/skills\"\n}\n"); + TreeMap before = tree(out); + AgentDocsWriter.ShippedContextException e = assertThrows(AgentDocsWriter.ShippedContextException.class, + () -> run(List.of(), List.of(), out, false, RELEASE)); + assertTrue(e.getMessage().contains("npx meta agent-docs --skills-dir .agents/skills")); + assertEquals(before, tree(out)); + } + + @Test + public void aHandEditedFileIsKeptAndTheFreshTextGoesBesideIt() throws IOException { + Path out = tmp.newFolder("edited").toPath(); + run(List.of("java"), List.of(), out, false, RELEASE); + Path agents = out.resolve(".metaobjects/AGENTS.md"); + String pristine = Files.readString(agents); + Files.writeString(agents, pristine + "\nmine\n"); + AgentDocsWriter.Result r = run(List.of("java"), List.of(), out, false, RELEASE); + assertTrue(Files.readString(agents).endsWith("mine\n")); + assertEquals(pristine, Files.readString(out.resolve(".metaobjects/AGENTS.md.new"))); + assertEquals(List.of(".metaobjects/AGENTS.md.new"), r.created()); + assertTrue(r.notes().stream().anyMatch(n -> n.contains("hand-edited"))); + Files.writeString(agents, pristine); + assertEquals(List.of(), run(List.of("java"), List.of(), out, false, RELEASE).created()); + } + + @Test + public void aChangedStackPrunesUntouchedOrphansAndKeepsEditedOnes() throws IOException { + Path out = tmp.newFolder("prune").toPath(); + run(List.of("java"), List.of("react", "tanstack"), out, false, RELEASE); + Set alone = AgentDocsWriter.materialize(AgentDocsWriter.loadShipped(), List.of("java"), List.of(), + "main", false).keySet(); + List reactOnly = tree(out).keySet().stream() + .filter(k -> !alone.contains(k) && !k.equals(AgentContextScaffold.MANIFEST_PATH)).sorted().toList(); + assertTrue(reactOnly.size() > 1); + String edited = reactOnly.get(0); + Files.writeString(out.resolve(edited), "mine"); + run(List.of(), List.of(), out, false, RELEASE); + for (String p : reactOnly) { + assertTrue(Files.exists(out.resolve(p))); + } + AgentDocsWriter.Result r = run(List.of("java"), List.of(), out, false, RELEASE); + assertEquals("mine", Files.readString(out.resolve(edited))); + assertTrue(r.notes().stream().anyMatch(n -> n.contains(edited) && n.contains("hand-edited"))); + for (String p : reactOnly) { + if (!p.equals(edited)) { + assertFalse(p, Files.exists(out.resolve(p))); + } + } + } + + @Test + public void rootFilesAreWiredOnce() throws IOException { + Path out = tmp.getRoot().toPath().resolve("proj"); + run(List.of("java"), List.of(), out, true, RELEASE); + run(List.of("java"), List.of(), out, true, RELEASE); + for (String name : List.of("AGENTS.md", "CLAUDE.md")) { + String body = Files.readString(out.resolve(name)); + assertEquals(1, body.split("@\\.metaobjects/AGENTS\\.md", -1).length - 1); + } + } + + // ---- the always-on pointer at the agent pages (fixtures/agent-pages-pointer/) -------- + + @Test + public void agentPagesSectionMatchesTheCorpus() throws IOException { + AgentDocsWriter.ShippedTree t = AgentDocsWriter.loadShipped(); + String template = t.file(t.manifest().get("agentPagesTemplate").getAsString()); + int cases = 0; + try (Stream dirs = Files.list(POINTER_CASES)) { + for (Path dir : dirs.filter(Files::isDirectory).sorted().toList()) { + assertEquals(dir.getFileName().toString(), Files.readString(dir.resolve("expected-section.md")), + AgentDocsWriter.renderAgentPagesSection(template, AgentDocsWriter.wiredAgentPages(dir))); + cases++; + } + } + assertEquals(3, cases); + } + + @Test + public void thePointerLandsAboveTheRules() throws IOException { + Path plain = tmp.newFolder("plain").toPath(); + run(List.of("java"), List.of(), plain, true, RELEASE); + Path wired = tmp.newFolder("wired").toPath(); + Path src = POINTER_CASES.resolve("wired/.metaobjects"); + try (Stream walk = Files.walk(src)) { + for (Path p : walk.filter(Files::isRegularFile).toList()) { + Path target = wired.resolve(".metaobjects").resolve(src.relativize(p)); + Files.createDirectories(target.getParent()); + Files.copy(p, target); + } + } + run(List.of("java"), List.of(), wired, true, RELEASE); + String before = Files.readString(plain.resolve(".metaobjects/AGENTS.md")); + String after = Files.readString(wired.resolve(".metaobjects/AGENTS.md")); + String section = Files.readString(POINTER_CASES.resolve("wired/expected-section.md")); + int at = before.indexOf("\n## Rules\n") + 1; + assertEquals(before.substring(0, at) + section + before.substring(at), after); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/agentcontext/AgentContextScaffold.java b/server/java/metadata/src/main/java/com/metaobjects/agentcontext/AgentContextScaffold.java index 52f085d779..34b5f2c8e2 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/agentcontext/AgentContextScaffold.java +++ b/server/java/metadata/src/main/java/com/metaobjects/agentcontext/AgentContextScaffold.java @@ -8,8 +8,8 @@ /** * Sidecar manifest and staleness advisor for the agent-context writer. * - *

Scaffold planning has moved to the {@code meta} CLI - * ({@code npx meta agent-docs --server java}). This class retains the READ-ONLY + *

The write path is the Maven goal {@code metaobjects:agent-docs} + * ({@code AgentDocsWriter} in the maven-plugin, no Node). This class holds the READ-ONLY * staleness advisory ({@link #staleness}/{@link #installedVersion}) called by * {@code AbstractMetaDataMojo.warnIfAgentContextStale()}. */ @@ -73,7 +73,7 @@ public static String staleness(Manifest manifest, String currentVersion) { } String from = manifest.generatedBy() != null ? manifest.generatedBy() : "an older MetaObjects"; return "MetaObjects agent context was generated by " + from + "; you're on " - + currentVersion + ". Run 'npx meta agent-docs' to refresh " + + currentVersion + ". Run 'mvn metaobjects:agent-docs' to refresh " + "the agent context and its skills (it keeps the stack and skills directory recorded in .metaobjects/)."; } @@ -96,9 +96,10 @@ static String releaseCoordinate(String version) { * {@link #staleness} for a consumer whose installed version sits on a DIFFERENT VERSION * LINE from the one that stamped the manifest. * - *

This exists because of a fact peculiar to the JVM. The manifest is always stamped by - * the Node CLI — {@code meta agent-docs} is the canonical scaffolder for every port and the - * others redirect to it — so {@code generatedBy} is always an npm version ({@code 0.24.1}). + *

This exists because of a fact peculiar to the JVM. The manifest is stamped on the npm + * line, by the Node CLI's {@code meta agent-docs} and by the Maven goal + * {@code metaobjects:agent-docs} alike, so {@code generatedBy} is an npm-line version + * ({@code 0.24.1}). * The JVM's {@link #installedVersion()} reads the Maven artifact version ({@code 7.24.1}), * which carries a historical major of {@code 7} by design. Exact equality between those two * is false and always will be, so the plain {@link #staleness} nudged on EVERY build, in @@ -126,8 +127,9 @@ static String releaseCoordinate(String version) { * a context stamped by a STRICTLY NEWER release is not stale and must stay silent. The * second is narrowed but not closed — equal coordinates still assert in-sync, and only * hashing the shipped context could settle it, which this artifact cannot do because the - * JVM ships no agent-context content (npm {@code meta agent-docs} is the canonical - * scaffolder for every port). + * shipped agent files live in the Maven plugin, not here. The plugin's own + * {@code metaobjects:agent-docs} stamps the npm-line version, so its output is in sync by + * this coordinate. * * @param manifest the parsed prior manifest, or {@code null} if none on disk. * @param currentVersion the installed version, on this port's own line. diff --git a/server/java/metadata/src/test/java/com/metaobjects/agentcontext/AgentContextStalenessTest.java b/server/java/metadata/src/test/java/com/metaobjects/agentcontext/AgentContextStalenessTest.java index 269c5fb760..b03d72e734 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/agentcontext/AgentContextStalenessTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/agentcontext/AgentContextStalenessTest.java @@ -21,7 +21,7 @@ *

  • {@code generatedBy} EQUALS current → {@code null} (in sync; exact-equality * on purpose, NOT a semver compare — any drift nudges);
  • *
  • {@code generatedBy} DIFFERS → a one-line nudge naming both versions and the - * Node CLI refresh command {@code npx meta agent-docs --server java};
  • + * refresh goal {@code mvn metaobjects:agent-docs}; *
  • {@code generatedBy} ABSENT (legacy manifest) → a nudge with "an older * MetaObjects" as the from-version.
  • * @@ -102,7 +102,7 @@ public void differingVersionNudgesNamingBoth() { String msg = AgentContextScaffold.staleness(manifest("7.1.0"), "7.2.1"); assertEquals( "MetaObjects agent context was generated by 7.1.0; you're on 7.2.1. " - + "Run 'npx meta agent-docs' to refresh the agent context and its skills (it keeps the stack and skills directory recorded in .metaobjects/).", + + "Run 'mvn metaobjects:agent-docs' to refresh the agent context and its skills (it keeps the stack and skills directory recorded in .metaobjects/).", msg); } @@ -113,7 +113,7 @@ public void absentGeneratedByNudgesAsOlder() { assertTrue("should describe an older MetaObjects", msg.contains("an older MetaObjects")); assertTrue("should name the agent-docs refresh goal", - msg.contains("npx meta agent-docs")); + msg.contains("mvn metaobjects:agent-docs")); // An explicit --server REPLACES the recorded stack (a Java + Kotlin + React // project would lose its other references), so the hint must not pass one. assertFalse("must not pass --server", msg.contains("--server")); diff --git a/server/python/pyproject.toml b/server/python/pyproject.toml index ccf855c062..eaa5d76e03 100644 --- a/server/python/pyproject.toml +++ b/server/python/pyproject.toml @@ -92,7 +92,7 @@ exclude = ["**/KNOWN_GAPS.md"] # The shipped agent files (`metaobjects agent-docs`) are a COMMITTED copy of the repo-root # agent-context-shipped/ tree under src/metaobjects/agent_context/shipped/, so the default # package inclusion above puts them in the wheel and sdist and the command needs no Node. -# scripts/sync-python-agent-context.sh refreshes the copy; a gate and +# scripts/sync-agent-context-shipped.sh refreshes the copy; a gate and # tests/unit/test_agent_docs.py fail when it drifts. No build hook is involved. [tool.pytest.ini_options] diff --git a/server/python/src/metaobjects/agent_context/agent_docs.py b/server/python/src/metaobjects/agent_context/agent_docs.py index 36f9b80752..a8f0c4545c 100644 --- a/server/python/src/metaobjects/agent_context/agent_docs.py +++ b/server/python/src/metaobjects/agent_context/agent_docs.py @@ -110,12 +110,11 @@ def run_agent_docs( version = installed_metaobjects_version() if version is None else version servers, clients = canonical_stack(servers, clients) prior = _prior_manifest(out) - if not servers and not clients: - # No flags: reuse the recorded stack, so a refresh keeps it without repeating them. - if prior is not None and (prior.servers or prior.clients): - servers, clients = list(prior.servers), list(prior.clients) - else: - servers = [DEFAULT_SERVER] + if not servers: + # No --server: reuse the recorded stack, so a refresh keeps it without repeating it. + if not clients and prior is not None: + clients = list(prior.clients) + servers = list(prior.servers) if prior is not None and prior.servers else [DEFAULT_SERVER] tree = load_shipped() shipped_skills = str(tree.manifest["skillsDir"]) if prior is not None and prior.skills_dir not in (None, shipped_skills): diff --git a/server/python/src/metaobjects/agent_context/shipped/files/3708591f7234348e.md b/server/python/src/metaobjects/agent_context/shipped/files/65026d55d54bec5a.md similarity index 97% rename from server/python/src/metaobjects/agent_context/shipped/files/3708591f7234348e.md rename to server/python/src/metaobjects/agent_context/shipped/files/65026d55d54bec5a.md index 086255b208..e72ad3b461 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/3708591f7234348e.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/65026d55d54bec5a.md @@ -119,11 +119,11 @@ class in a `` element — the plugin loads it from the project classp SHAPE is the thing being iterated on or the same output is wanted in another language; prefer code when the logic is gnarly. See `docs/features/codegen-concepts.md` §3. -To re-scaffold the agent-context into a Java project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a Java project, run the Maven goal. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server java [--out ] +mvn metaobjects:agent-docs -Dmetaobjects.servers=java [-Dmetaobjects.clients=] ``` --- diff --git a/agent-context-shipped/files/a3cd9779195de55f.md b/server/python/src/metaobjects/agent_context/shipped/files/75e6eb82781a5f86.md similarity index 98% rename from agent-context-shipped/files/a3cd9779195de55f.md rename to server/python/src/metaobjects/agent_context/shipped/files/75e6eb82781a5f86.md index af3a11584f..93a0714994 100644 --- a/agent-context-shipped/files/a3cd9779195de55f.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/75e6eb82781a5f86.md @@ -329,8 +329,7 @@ consuming fields reference a hand-written/third-party enum, and the C# namespace ## Re-scaffold this context -Agent-context scaffolding is owned by the Node `meta` CLI (ADR-0015). `dotnet meta -agent-docs` only prints a redirect and exits non-zero — it does **not** scaffold. -(Re)scaffold the slim always-on Markdown + these `metaobjects-*` skills with -`npx meta agent-docs --server csharp [--client ] [--out ]`. A C# consumer -needs Node `meta` (npx) for this one scaffold step; codegen + verify stay on `dotnet meta`. +Run `dotnet meta agent-docs` to (re)scaffold the slim always-on Markdown and these +`metaobjects-*` skills into the project. It needs no Node: the files ship inside the +`MetaObjects.Cli` tool. Add `--client ` for a web client and `--out ` for another +project root. diff --git a/agent-context-shipped/files/d6c5d2863183241f.md b/server/python/src/metaobjects/agent_context/shipped/files/91fd9a97e8d84a91.md similarity index 97% rename from agent-context-shipped/files/d6c5d2863183241f.md rename to server/python/src/metaobjects/agent_context/shipped/files/91fd9a97e8d84a91.md index af4334cf67..4ab60b457c 100644 --- a/agent-context-shipped/files/d6c5d2863183241f.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/91fd9a97e8d84a91.md @@ -124,11 +124,11 @@ template when the output SHAPE is the thing being iterated on or the same output wanted in another language; prefer code when the logic is gnarly. See `docs/features/codegen-concepts.md` §3. -To re-scaffold the agent-context into a Kotlin project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a Kotlin project, run the Maven goal. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server kotlin [--out ] +mvn metaobjects:agent-docs -Dmetaobjects.servers=kotlin [-Dmetaobjects.clients=] ``` --- diff --git a/server/python/src/metaobjects/agent_context/shipped/files/a978da9641eb06d6.md b/server/python/src/metaobjects/agent_context/shipped/files/a994506de7729cdb.md similarity index 97% rename from server/python/src/metaobjects/agent_context/shipped/files/a978da9641eb06d6.md rename to server/python/src/metaobjects/agent_context/shipped/files/a994506de7729cdb.md index beee7e9340..2fb4a890e8 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/a978da9641eb06d6.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/a994506de7729cdb.md @@ -120,15 +120,13 @@ hand-written layer the model fully describes, resolves to a generator the projec matters. Recommend it; it is the primary path. Worked template example: `docs/ports/csharp.md`. -To re-scaffold the agent-context into a C# project, use the Node `meta` CLI (the -single agent-docs assembler per ADR-0033): +To re-scaffold the agent-context into a C# project, run the .NET tool. It writes the +files the single assembler built (ADR-0033 Amendment 1), with no Node: ```bash -npx meta agent-docs --server csharp [--out ] +dotnet meta agent-docs [--client ] [--out ] ``` -(`dotnet meta agent-docs` is a non-executing stub — it prints this redirect and exits 1.) - --- ## Version-skew check diff --git a/server/python/src/metaobjects/agent_context/shipped/manifest.json b/server/python/src/metaobjects/agent_context/shipped/manifest.json index ca50485056..817d76a054 100644 --- a/server/python/src/metaobjects/agent_context/shipped/manifest.json +++ b/server/python/src/metaobjects/agent_context/shipped/manifest.json @@ -1813,7 +1813,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2007,7 +2007,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2203,7 +2203,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2403,7 +2403,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2604,7 +2604,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -2809,7 +2809,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3013,7 +3013,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3209,7 +3209,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3403,7 +3403,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3597,7 +3597,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3793,7 +3793,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -3993,7 +3993,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4194,7 +4194,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4399,7 +4399,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4603,7 +4603,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4799,7 +4799,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -4989,7 +4989,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5097,7 +5097,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -5183,7 +5183,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5291,7 +5291,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -5379,7 +5379,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5487,7 +5487,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -5579,7 +5579,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5687,7 +5687,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -5780,7 +5780,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5888,7 +5888,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -5985,7 +5985,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6093,7 +6093,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -6189,7 +6189,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6297,7 +6297,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -6385,7 +6385,7 @@ }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", - "file": "a978da9641eb06d6.md" + "file": "a994506de7729cdb.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -6493,7 +6493,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/csharp.md", - "file": "a3cd9779195de55f.md" + "file": "75e6eb82781a5f86.md" }, { "path": ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md", @@ -9604,11 +9604,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -9819,11 +9819,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10036,11 +10036,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10257,11 +10257,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10479,11 +10479,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10705,11 +10705,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -10930,11 +10930,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", @@ -11147,11 +11147,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/java.md", - "file": "3708591f7234348e.md" + "file": "65026d55d54bec5a.md" }, { "path": ".claude/skills/metaobjects-audit/references/kotlin.md", - "file": "d6c5d2863183241f.md" + "file": "91fd9a97e8d84a91.md" }, { "path": ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md", diff --git a/server/python/tests/unit/test_agent_docs.py b/server/python/tests/unit/test_agent_docs.py index 466def9d21..eee682f8f0 100644 --- a/server/python/tests/unit/test_agent_docs.py +++ b/server/python/tests/unit/test_agent_docs.py @@ -2,8 +2,9 @@ The contract is ``agent-context-shipped/README.md``: the embedded tree, one stack, guide links pinned to the release tag, each file written at its path. The result must equal -what the TypeScript scaffolder writes, which ``fixtures/agent-context-conformance/python`` -holds as the shared golden. +what the TypeScript scaffolder writes, which ``fixtures/agent-context-conformance/`` holds as +the shared goldens. Every port reproduces every case there, whatever its default server, so +the corpus is cross-port conformance and not a per-port snapshot. """ from __future__ import annotations @@ -27,7 +28,8 @@ REPO_ROOT = next(p for p in Path(__file__).resolve().parents if (p / "agent-context-shipped").is_dir()) SHIPPED_ROOT = REPO_ROOT / "agent-context-shipped" EMBEDDED_ROOT = Path(__file__).resolve().parents[2] / "src/metaobjects/agent_context/shipped" -GOLDEN = REPO_ROOT / "fixtures/agent-context-conformance/python" +CORPUS = REPO_ROOT / "fixtures/agent-context-conformance" +CORPUS_CASES = sorted(p.name for p in CORPUS.iterdir() if (p / "stack.json").is_file()) RELEASE = "1.3.0" _TREE = json.loads((SHIPPED_ROOT / "manifest.json").read_text(encoding="utf-8")) @@ -48,7 +50,7 @@ def _without_manifest(tree: dict[str, str]) -> dict[str, str]: def test_embedded_copy_matches_the_repo_root_tree() -> None: root, copy = _tree(SHIPPED_ROOT), _tree(EMBEDDED_ROOT) root.pop("README.md") - assert copy == root, "stale copy: run scripts/sync-python-agent-context.sh" + assert copy == root, "stale copy: run scripts/sync-agent-context-shipped.sh" @pytest.mark.parametrize("stack", PYTHON_STACKS, ids=lambda s: s["id"]) @@ -72,14 +74,25 @@ def test_every_python_stack_equals_the_tree_after_link_pinning(stack: dict[str, assert {k: v for k, v in _without_manifest(_tree(tmp_path)).items() if k != ".metaobjects/config.json"} == expected -def test_the_shared_golden_is_reproduced_byte_for_byte(tmp_path: Path) -> None: - stack = json.loads((GOLDEN / "stack.json").read_text(encoding="utf-8")) - # The golden is written by a prerelease-or-main build, so its links stay on main. +def test_the_corpus_has_every_case() -> None: + assert len(CORPUS_CASES) >= 6 and "python" in CORPUS_CASES + + +@pytest.mark.parametrize("case", CORPUS_CASES) +def test_every_corpus_case_is_reproduced_byte_for_byte(case: str, tmp_path: Path) -> None: + stack = json.loads((CORPUS / case / "stack.json").read_text(encoding="utf-8")) + if stack.get("migrate"): + (tmp_path / ".metaobjects").mkdir() + (tmp_path / ".metaobjects" / "config.json").write_text( + '{"schema_version": 1, "migrate": {"dialect": "postgres"}}\n', encoding="utf-8" + ) + # The goldens are written by a prerelease-or-main build, so their links stay on main. run_agent_docs( servers=stack["servers"], clients=stack["clients"], out=tmp_path, wire_root=False, version="1.3.0-rc.1", ) - assert _without_manifest(_tree(tmp_path)) == _tree(GOLDEN / "expected") + got = {k: v for k, v in _without_manifest(_tree(tmp_path)).items() if k != ".metaobjects/config.json"} + assert got == _tree(CORPUS / case / "expected") def test_a_prerelease_or_unresolvable_version_keeps_main() -> None: @@ -122,6 +135,19 @@ def test_the_default_server_is_python(tmp_path: Path) -> None: assert manifest["generatedBy"] == RELEASE +def test_a_client_alone_takes_the_recorded_server_else_python(tmp_path: Path) -> None: + def stack(out: Path) -> tuple[list[str], list[str]]: + manifest = json.loads((out / AGENT_CONTEXT_MANIFEST_PATH).read_text(encoding="utf-8")) + return manifest["servers"], manifest["clients"] + + fresh, recorded = tmp_path / "fresh", tmp_path / "recorded" + run_agent_docs(servers=[], clients=["react"], out=fresh, wire_root=False, version=RELEASE) + assert stack(fresh) == (["python"], ["react"]) + run_agent_docs(servers=["java"], clients=[], out=recorded, wire_root=False, version=RELEASE) + run_agent_docs(servers=[], clients=["react"], out=recorded, wire_root=False, version=RELEASE) + assert stack(recorded) == (["java"], ["react"]) + + def test_a_rerun_writes_nothing_and_keeps_the_recorded_stack(tmp_path: Path) -> None: run_agent_docs(servers=["python"], clients=["react"], out=tmp_path, version=RELEASE) files = [p for p in tmp_path.rglob("*") if p.is_file()] diff --git a/server/rust/metaobjects-cli/Cargo.toml b/server/rust/metaobjects-cli/Cargo.toml index 60b3998cce..7f071d60a5 100644 --- a/server/rust/metaobjects-cli/Cargo.toml +++ b/server/rust/metaobjects-cli/Cargo.toml @@ -15,6 +15,8 @@ categories = ["development-tools", "development-tools::cargo-plugins", "command- # `metaobjects-cli` and only its binary is called `cargo-meta`; that binary name is what makes # cargo's external-subcommand rule run it for `cargo meta ...`. +build = "build.rs" + [lib] name = "metaobjects_cli" path = "src/lib.rs" diff --git a/server/rust/metaobjects-cli/agent-context-shipped/files/0121296a2cb80b43.md b/server/rust/metaobjects-cli/agent-context-shipped/files/0121296a2cb80b43.md new file mode 100644 index 0000000000..1a30c84b6c --- /dev/null +++ b/server/rust/metaobjects-cli/agent-context-shipped/files/0121296a2cb80b43.md @@ -0,0 +1,86 @@ +# Working with MetaObjects in this project + +> Stack: rust server, no client. +> +> Generated by MetaObjects (refresh: `meta init --refresh-docs`). Put project notes in your +> root `AGENTS.md` or `CLAUDE.md`, not here: this file is regenerated. + +The metadata (`metaobjects/` unless `.metaobjects/config.json` says otherwise) is the source of +truth. Code, schema and migrations are generated from it and are regenerated output. + +## Start here: the whole loop, in order + +### Rust: generate with `cargo meta gen` + +1. **Config.** `metaobjects.config.json` at the project root (written by `cargo meta init`) is the + generator list. Nothing is generated until it is listed: + + ```json + { "generators": ["entity", "client", "commands"] } + ``` + + `entity` writes the model crate, `client` a typed client for the REST API the model implies, + and `commands` command-line commands over that client (`client` needs `entity`; `commands` + needs both). There is no server-side route or ORM generator for Rust yet. `cargo meta gen + --list` is the catalog. +2. **Generate.** `cargo meta gen`. `cargo meta eject ` copies a generator into the repo + to change what it emits. + +### Requirements, when the metadata declares `requirement.*` nodes + +A commit that changes behaviour updates them in the same commit: `@status: live` once a claim +is built (never before), a new node for new behaviour. + +### Before you call it done + +- `cargo meta verify` (the generated crates and the business rules; `--codegen` runs the drift gate alone). + +Commit the metadata, the generated code and `.metaobjects/.gen-state/.hashes/`. + +## Calling the generated REST API + +When the project serves the generated routes (any port): + +- Filter as `?filter[][]=`: `?filter[status][eq]=active`, never + `?status=active` (TypeScript refuses that with 400; the other ports ignore it). Operators: `eq`, `ne`, `isNull` (`true`/`false`), `in` (comma list, at most 100), `like` + (case-sensitive, `%` and `_`), `gt`, `gte`, `lt`, `lte`. Filters AND; only `@filterable` + fields filter. +- `?sort=:asc|desc`, `?limit=N&offset=N`; `withCount=1` returns `{"rows", "total"}`. + Always send `limit`: without it the project's `api.pagination.defaultLimit` applies, or with + none set C# returns every row, the other ports 50; above `maxLimit` is 400. +- `PUT` is the same partial update as `PATCH`. Send only declared fields: an undeclared key is + 400 `unknown_fields` (unless `api.unknownFields` is `drop`). +- Errors are `{"error": ""}`: 400 for validation (`issues` lists each problem) and for + a bad filter or sort (`invalid_filter_field`, `_op`, `_value`, `invalid_sort`, each naming + `field`), 404 `not_found`, 409 for a unique or foreign-key conflict. + +## Rules + +- What the metadata describes is generated, never hand-written (tables, types, validators, + foreign keys, schema, migrations). Hand-write only what it cannot describe, on top. +- Never hand-edit generated output: change the metadata and regenerate. Output wrong for you, or + broken? Fix the generator: eject it and it is yours, no permission needed, nothing to wait on. +- Never spell a table or column name as a string; use the generated table or names constants. +- Wire a generator only for output you will import. +- An LLM prompt in a project that declares `template.prompt` is a declared template + (`metaobjects-prompts`); a grouped total or report view is an `object.report` + (`metaobjects-authoring`). Open the skill before writing either by hand. +- Never invent metadata vocabulary. Search it: `npx meta types `, and + `npx meta types . --detail` for one construct's valid attributes. Vocabulary of + your own says what a thing is and relates to, never a product, a version or a step. +- Metadata nodes are fused-key maps, `{"field.string": {"name": "email"}}`. Attribute names are + unique within a node, and package paths use `::`. + +## Going deeper + +The loop above needs no skill. For less common work load a `metaobjects-*` skill by name, or open +`.claude/skills//SKILL.md` if your assistant does not load skills: `metaobjects-authoring` +(unusual shapes, your own vocabulary, reports, adopting existing code), `metaobjects-codegen` +(owning or writing a generator), `metaobjects-runtime-ui` (REST routes, the web client), `metaobjects-prompts` (LLM +prompts), `metaobjects-verify` (migration edge cases, drift, upgrades), `metaobjects-audit` (an +adoption review). Each names the one reference page to open. + +`meta init --refresh-docs` regenerates this file and the skills, so keep project guidance in +the root `AGENTS.md` or `CLAUDE.md` (or copy a skill to a new name). A refresh never overwrites a +file you edited; it writes `.new` beside it, which you merge into `` and delete. +Never `--force` a refresh over local edits. diff --git a/server/rust/metaobjects-cli/agent-context-shipped/files/01fcc1b45dff7950.md b/server/rust/metaobjects-cli/agent-context-shipped/files/01fcc1b45dff7950.md new file mode 100644 index 0000000000..ca32e33fea --- /dev/null +++ b/server/rust/metaobjects-cli/agent-context-shipped/files/01fcc1b45dff7950.md @@ -0,0 +1,245 @@ +# TypeScript parser-on-receipt + +For every RESPONDING `template.prompt` in your metadata — one declaring +`@responseRef` — the `outputParser()` generator (from +`@metaobjectsdev/codegen-ts/generators`) emits a **typed parser** that validates a +model's reply against that shape. ADR-0052: the tier binds `@responseRef`, never +`@payloadRef` (which types the request the prompt renders outbound), and a +`template.output` gets no parser at all. This is the receive side; codegen emits **no** +provider/LLM-call layer — you compose the call yourself. + +## Contents +- Wire the generator +- What it emits +- The response-format prompt fragment (FR-010) +- The three-step consumer pattern +- Recommended LLM caller (bring-your-own) +- Drift gate +- See which fields a template consumes + +## Wire the generator + +```ts +// metaobjects.config.ts +import { defineConfig } from "@metaobjectsdev/cli"; +// `meta init` wires nothing (ADR-0034 Amendment 2). Each generator is imported from the +// package to run it as shipped. The parser's reply type is the @responseRef value +// object's own interface, which `entity` emits, so `entity` has to be in the run. +// (On a 1.0.x install the first three have no package export: `meta eject entity queries +// barrel` and import them from ./codegen/generators/ instead.) +// +// Any of these can be OWNED instead: `meta eject prompt-render output-parser` copies them +// into ./codegen/generators/ and prints the local import to swap in. Either way the +// render and parse ENGINES they call stay in the package. +import { + entityFile, queriesFile, barrel, promptRender, outputParser, +} from "@metaobjectsdev/codegen-ts/generators"; + +export default defineConfig({ + outDir: "src/generated", + generators: [ + entityFile(), queriesFile(), barrel(), + promptRender(), // render() per template.prompt (the send side) + outputParser(), // parse*/safeParse* per responding template.prompt (the receive side) + ], +}); +``` + +`outputParser({ outDir: "src/generated/outputs", target: "default" })` are the +options. + +## What it emits + +Per responding `template.prompt` (say named `NpcReview`, `@responseRef: +"NpcResponse"`), `meta gen` writes `NpcReview.response.ts` with a Zod schema + a dual +API, named after the TEMPLATE. The strict tier is JSON-only — an `@responseFormat: xml` +reply gets the tolerant `extract` and no `parse`/`safeParse`: + +```ts +import { z } from "zod"; +import type { NpcResponse } from "./NpcResponse.js"; // the value object's own interface (entityFile) + +const NpcReviewSchema = z.object({ + name: z.string(), + level: z.number().int(), + role: z.enum(["tank", "healer", "dps"]), // field.enum → its declared members + notes: z.string().optional(), // not @required → .optional() +}); + +export type NpcReviewValidationError = z.ZodError; + +/** Throws ZodError on bad input. */ +export function parseNpcReview(text: string): NpcResponse { /* ... */ } + +/** Result-style; never throws. */ +export function safeParseNpcReview(text: string): + | { success: true; data: NpcResponse } + | { success: false; error: NpcReviewValidationError } { /* ... */ } +``` + +The dual API mirrors Zod's idiomatic shape: `parse*` throws a `ZodError`, +`safeParse*` returns a discriminated union. Both return the `@responseRef` value +object's OWN interface — the one `entityFile()` declares in `NpcResponse.ts` (ADR-0056) +— so the parser declares no type of its own. `parse*` / `safeParse*` expect the reply to +BE the JSON document; a raw chat reply — `Sure!` followed by a fenced JSON block — fails +them with `invalid JSON: Unexpected token 'S'…`. For a raw reply the same file exports the +tolerant tier: + +```ts +import { extractLenientNpcReviewWithLoader } from "./generated/NpcReview.response.js"; +import { MetaDataLoader } from "@metaobjectsdev/metadata"; +import { orThrow } from "@metaobjectsdev/render"; + +const { root } = await MetaDataLoader.fromDirectory("./metaobjects"); // load once at startup +const result = extractLenientNpcReviewWithLoader(root, reply); // strips prose + fences +result.report; // per field: recovered / defaulted / lost / malformed +const npc = orThrow(result); // opt-in: throws ExtractError if a @required field was lost +``` + +It reads the live metadata, so it takes a loaded `MetaRoot`; there is no text-only +`extractLenientNpcReview(text)`. A bad reply never throws — it is classified in `report` +and `data` holds what was recovered (every field of the `Extracted` mirror is +nullable). It throws only when `root` does not declare the response value object, which is +a setup error. + +Wiring the `extractor` generator as well adds `.extractor.ts` with two more entry +points over the same call: `extract(root, text)` returns the strict response type and +throws when a `@required` field is lost or malformed, and `extractLenient(root, text)` +re-exports the tolerant call above. `extractLenientWithLoader` itself is exported +only from `.response.ts`. + +Field-type → Zod mapping: `field.string` → `z.string()`; `field.int`/`long`/`currency` +→ `z.number().int()`; `field.double`/`float` → `z.number()`; `field.boolean` → +`z.boolean()`; `field.enum` → `z.enum([...])` over its declared `@values`; +`field.uuid` → `z.string().uuid()`; `field.decimal` and the temporal subtypes → +`z.string()` (their JSON wire form); `field.object` (with `@objectRef`) → a nested +`z.object({...})`; `isArray: true` → wrapped in `z.array(...)`; a field that is not +`@required` → `.optional()`. Only a subtype outside that set, or a self-referencing +`@objectRef`, falls through to `z.unknown()`. + +## The response-format prompt fragment (FR-010) + +For every responding `template.prompt`, the `outputPrompt()` generator (same import +path, `@metaobjectsdev/codegen-ts/generators`) emits a +`.responseFormat.ts` exporting `renderFormat(overrides?)` — +backed by the render engine's `renderOutputFormat()`. This is the "produce your +answer like this" fragment you splice into the prompt text so the model returns the +shape the parser above expects: + +```ts +// metaobjects.config.ts — the same entity trio as above, plus outputPrompt +import { + entityFile, queriesFile, barrel, promptRender, outputParser, outputPrompt, +} from "@metaobjectsdev/codegen-ts/generators"; + +export default defineConfig({ + outDir: "src/generated", + generators: [ + entityFile(), queriesFile(), barrel(), + promptRender(), outputParser(), outputPrompt(), + ], +}); +``` + +`@promptStyle` on the `template.prompt` (`guide` default / `inline` / `exampleOnly`) +controls the fragment's presentation: `guide` is a prose field list + example +skeleton, `inline` is one skeleton with inline placeholders/enum choices, +`exampleOnly` is just the filled skeleton. Guidance is never emitted as comments — +models ignore them. Skipped for `template.output` and for any prompt whose +`@responseRef` doesn't resolve — the same skip contract as `outputParser()`. There is NO +format gate: the old `@format ∈ {json,xml}` test read the syntax of the outbound BODY to +decide whether to describe the REPLY. `@responseFormat` selects which syntax the fragment +teaches. The baked spec's root name matches the response shape, so the fragment and the +parser's `extract()` agree on the same root. + +## The three-step consumer pattern + +Render the prompt → call your LLM client (provider-agnostic; nothing is generated +here) → parse the response with the generated parser: + +```ts +// Node-only subpath: the package ROOT stays browser-safe, so the filesystem provider +// lives on `@metaobjectsdev/render/providers`. `lobby/welcome` → ./prompts/lobby/welcome.mustache. +import { FilesystemProvider } from "@metaobjectsdev/render/providers"; +import { renderNpcReview } from "./generated/prompts"; +import { parseNpcReview, safeParseNpcReview } from "./generated/NpcReview.response"; + +const textProvider = new FilesystemProvider("./prompts"); +const promptText = renderNpcReview(payload, textProvider); +const llmResponse = await myLlmProvider.call(promptText); // YOUR code — no generated provider + +// Throwing path: +const npc = parseNpcReview(llmResponse); + +// Result-style: +const r = safeParseNpcReview(llmResponse); +if (!r.success) log.warn("malformed LLM payload", r.error); +else handle(r.data); +``` + +## Recommended LLM caller (bring-your-own) + +MetaObjects generates **no** provider/LLM-call layer and never will — the call is a +commodity the ecosystem already solves, and a maintained vendor wrapper would just +chase SDK churn (ADR-0024). You bring the caller; MetaObjects owns the typed +render → parse → record. For the call step, plug the idiomatic library into the +one-method `LlmClient` seam. The `trace-helper` generator writes it into your project, in +`llm-call.ts` beside the helpers (no package to install): + +```ts +import { generateText } from "ai"; // Vercel AI SDK — recommended +import { anthropic } from "@ai-sdk/anthropic"; +import type { LlmClient } from "./generated/llm-call"; // where trace-helper wrote it + +export const llm: LlmClient = { + async complete({ prompt, model, system }) { + const { text } = await generateText({ model: anthropic(model), system, prompt }); + return { body: text }; // also map usage/model/finishReason from the result → cost + token columns + }, +}; +``` + +**Recommended: the Vercel AI SDK (`ai`)** — provider-agnostic (`generateText` / +`generateObject` over Anthropic / OpenAI / Google / …), first-class structured +output, the de-facto TS standard. Single-provider apps can implement `complete` +directly over `@anthropic-ai/sdk` / `openai`; heavy chains can use LangChain.js — +the seam is one method either way. + +With a client in hand, the generated `call` helper (the `trace-helper` +generator) does render → call → **typed trace persist** in one call, recording +request/response as typed value objects in your own DB; `record` persists a +call you made yourself. The parser above is the standalone receive side if you don't want the +recorder. + +## Drift gate + +`meta verify` walks every template's `@payloadRef` resolution and fails the build +(exit 1) if a reference can't be resolved. A `@responseRef` that does not resolve to a +value-object (or sourceless projection) is caught one layer earlier — it is a LOAD +error in every port. The emitted parser imports `zod`; +it's usually already a dependency (Drizzle / `runtime-ts` lean on it), else +`npm i zod`. + +**Jinja bodies (ADR-0061).** A body may be `/.jinja` (or `.j2`, `.jinja2`) +instead of `.mustache`; `@textRef` does not change. `@metaobjectsdev/render` renders it with +nunjucks (a dependency of the package, nothing to install) and `meta verify` checks it the same +way, walking the parsed template; it names the `.jinja` file and line on a drift. +`FilesystemProvider.engineOf(ref)` reports the engine of the file it found; for an +`InMemoryProvider` pass `new InMemoryProvider(map, { engine: "jinja" })`, or pass +`engine: "jinja"` to `render` / `verify`. A generated `render()` helper over a Jinja body +passes `engine: "jinja"`, so it renders as Jinja through any runtime provider, and the +runtime check runs on it as on a Mustache body. What the check cannot settle statically is +`ERR_TEMPLATE_NOT_STATIC`. nunjucks treats an empty list as true (jinja2 does not), so test a +list with `{% if items | length %}` when the same template must render in Python. + +## See which fields a template consumes + +List `docsFile()` in `generators` and run `meta gen` to emit the model surface to the +`docs` target — one page per `template.*` at `/