# Shared Domain Schemas Implementation Plan ## Scope And Execution Implement [Shared Domain Schema Adoption](shared-domain-schemas.md). That roadmap owns the target state, intent, and approved input cutover. This document owns the ordered implementation tasks. The planning baseline is `ea163dd`; application code still uses the private spell overlay and text party/glossary references. Each numbered stage is one Luna implementation prompt. Execute in order during one end-to-end sprint. Intermediate stages may leave callers or tests broken; do not build temporary compatibility layers merely to make a stage compile. Record deferred wiring accurately and complete it in its assigned later stage. Final acceptance requires the whole implemented workflow, not just isolated reader tests. Follow `docs/development.md` and its applicable policy guide; commit completed units according to Agent Policy. Only planning documents change while preparing this plan. The instructions below authorize future implementation, not implementation during the planning pass. ## Resolved Design Details - Adopt `glossary@0.2.0` and `rpg/party@0.2.0` from published schemas distribution `2026.11.1`, commit `f7e3cedeca11ed903311cdf29ca4d81fb1f216b7`. The respective document markers remain `maximumdirect.glossary.v1` and `maximumdirect.rpg.party.v1`; unchanged markers do not imply old decoding behavior. No publication wait or historical-version compatibility reader is needed. - Bundle content under `assets/shared-domain/`, retaining upstream paths `glossary/v0.2.0/` and `rpg/party/v0.2.0/`. Include schema files, adjacent semantics, and a small source/version record. Link upstream manuals rather than copying them. Keep the single assets Go file content-only; extend its embed declaration as necessary. - Put a small native-load/schema-validation integration in `internal/integrations/domainrefs`. Use ConfigKit `v1.4.0`'s public `Load[map[string]any](configkit.Bytes(label, content))` for both JSON and YAML. Pass `Result.Config` directly to JSON Schema validation. Keep that resolved mapping as the document; build narrow D&D projections in `internal/modules/dnd/shared` and recognition views in the spell catalog. No custom parser, generic document SDK, or upstream internal-package import. - Use a single-source native load with no enabled imports, selected overlay, defaults, application resolver, overrides, or secrets bootstrap. Native structural behavior still applies, including `extends` and source-root `config` controls. Do not pre-parse, disable, or reinterpret native reserved controls. Retain wrapped native causes instead of reconstructing parser diagnostics. This is a reference-document load, not another load of application settings. - Keep native dynamic number binding (`int64`/finite `float64`) and native value limits. Retain supported resolved extensions, not exact authored numeric spelling/precision or consumed controls. Do not create serialization/forwarding APIs or marshal/reload documents merely to construct typed views. Existing reference items retain original bytes independently where needed. - External reference objects gain `collections: [name, ...]`. Omission or null means slot defaults. Explicit `[]` selects no collections. Preserve this distinction through conversion, cloning, resolution, and inspection. Use ordinary ConfigKit-bound nullable fields and its native presence/inspection behavior, then a runtime nil-versus-empty slice; do not add a presence tracker or collapse an explicit empty slice with `append(nil, values...)`. - Collection names compare exactly, without trimming or case folding. Empty names cannot identify a valid upstream collection and are input errors. Repeated selections are harmless: deduplicate exact names. Selection is a set, not precedence; sort selected names for deterministic projection. Do not add count limits, name grammars, or uniqueness restrictions beyond the contracts. - A bound `spell_catalog` defaults to required `spells`; a bound `glossary` defaults to whichever of `campaign` and `setting` exist. Explicit names must exist. Empty valid collections and explicit empty selection contribute no vocabulary. No binding means no external vocabulary, not a missing-input error. - Configuration-local overrides select the surviving reference object using existing precedence. An omitted selection on that object uses defaults; it does not implicitly inherit selection from a replaced lower-scope object. CLI path overrides are deliberately path-only: retain each concrete target's effective configured selection. CLI-only bindings use defaults. Unbinding removes the binding and its selection. Generated artifacts remain unchanged; `collections` is an external-file selection, not a new artifact selector. - `party` and existing accepted `roster` aliases consume shared party documents; `glossary` consumes shared glossary documents. Retain current party-over-roster precedence and per-module alias availability. `players` stays optional text. Roster player relationships appear in party context; no second authored player file or derived glossary is required. - General context projects names, aliases, categories, descriptions, and plural forms when supplied. Party context projects names, aliases, player relationships, and classes/levels when supplied. Sort roster keys for presentation but omit those IDs from model content. Preserve distinct same-name roster entries. Ordinary extensions remain native resolved data, not model instructions; these task views omit them. Native reserved controls keep their upstream meaning. - Spell context projects canonical names/aliases only. Embedded vocabulary keeps display precedence. For new external names, traverse collections and entries in exact collection-name/entry-ID order so map/list order does not select the display spelling. Use existing lookup normalization; trim surrounding whitespace in the recognition view without changing the resolved document. A name/alias that becomes unusable after normalization is a task suitability error. Preserve existing same-spell alias augmentation and cross-spell collision rejection. - Structured media types are `application/json`, `application/yaml`, and `application/x-yaml`, matching existing file-extension materialization. JSON media requires JSON syntax via a standard `json.Valid` check, followed by the same native load used for YAML. Neither serialization bypasses native limits. Keep current byte bounds rather than adding new ones. Do not infer old text or overlay formats, require optional provenance/rulesets, or add a campaign reader. - Validate completed documents before task selection. Configuration composition remains ConfigKit-owned. Validate external typed references in module construction shared by run and explicit preflight, before domain inference. Keep ordinary offline pipeline validation free of reference-file reads. ## Stage 1 — Bundle The Pinned Aligned Contracts **Status:** Complete. **Goal:** Make the selected released contracts available offline without behavioral asset registration. **Inspect:** `assets/package.go`, schemas tag/catalog and selected version directories in `../schemas`, `docs/policy/oss.md`, and current attribution. **Work:** 1. Read the pinned `2026.11.1` catalog and glossary/party `0.2.0` semantics from commit `f7e3cedeca11ed903311cdf29ca4d81fb1f216b7`. Use these exact versions, not an automatic highest-version selection or older contracts with the same `.v1` markers. Campaign support remains deferred. 2. Record distribution, full source commit, versions, document markers, and canonical IDs in a small asset source record. The IDs are `https://schemas.maximumdirect.net/glossary/v0.2.0/schema.json` and `https://schemas.maximumdirect.net/rpg/party/v0.2.0/schema.json`. No runtime release discovery or inventory framework. 3. Copy only the selected schema files and adjacent semantics, plus exact schema dependencies if any, into the asset subtree. Keep schema files verbatim; link nonbundled documentation targets to the selected upstream revision and record any navigation adaptations. Do not copy upstream parser manuals, full example archives, or a catalog advertising unbundled campaign support. 4. Extend the existing embed declaration. Update asset-package commentary to recognize shared input contracts as well as LLM content. 5. Add the incorporated material's attribution and applicable license text using the selected release's actual terms, existing OSS conventions, and pinned links. **Acceptance:** The packaged filesystem contains the pinned `0.2.0` schemas and semantics; `assets` still has no business logic or kit dependency. Source/license records describe only incorporated material. **Validation:** `go test ./assets`; inspect copied files against `git show` at the selected upstream commit, and `git diff --check`. ## Stage 2 — Load Shared References Through ConfigKit **Status:** Complete. **Goal:** Delegate parsing and resolution for both serializations to ConfigKit. **Inspect:** ConfigKit's pinned public `Load`, `Bytes`, and dynamic-value contracts; the aligned schemas' semantics; existing reference byte/media-type transport. **Work:** 1. Create a small shared-reference loader in `internal/integrations/domainrefs` that accepts already-materialized bytes, media type, and a useful diagnostic label. For JSON media, use only `json.Valid` to enforce JSON syntax. Then call the public native byte-source load for either media type. 2. Return the native resolved mapping for subsequent schema/domain validation. Do not recreate a raw/typed document hierarchy, custom JSON token walker, direct YAML-library decoder, numeric adapter, or generic conversion API. 3. Use the single-source selections above. Native parsing, structural resolution, scalar binding, limits, and error details remain authoritative. Wrap failures with reference context and retain their causes; do not create an error taxonomy. 4. Add a few public-API integration tests: ordinary equivalent YAML/JSON input, one representative native rejection, resolved numeric/extension values, and native reserved-control handling. Do not reproduce ConfigKit's parser matrix. An `instruction` extension remains ordinary data. JSON receives no fallback path when ConfigKit rejects a syntactically valid document. **Acceptance:** Both serializations use one native loading boundary. No exact numeric-preservation guarantee, independent parser, or configuration reconstruction has been introduced. ConfigKit failures remain distinguishable from later schema and domain checks without reimplementing native error semantics. **Validation:** `go test ./internal/integrations/domainrefs`; no network, engine, or credentials. ## Stage 3 — Validate Resolved Shared Documents **Status:** Complete. **Goal:** Separate shared conformance from consumer requirements. **Inspect:** Bundled schemas/semantics and `assets.FS()`. **Work:** 1. Register the two local schemas under their canonical IDs using the existing jsonschema library. Compile once with safe shared reuse; configure unresolved resource loads to fail locally. Do not enumerate unrelated schemas or query canonical URLs at runtime. Schema resource JSON remains owned by the schema engine's resource loader, preserving exact numeric constraints; it is not a domain document to load through ConfigKit. 2. Validate the Stage 2 native mapping directly. Check the complete resolved envelope, all known fields, and all collections, not only selected entries. Do not decode a second typed copy or marshal/reload subtrees. Add narrow typed accessors/projections only where needed by the concrete consumers. 3. Check glossary entry-ID uniqueness within each collection using exact strings. Do not add name uniqueness, global ID uniqueness, required player/classes, or cross-document reference checks. 4. Implement exact collection selection with the presence/default rules above; keep slot-specific default choice in D&D code. Report absent selected names as task errors, not upstream schema errors. 5. Cover omitted/null/empty aliases, permitted extensions at all relevant levels, invalid optional-field types, empty collections/rosters, shared IDs across collections, and duplicate IDs within a collection. Retain supported resolved extensions in the mapping without inventing a forwarding subsystem. **Acceptance:** The native resolved mapping is validated offline against the exact aligned contracts. Domain checks add no new authoring format or decoding path. **Validation:** `go test ./internal/integrations/domainrefs`. ## Stage 4 — Carry Collection Selection Through Configuration **Status:** Complete. CLI path overrides and materialization are wired separately below. **Goal:** Preserve binding selection and its presence through normal configuration resolution without changing ConfigKit ownership. **Inspect:** `internal/core/config/{document.go,pipeline_document.go,loaded_config.go,document_paths.go,config.go}`; `internal/framework/pipeline/profile.go` and copy helpers; reference contract types in `internal/framework/contracts/contracts.go`. **Work:** 1. Add the presence-aware `collections` field to external reference documents, runtime `ReferenceSource`, and resolved `ReferenceBinding`. Extend existing external-source constructors as needed; avoid duplicate legacy source types. Use ordinary typed ConfigKit binding and inspection. Do not create another presence index, source tracker, configuration merge, or cloning framework. 2. Keep the reference source union explicit: collection selection accompanies `path`, not `artifact`. Reject wrong selection types and empty names; preserve null/omitted versus explicit empty according to the resolved design. 3. Carry selection through pipeline, step, lane, and stage maps, runtime conversion, effective resolution/digests, and clone helpers. Deep-copy slices and retain nil/empty distinctions. Do not alter source-relative path handling. 4. Treat configured local source replacement as replacement of the whole external reference object. Leave field composition before that point to ConfigKit; do not add a second inheritance algorithm. **Acceptance:** ConfigKit inspection and detached runtime settings reflect the operator's selection. Changing a detached selection cannot mutate its source; explicit `[]` does not turn into defaults. **Validation:** Focused configuration and pipeline reference/copy tests with `go test ./internal/core/config ./internal/framework/pipeline`. Temporary failures from later wiring must be identified, not hidden with compatibility scaffolding. ## Stage 5 — Preserve Selections Through CLI And Materialization **Status:** Complete. **Goal:** Deliver selected input views consistently to consumers. **Inspect:** `internal/cli/reference_selectors.go`, framework reference resolution in `profile.go`, `references.go`, reference clone/marshal helpers, and existing CLI reference contract tests. **Work:** 1. Carry selection from each resolved binding into its materialized `ReferenceItem` (and its clone/evidence serialization as applicable), alongside unchanged complete bytes, origin, raw-content digest, and media type. 2. Apply CLI path overrides after configured scope resolution while retaining each concrete target's surviving configured selection. A broad CLI selector may therefore replace paths on targets with different selections. Preserve current specificity, unbind, required-slot, and generated-handoff behavior. 3. Keep readers out of generic materialization. Collection names are opaque metadata here; D&D consumers perform glossary interpretation. Collection selection on a non-collection D&D slot should receive a useful task error rather than being silently interpreted as something else. 4. Test configured pipeline/local precedence, explicit empty selections, broad and narrow CLI overrides, CLI-only defaults, unbinding, and clone isolation. Keep file byte limits and raw reference digests unchanged. **Acceptance:** The final selected target has the right path and selection; materialization retains the full shared document for validation. No new CLI flag or configuration composition mechanism is introduced. **Validation:** Focused tests in `./internal/framework/pipeline` and `./internal/cli` for reference handling. ## Stage 6 — Cut Spell Recognition Over To Shared Glossaries **Goal:** Replace the private overlay format across the whole spell family. **Inspect:** `internal/modules/dnd/spells/catalog/effective.go`, extraction and normalization constructors, `internal/modules/dnd/validate/spells/catalog`, and CLI spell catalog identity/correction contract tests. **Work:** 1. Replace overlay decoding with the shared glossary reader/selector. Accept the three structured media types. Retain the existing optional reference and byte bound; empty selected collections retain embedded-only recognition. 2. Feed names and aliases into existing effective vocabulary construction using the deterministic traversal and recognition-view normalization above. Retain embedded display precedence, same-spell alias augmentation, and cross-spell collision diagnostics with selected collection/entry context. 3. Remove private overlay wire types, marker, parser, and obsolete metadata requirements. Adapt internal digest/metadata helpers where still needed; do not turn them into new accepted-result cache-key inputs. 4. Ensure extractor, normalizer, and validator construction all use the same selected reference semantics. Keep model catalog material name/alias-only. 5. Replace affected fixtures/helpers with shared documents. Test a custom spell, an embedded spell alias, collisions, optional/null aliases and provenance, arbitrary categories, explicit selection, and unusable normalized names. **Acceptance:** One shared glossary serves recognition and normalization with no overlay conversion. Old envelopes are not accepted as an alternative format; no durable spell shape or evidence rule changes. **Validation:** `go test ./internal/modules/dnd/spells/... ./internal/modules/dnd/extract/spells ./internal/modules/dnd/normalize/spells ./internal/modules/dnd/validate/spells/...` and focused CLI spell-catalog tests after their fixture migration. ## Stage 7 — Prepare Shared Context For Scenes And Registry Lanes **Goal:** Establish one reusable context preparation path and migrate its first coherent consumer group. **Inspect:** `internal/modules/dnd/shared/{references.go,prompt_inputs.go}`, `chunk/scenes`, extractors for item/NPC/location registries and scene descriptions, and `assets/dnd/shared/prompts/common-dnd-references.md`. **Work:** 1. Add a constructor-time shared context preparer using Stage 3's validated native mappings and narrow task views. Prepare fixed party/glossary/player material and combine it with each operation's current transcript material. Keep generated references separate and dynamic. 2. Change party/roster/glossary declarations to structured media; retain text acceptance for `players`. Validate every supplied typed slot, including a bound roster alias even if canonical party context takes presentation precedence. 3. Implement deterministic projections described above. Keep IDs and provenance in internal data, not the body the model must interpret. Roster relationships live in party material; the independent players material stays supplemental. 4. Store immutable prepared context in the scene chunker and four selected extractors. Update constructors, builders, and request assembly; invalid references must fail construction, not wait for a chunk or cache miss. 5. Adjust shared prompt labels/instructions only as necessary for the new contextual material. Preserve shared-asset use, message ordering/cache controls, native correction, and the reference-versus-transcript evidence distinction. **Acceptance:** These consumers use the same projection without per-chunk parsing; missing optional context is supported and same-name roster members remain distinct. **Validation:** Shared projection tests plus scene chunker and four migrated extractor package tests. Update obsolete text fixtures for these consumers. ## Stage 8 — Migrate All Remaining D&D Context Consumers **Goal:** Complete context cutover without leaving a text-input bypass. **Inspect:** Remaining extraction constructors/builders for spells, combat turns, item/NPC/location occurrences, and enemy events. Inspect direct prompt material calls and grounding helpers, including enemy-event material assembly. **Work:** 1. Migrate these six extractors to the Stage 7 prepared context facility. Keep their generated registry/scene/combat handoffs and operation-local inputs intact. 2. Audit production calls to `shared.PromptInputs`, `ReferencePromptMaterial`, and `ReferencePromptInput`. Remove the obsolete party/glossary raw-text path; preserve generic text handling still needed by supplemental players or other unrelated context. 3. Update constructors and registration builders consistently. Do not modify deterministic normalizers to consume party context they do not currently use. 4. Migrate affected package/integration fixtures and assert representative contextual names/aliases/relationships, rather than snapshotting whole prompts. Retain correction and generated-reference behavior coverage. **Acceptance:** All ten extractors and the scene chunker validate/prepare their declared shared inputs consistently. No stage-scoped typed binding escapes validation simply because no chunks execute or accepted artifacts are cached. **Validation:** `go test ./internal/modules/dnd/... ./internal/modules/integration`. ## Stage 9 — Verify Assembled Run And Preflight Behavior **Goal:** Prove the public workflow through real internal collaborators and fake provider boundaries. **Inspect:** `internal/cli/pipeline_invocation.go`, `pipeline_preflight.go`, `internal/framework/pipeline/prepare.go`, CLI preflight/reference tests, and `internal/preflight/preflight.go`'s separate offline boundary. **Work:** 1. Add focused assembled tests supplying shared YAML/JSON references through CLI paths and scoped configuration. Check selection survives into actual prepared model input and spell normalization/catalog validation. 2. Prove run and explicit preflight reject malformed party/glossary documents, duplicate IDs, absent explicit collections, and spell collisions before any fake domain inference/provider smoke call. Use representative cases rather than rerunning ConfigKit's parser matrix in CLI tests. 3. Prove valid shared inputs reach the expected tasks; use a controlled empty model extraction with populated references to verify the application does not synthesize reference-only events. Do not assert live model quality guarantees. 4. Verify construction occurs before accepted-result reuse, and offline pipeline validation still works with nonexistent reference paths. Keep ordinary run free of preflight probes and keep reports/cancellation/generated handoffs unchanged. 5. Fix missing wiring at its owner, using existing preparation rather than a second CLI-specific reader or a domain-dependent generic framework hook. **Acceptance:** Input and suitability checks have one behavior for run/preflight; the final ordinary pipeline remains usable with optional references omitted. **Validation:** `go test ./internal/cli ./internal/preflight ./internal/framework/pipeline`. ## Stage 10 — Migrate Maintained Examples And Canonical Documentation **Goal:** Make the supported workflow discoverable without duplicating upstream schema manuals. **Inspect:** `examples/dnd-complete/`, CLI example contract tests, `docs/config.md`, integration docs, D&D consumer guide, relevant internal guides, and the documentation/OSS policies. **Work:** 1. Replace `party.txt`, `glossary.txt`, and `spell-catalog.json` with synthetic `party.yml` and multi-collection `glossary.yml`. Bind the latter to general glossary and spell-catalog roles, including both spell extract and normalize where currently configured. Preserve imports, development overlay, all ten lanes, ordered handoffs, and auxiliaries. Keep the minimal example minimal. 2. Update example tests to validate shared references and exercise one maintained full pipeline with fake model responses. Do not require a sibling checkout. 3. Create `docs/integrations/shared-domain-inputs.md` owning supported versions, serializations and Notarius task adaptations; link pinned upstream semantics for the format. Retire the private overlay contract and update inbound links. 4. Update config reference fields/defaults, CLI path-override semantics, D&D subprocess examples, and relevant internal ownership docs. Include a concise migration section: new envelopes, existing slot names, collection selection, nullable aliases, optional provenance, and roster-derived player relationships. Link native loading, numeric binding, limits, and reserved controls to the pinned ConfigKit documentation rather than maintaining a second manual. 5. Recheck attribution and copied content. Do not publish a release, preselect a version, or claim other applications already support the shared format. **Acceptance:** A caller can follow maintained docs to supply one roster and one shared glossary through the CLI with no duplicate spell/player authoring. Current docs describe the implemented cutover, not legacy support or future campaigns. **Validation:** `go test ./internal/cli -run 'TestMaintained|TestCompleteDNDSharedCLIReferences'`; local link checks and searches for retired example paths/overlay marker. Intentional migration explanations are not stale references to delete. ## Stage 11 — Final Contract And Regression Pass **Goal:** Finish the end-to-end sprint with all target behavior verified. **Work:** 1. Review each feature-roadmap acceptance item against current implementation and tests. Check explicit-empty/default selection, multi-target CLI overrides, supported decoded extension retention, all context consumers, schema offline use, spell collision/display policy, and preflight/run agreement. 2. Check for accidental extra requirements: mandatory context/player/classes, trimmed authored strings, extra name/ID uniqueness, extension rejection, ruleset/provenance requirements, custom composition, new caps or retries. Confirm no parallel parser, scalar adapter, subtree conversion round trip, generic document/forwarding SDK, or copied upstream parser suite remains. Native reserved controls and dynamic-value limits are upstream behavior, not locally reimplemented restrictions or guarantees. Check durable outputs, session identity, native reports and cache policy remain unchanged. Remove temporary migration scaffolding and obsolete fixtures. 3. Run `gofmt` on modified Go files, then `go test ./...`, `go vet ./...`, and `go build -o /tmp/notarius-shared-schemas-check ./cmd/notarius`. Run `git diff --check` and verify documentation links/examples. No API key or paid request is required. Optional cross-application/live model evaluation is separate from completion of deterministic acceptance. 4. Record results and any real remaining gaps. Do not mark the feature complete based only on isolated reader tests or compilation. Commit the completed unit according to repository policy; release/tag/push needs separate authorization. **Acceptance:** All stages' outcomes and the feature-roadmap acceptance criteria are satisfied; repository-wide checks pass and no compatibility reader or duplicated authoring workflow remains. No blocking product decision or schema publication prerequisite remains.