Files
notarius/docs/roadmap/implementation.md

454 lines
26 KiB
Markdown
Raw Normal View History

# 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 baseline is `3ba68e6`; 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.1.0` and `rpg/party@0.1.0` from schemas distribution
`2026.11.0`, commit `1b8430bdcbf04eb98c8d45c98a1cb986a9e6d477`.
Use that revision's schemas, semantics, validation profile, and license terms.
- Bundle content under `assets/shared-domain/`, retaining upstream paths
`glossary/v0.1.0/` and `rpg/party/v0.1.0/`. Add a small source/version record
and the selected validation/compatibility documents. Keep the existing single
assets Go file content-only; extend its embed declaration as necessary.
- Put reusable decoding, validation, and retained document types in
`internal/integrations/domainrefs`. Put D&D contextual projections in
`internal/modules/dnd/shared`; spell recognition remains catalog-owned.
No dependency on upstream internal Go packages or runtime schema downloads.
- 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 a
presence-aware document field and a runtime nil-versus-empty slice; do not
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.
Unknown extensions remain retained data, not interpreted instructions. Full
document forwarding preserves extensions; these task views omit them.
- 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 authored data. 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; YAML uses the selected profile (and accepts JSON).
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 Selected Contract Content
**Goal:** Make exact adopted 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. Copy the two schema directories, including adjacent semantics and synthetic
examples, from the exact source revision into the selected asset subtree.
Copy selected validation/compatibility documentation into its `docs/` folder,
preserving contract text and identifying its source. Keep schemas verbatim;
repair documentation links to pinned upstream sources for targets not bundled,
recording those navigation adaptations in the material identification. Do not
copy the full catalog as though the unbundled campaign schema were supported.
2. Record distribution, revision, exact schema versions and canonical IDs in a
small content record. No runtime release discovery or inventory framework.
3. Extend the existing embed declaration. Update asset-package commentary to
recognize shared input contracts as well as LLM content.
4. Add the incorporated material's attribution and applicable CC0 license text
using the existing OSS conventions and commit-pinned links.
**Acceptance:** The packaged filesystem contains the selected 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 — Implement Lossless JSON Document Decoding
**Goal:** Establish the reusable completed-document representation and JSON path.
**Inspect:** Selected validation profile, existing jsonschema dependency usage,
and upstream decoder behavior for guidance only.
**Work:**
1. Create `internal/integrations/domainrefs` with a decoder accepting bytes and
media type and retaining string-keyed objects, arrays, strings, booleans,
null, and exact JSON numbers. Retain a complete document separately from any
later typed view; no general import/composition machinery.
2. Use standard JSON token decoding with `UseNumber` to reject duplicate keys at
every depth, including equivalent escaped spellings, before a map loses them.
Require one complete JSON value; invalid JSON must not fall back to YAML when
the declared media type is JSON.
3. Return contextual decode errors using existing error wrapping, not a public
taxonomy. Add ordinary serialization/forwarding support that preserves values
and extensions without promising original whitespace or key order.
**Acceptance:** Precision-sensitive extension values survive a decode/encode
round trip. Duplicate keys, trailing values, and invalid JSON fail distinctly
from subsequent schema validation.
**Validation:** `go test ./internal/integrations/domainrefs` with focused JSON
fixtures; no network, engine, or credentials.
## Stage 3 — Implement The Shared YAML Decoding Profile
**Goal:** Accept authored YAML without changing its defined data meanings.
**Inspect:** The bundled validation profile, pinned `go.yaml.in/yaml/v4` API,
and selected upstream decoder/fixtures as reference material.
**Work:**
1. Decode YAML nodes into the Stage 2 representation. Enforce one document,
unique string keys, supported tags, and finite numeric values. Resolve aliases
while rejecting cycles; reject merge keys as specified by the profile.
2. Preserve timestamp-like scalars as authored strings, YAML booleans/null as
specified, and integer/decimal precision with standard `math/big` and
`encoding/json` facilities. Handle the profile's alternate integer spellings
and decimal forms without a float64 conversion that loses data.
3. Reuse the JSON decoder for JSON syntax supplied under YAML media where useful.
Preserve node location/field context in errors where the parser provides it.
4. Add representative profile cases, including quoted versus plain scalars,
anchors, duplicate keys, cycles, unsupported tags/keys, nonfinite values, and
large numbers. Avoid cloning the entire upstream harness.
**Acceptance:** Equivalent YAML and JSON yield equivalent document values;
allowed optional/extension values retain their meaning and unsupported profile
forms fail before domain projection.
**Validation:** `go test ./internal/integrations/domainrefs`.
## Stage 4 — Add Offline Shared Validation And Typed Views
**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.
2. Provide glossary/party readers that decode and validate the complete envelope,
then expose typed known-field views alongside the retained full document.
Validate all known fields and all collections, not only selected entries.
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. Include a forwarding test
showing that an `instruction` extension stays ordinary retained data.
**Acceptance:** Both readers conform offline to their exact selected contracts;
typed projection neither discards forwarded extensions nor alters authored data.
**Validation:** `go test ./internal/integrations/domainrefs`.
## Stage 5 — Carry Collection Selection Through Configuration
**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.
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 6 — Preserve Selections Through CLI And Materialization
**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 7 — 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 8 — 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 the Stage 4 readers.
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 9 — 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 8 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 10 — 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 the decoder 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 11 — 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.
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 12 — 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,
whole-document 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.
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 design question is known.