Files
notarius/docs/roadmap/implementation.md

953 lines
53 KiB
Markdown
Raw Normal View History

# Core And Integration API Implementation Plan
## Purpose And Baseline
Implement the accepted [Core And Integration API Roadmap](core-integration-api.md).
That document owns scope and policy; this plan owns the implementation sequence.
The outcome is a core-driven authoring API, not just a smaller `RunProducer`.
Planning baseline: `a051f34bf6db92bef65871f7602f0d15ea12b27c`.
Application code is unchanged from
`3887d89b763b7040efc866d4a57eb910d8778730`. Go 1.27.0 and the dependencies in
[go.mod](../../go.mod) are sufficient starting points. No dependency update,
configuration migration, durable schema change, or production inference is planned.
Each numbered stage is one implementation prompt for a Luna coding agent. Follow
the stages in order as one end-to-end sprint. Intermediate stages may leave
unmigrated callers or tests uncompilable. Do not build compatibility interfaces,
duplicate executors, or temporary supported authoring recipes merely to make
each stage green. Keep a short record of deferred compile/test repairs so later
stages can finish them. All acceptance criteria must hold at sprint completion.
Begin each stage with [Development](../development.md),
[Agent Policy](../policy/agents.md), and the policies applicable to its changes.
Use code discovery to confirm current callers; the paths below are starting
points, not a closed inventory. Preserve unrelated changes. Follow local commit
policy for completed units; an intermediate commit must accurately describe any
known incomplete migration. This plan does not authorize pushing or releasing.
Source-path shorthand below uses `contracts`, `pipeline`, and `semanticreconcile`
for their directories under `internal/framework`, and `dnd` for
`internal/modules/dnd`. Test files remain beside their owning packages.
## Selected Implementation Decisions
These decisions make the work executable without another design approval round.
Exact Go names and file splits can follow the representative callers; preserve
the responsibilities and data flow below.
### Contracts And Dependency Direction
- Put author-facing operation/preparation/evaluation contracts beside the existing
typed stage contracts in `internal/framework/contracts`. Keep core execution
in `internal/framework/pipeline`. The reconciliation facility remains in
`internal/framework/semanticreconcile` and returns operation definitions for
that same executor; it does not execute a second producer loop or import D&D.
- A stage implementation prepares a typed operation. Core invokes preparation
and executes its result. Remove the module request's assessor, cache binding,
controls, and reuse-eligibility plumbing. Domain requests retain source/chunk,
incoming values, references, profile/session selection, metadata, and any narrow
optional domain-evidence facility actually needed.
- Distinguish deterministic candidate, native model operation, and the existing
preparation-limit disposition with small typed variants/constructors. Ordinary
preparation failure is a Go error, not the limit variant. Avoid a workflow DSL
or one struct containing unrelated optional branches.
- Keep engine, resolved controls, assessment, cache codecs/store, observation,
and terminal state in core's execution context. Registered calls bind this
context privately. A direct caller can supply the needed core execution
context and preparation function to the same executor; domain preparation
does not select or replace those collaborators.
- Remove engine storage and constructor arguments from producers that only used
the engine to run the retired helper. Validators that execute native one-shot
assessment still receive the shared engine. Do not remove native request and
result types from model-owning integrations.
### Evaluation And Correction
- One evaluation owns the optional typed candidate, ordered interpretation
guidance, candidate-associated diagnostics, and any evaluation-scoped domain
evidence/presentation. Core adds configured assessment separately and stores
the current evaluation as a unit. A candidate is not an acceptance claim.
- Reconciliation uses a typed evaluation record containing its proposal issues,
application information, omission counts/details, and family findings. Expose
the small common evaluation view to core, using composition or a small typed
interface. Keep reconciliation-only information out of ordinary extraction.
Evaluation-scoped projection functions may capture those fixed typed details;
a mutable `lastProposal`/`lastFindings` closure shared across turns is not the
replacement design. No untyped universal metadata payload is needed.
- Core invalidates the entire previous evaluation before constructing a selected
correction. Construction failure, unusable native output, and undelivered work
cannot leave its candidate or findings available as current output. Historical
evidence may retain earlier evaluations.
- The common correction form selects a native prompt and provides an explicit
guidance-to-native-input binding. Implement it by constructing the same native
request builder used by the custom form. Do not require a global `guidance`
variable name or D&D response schema. Carry explicit initial profile/session
selection and resolved native execution options through both forms.
- Core owns when fallback is selected. An integration constructs and intrinsically
checks supported output from the final eligible evaluation, or its existing
fixed fallback inputs when no evaluation remains. Family diagnostic projection
uses that same evaluation and terminal disposition, not an earlier turn.
### Preparation And Terminal Behavior
| Prepared/executed outcome | Core behavior |
| --- | --- |
| Ordinary preparation error or deterministic production error | Propagate; do not turn arbitrary errors into permissive recovery. |
| Deterministic candidate, including a no-model branch of a model role | Assess once; apply existing terminal policy after nonacceptance. No native request, correction loop, or synthetic cache key. |
| Existing explicit preparation-limit disposition | Apply existing strict/permissive handling and supported fallback. Do not assess a nonexistent candidate or broaden eligibility. |
| Usable model candidate | Run the complete configured assessment; collect ordered actionable guidance; continue through native coordination when permitted. |
| Correctable interpretation without a candidate | Use its domain guidance for native correction; do not claim approval or run candidate validators without a value. |
| Native failure or unusable result | Preserve classification/details and existing terminal policy. Do not convert it into semantic guidance or extend native repair budgets. |
| Model interpretation/application error | Preserve its cause and existing disposition; do not invent corrective guidance from an operational error. Capture and assessment-contract failures remain fatal. |
| Caller cancellation, undelivered response, framework/assessment-contract failure, or required-capture failure | Preserve existing fatal handling; no acceptance or fallback. |
| Accepted cache hit | Decode/check against current source; return accepted output without semantic reassessment or fictitious native execution. |
Preserve the distinction between caller cancellation and a native operation
timeout. Preserve final-only safe-partial reconciliation, whole-chain assessment
of the final allowed usable response, and exactly one fallback count at its
emitting operation. These are existing contracts, not additional guarantees.
### Scope Control
Preserve native-kit ownership, module keys/default chains, fixed stage boundaries,
artifact types/identity rules, source semantics, CLI/configuration behavior, native
budgets, output/report contracts, and cache identity. Optional configured checks
remain optional; codec acceptance must not silently become ordinary validator
acceptance. An unsupported fallback still fails.
Use the existing generic source model. Email and NWS Forecast Discussion
walkthroughs exercise text, domain metadata, chunk selection, and interpretation;
they do not implement new processors, ingestion, formats, or mandatory topology.
Do not introduce a public SDK/version guarantee, dynamic plugins, a new scheduler,
resource limits, security hardening, or universal collaborator thread safety.
The remaining [audit catalog](audit/catalog.md) is not this sprint's task list.
CAT-015/CAT-016 and CAT-007 are in scope. Other entries are affected only to the
extent demonstrated by this migration. In particular, runner-wide diagnostic
retention/group-cap changes, process signals, full-source capture deduplication,
pipeline-layout consolidation, and unrelated efficiency fixes remain separate.
If this work must change whole-source capture representation, follow the accepted
[discussion Item 2](audit/discussion.md#2-convenient-debug-evidence-and-repeated-full-source-capture)
and record the added scope; do not invent a conflicting representation.
## Validation Approach
Use real internal collaborators and native kits with offline provider fakes.
Move/adapt existing behavioral tests as their entry points change; retain their
independent domain expectations. New common lifecycle coverage belongs in core,
not a full duplicate matrix in every family. Test observable outputs, assessment,
native history/selections, fallback, cancellation, reuse, and capture failure.
Do not pin callback order, type layout, error prose, prompt English, or hashes as
change detectors. Test-controlled prompt markers may verify request binding.
Each stage lists focused commands. Run them when the affected packages can build;
if an earlier interface cutover prevents execution, record that fact and rerun the
checks after migration rather than claiming they passed. The last stage requires
the full suite. No paid API, benchmark threshold, coverage target, new CI gate,
or release process is needed. Adjust focused test-name filters when tests move
or are renamed; a filter matching no tests does not verify the stage.
## Stage 1 — Define The Typed Preparation And Evaluation API
**Status:** Complete.
**Goal:** Establish the authoring contract using representative integrations.
### Migration checklist
- Native producer callers: D&D scene planning; spell, combat-turn, enemy-event,
scene-description, registry, and occurrence extractors; and NPC, item, and
location registry normalizers. Combat-turn and enemy-event extraction also
have deterministic no-model branches.
- Registry normalizers additionally call the deterministic assessment helper
for insufficient candidates and the terminal-failure helper for preparation
limits. Pipeline completion also calls the assessment helper.
- Migrate chunker registration and typed extractor, merger, and normalizer
registries, including generic unit chunking, append-order merge, and noop
normalization, plus deterministic D&D normalizers.
- Adapt direct producer, cache, capture, cancellation, operation, typed-registry,
CLI, integration, and module tests as their entry points move. Combat semantic
validation remains a separate one-shot native caller.
The inventory is a migration aid; confirm additional callers as interfaces move.
**Inspect:** `contracts/{contracts,typed_pipeline,producer}.go`,
`pipeline/{typed_execution,construction}.go`, spell extraction, scene planning,
the three registry normalizers, and current source types.
**Work:**
- Inventory producer/outcome-helper callers, typed registrations, direct tests,
generic deterministic modules, and preparation-limit/no-model paths. Keep the
inventory as a compact migration checklist in this plan, without freezing counts.
- Define the operation variants and common evaluation view selected above.
Give the core a preparation function to invoke; do not inject an executor for
the module to call. Separate domain requests from framework execution context.
- Sketch spell extraction, scene-plan interpretation with no candidate, a
deterministic branch, and registry application through those types. Add small
synthetic email/NWS-shaped source and operation sketches. Use domain metadata
without transcript speakers, scene tags, or registry requirements.
- Specify ownership of returned operation inputs, evaluation values, mutable maps/
slices, and optional evidence hooks in local comments. Existing prepared module
instances may serve concurrent operations; new per-operation state belongs to
that preparation, not shared module fields. Preserve current detached boundaries
rather than imposing a new blanket clone/immutability system.
**Acceptance:** Representative cases fit one core-driven contract; no domain type
enters core; ordinary preparation cannot access assessor/cache replacement or
terminal helper selection. Exact names are selected here, not deferred to each
module migration. Keep the design sketches small and reusable as later fixtures.
**Check:** `go test ./internal/framework/contracts ./internal/core/source`.
This stage is one prompt for contracts and sketches, not executor implementation.
## Stage 2 — Correct And Share Native Result Usability Handling
**Status:** Complete.
**Goal:** Resolve CAT-007 independently of the broader lifecycle rewrite.
**Inspect:** `pipeline/producer.go`, combat semantic `validator.go` and tests,
`semanticreconcile/engine_test.go`, and pinned native result/error types.
**Work:**
- Add one small framework-owned check distinguishing absent result, completed
failed/invalid native validation, and an actual native Go error. Keep useful
native validation details in the returned cause. Do not manufacture
`promptkit.ErrValidation` for a completed content-check failure.
- Use it in the current producer and one-shot combat validator. The producer
retains its terminal handling; the validator retains unavailable judgment.
Preserve actual upstream causes for `errors.Is`/`errors.As`, cancellation,
capture failure, and ordinary valid-result interpretation.
- Correct the validator's wrong-sentinel assertion. At both caller boundaries,
check retained validation detail and refusal to interpret unusable content.
- Repair the native reconciliation fixture to select its real schema context,
request zero repair attempts, and require nil Go error plus a present failed
validation result with useful details and one provider call. An arbitrary setup
or schema-path error must not satisfy that test.
**Acceptance:** A completed failed check is not mislabeled as an upstream
operational error; real upstream errors retain their identity. No extra loop or
budget is added. The later executor reuses this check.
**Checks:** `go test ./internal/framework/pipeline ./internal/framework/semanticreconcile`
and `go test ./internal/modules/dnd/validate/scenedescriptions/combat_semantics`.
## Stage 3 — Execute Preparation And Deterministic Outcomes In Core
**Status:** Complete.
**Goal:** Implement the core entry point and terminal policy before native work.
**Inspect:** `pipeline/{producer_outcome,runner_operation,candidate_assessment}.go`
and their existing tests; Stage 1's types and migration checklist.
**Work:**
- Implement the typed executor that calls preparation once and consumes its
operation variant. Registered and direct use will share this implementation.
- Handle deterministic candidate, explicit preparation limit, and ordinary error
distinctly. Reuse assessment/terminal helpers privately where useful.
- Return core-owned value, current evaluation/assessment information needed for
diagnostics, and terminal disposition. Integrations do not construct acceptance.
- Apply core terminal mode once. A supported fallback is constructed once,
intrinsically checked by its owner, not ordinarily reassessed, and reuse-ineligible.
Honor caller cancellation and framework/assessment-contract failure precedence.
- Port existing no-model and terminal-policy tests to the new core boundary;
cover a preparation error that must not invoke fallback.
**Acceptance:** Core invokes preparation and assessment; deterministic work has
no engine/request requirement, no synthetic key, and no production retry. Existing
permissive behavior is neither widened nor removed.
**Check:** `go test ./internal/framework/pipeline -run 'Producer|Operation'`.
## Stage 4 — Move Native Evaluation And Continuation Into The Executor
**Status:** Complete. Existing integrations still use the previous producer
entry point until their scheduled migrations.
**Goal:** Own model production and replace coupled outer candidate variables.
**Inspect:** `pipeline/producer.go`, native continuation/cancellation tests, and
the initial/correction request pairs in the pilot modules.
**Work:**
- Run native initial requests through the shared engine and Stage 2's usability
check. Interpret into a complete evaluation; assess each usable candidate once.
- Use explicit current-evaluation and terminal state, separate from pending
capture state. Replace findings with the candidate and clear the evaluation
before building a selected correction. No stale candidate survives a failed
builder, result-less execution, or unusable correction.
- Implement the common correction prompt plus guidance-input binder as a native
builder convenience. Exercise a different test-controlled input binding and a
specialized builder. Both use one path with native `Coordinate`, growing
exchange history, initial selections, and resolved execution overrides.
- Carry interpretation-only guidance without a candidate. Native errors and
validator unavailability do not become invented corrective instructions.
- If a candidate exists, interpretation guidance does not short-circuit its
configured validator chain. Keep native admission released before assessment
so nested validators can use the same limited backend.
- Preserve complete assessment of unchanged revisions and the final allowed
response, native turn limits, caller-cancellation precedence, operation-timeout
classification, and undelivered-response handling.
**Acceptance:** The executor owns acceptance and continuation; the integration
has no turn loop. Candidate and associated findings are replaced atomically as a
logical evaluation. Existing producer tests protect behavior, not old closures.
**Check:** `go test ./internal/framework/pipeline -run 'NativeProducer|Producer.*Cancellation'`.
## Stage 5 — Bind Accepted-Result Reuse Inside Core Execution
**Status:** Complete.
**Goal:** Preserve cache semantics without author-controlled lifecycle plumbing.
**Inspect:** `pipeline/{producer_cache,runner_cache}.go`, producer/runner cache
tests, chunk-plan cache tests, and [ADR-0023](../adr/0023-unify-accepted-artifact-and-plan-caching.md).
**Work:**
- Bind existing store, exact codec, current-source checks, and reuse eligibility
to the executor through framework-owned context, not domain preparation requests.
- Prepare the initial native request once; use its opaque message-content hash
and execute its retained prepared handle after a miss. Discard handles on every
terminal path. Do not rerender between keying and execution.
- Cache final accepted artifacts/plans, including corrected output, under the
original key. Hits decode/check current source without ordinary reassessment.
- Preserve bypass/refresh and previous entries on failed refresh. Fallback or
fallback-derived work skips lookup/write; deterministic/no-model work has no
manufactured key. Keep cache I/O diagnostic and encoding/capture errors distinct.
**Acceptance:** Existing reuse tests can use the new executor without changing
the selected cache contract, adding dimensions, or persisting evaluation metadata.
**Check:** `go test ./internal/framework/pipeline -run 'ProducerCache|ProducerCaches|ProducerExecutes|RunnerCache|ChunkPlanCache'`.
## Stage 6 — Attach Evidence And Observation To Core-Owned Operations
**Status:** Complete.
**Goal:** Keep standard evidence out of integration lifecycle code.
**Inspect:** `pipeline/{native_capture,operation_capture,producer}.go`,
operation evidence helpers, native capture tests, and run-state internals.
**Work:**
- Attach existing native capture/preparation/consumer observation hooks at the
executor boundary. Preserve supplied native hooks and the invocation context.
- Record standard preparation, candidate assessment, correction, cache decision,
and terminal evidence from actual execution. Retain earlier evaluations as
history without attributing their findings to the final artifact.
- Keep pending native capture finalization separate from candidate evaluation.
Finish each actual request on success, native failure, cancellation, or
undelivered continuation; preserve requested-capture failure and primary causes.
- Allow narrow optional domain evidence, including typed reconciliation detail,
without making the integration finalize capture. Guard expensive debug-only
construction before building its payload; use evaluation-scoped lazy projection
where needed. Required artifact encoding is not debug-only work.
- Cache hits may retain prepared/cache evidence but emit no native execution or
fabricated observation. Do not add invocation accounting or a capture package
migration. Leave untouched legacy capture inventory for the later audit work.
**Acceptance:** Disabled evidence avoids new expensive debug-only work; enabled
evidence and independent observers retain their actual lifecycle. Physical sinks,
allocation, report delivery, and invocation finalization remain at existing owners.
**Check:** `go test ./internal/framework/pipeline -run 'Capture|Evidence|Producer'`.
## Stage 7 — Wire Typed Extraction And Migrate The Spell Pilot
**Status:** Complete. The spell and pipeline checks pass. The broader modules
check is deferred: the other D&D extractors and integration fixtures still use
the previous extraction interface. Migrate the extractors in their assigned
work and repair the remaining assembled fixtures by the cutover completion.
**Goal:** Prove registered extraction reaches the core executor end to end.
**Inspect:** `pipeline/{extractor_registry,typed_execution,prepare,runner_concurrent}.go`,
spell `extractor.go`, shared extraction input helpers, and typed registration tests.
**Work:**
- Change extraction's typed interface/request to preparation under the selected
API. Registry erasure binds exact type and core context, invokes preparation
through the executor, and returns only core-completed results to the runner.
- Adapt `runExtractJob` without adding a second worker acquisition, outer
assessment, or new scheduler. Preserve source/reference isolation, provenance,
diagnostic origin, fallback count, serialization, and scoped errors.
- Migrate spells: prepare fixed catalog/registry/chunk inputs, return native
initial request and interpretation plus convenient correction and fallback.
Remove the producer engine field and domain `RunProducer` invocation.
- Update spell direct-call tests to use the same core entry point with explicit
test-controlled core context; retain independent expected spell output.
- Exercise exact-type registration and a core-selected correction/cache hit
through a registered pilot, not only a helper test.
**Acceptance:** Spell domain code describes preparation and policy, not execution
or terminal composition. Registration uses core; no external outcome can bypass
its assessment. Other extractors may await their migration stages.
**Checks:** `go test ./internal/modules/dnd/extract/spells` and focused typed
extraction/operation tests in `./internal/framework/pipeline`.
## Stage 8 — Wire Merge And Normalize Preparation
**Status:** Complete. Generic modules and pipeline fixtures use the new
boundary. D&D normalizers and assembled fixtures still using the former
normalizer interface are deferred to their scheduled migrations and cutover.
**Goal:** Apply the same boundary to the remaining typed lane stages.
**Inspect:** `pipeline/{merger_registry,normalizer_registry,typed_execution,runner_typed}.go`,
generic `merge/appendorder/typed.go`, generic `normalize/noop/typed.go`, and prepared lanes.
**Work:**
- Adapt typed merger/normalizer registration and private exact-type erasure to
bind and invoke the same executor. Retain type/codec/projector compatibility
failures as errors, not panics or looser `any` acceptance.
- Change runner merge/normalize completion to consume core outcomes rather than
trust module-owned disposition and then choose another completion recipe.
- Migrate generic append-order and noop implementations to deterministic prepared
candidates. Keep ordering, domain combine errors, empty representation, and
ownership behavior. No synthetic prompts are required.
- Keep merge/normalize in the existing ready lane continuation. Preserve generated
handoff/reuse propagation and count emitted fallback once, not again in consumers.
- Adapt local generic and framework fixtures used by these paths. Domain D&D
normalizers can remain pending until their assigned migration stages.
**Acceptance:** All typed stage adapters have the core-owned route; deterministic
generic modules produce once, and no configured assessment is duplicated outside it.
**Checks:** `go test ./internal/modules/generic/merge/appendorder ./internal/modules/generic/normalize/noop`
and focused runner operation/typed resolution tests.
## Stage 9 — Wire Chunk Planning And Migrate D&D Scenes
**Status:** Complete. Chunk-plan, generic unit, scene, and pilot checks pass.
Unmigrated D&D extractors, normalizers, and assembled fixtures remain deferred
to their assigned work and cutover.
**Goal:** Include plan production without making scenes a core concept.
**Inspect:** `contracts/contracts.go`, `pipeline/{chunker_registry,runner_chunk_plan}.go`,
generic unit chunking, D&D scene chunking, plan materialization, and plan cache tests.
**Work:**
- Move chunker invocation to preparation consumed by the same core executor.
The framework still materializes/validates generic plans before assessing chunks.
- Migrate generic unit chunking as deterministic preparation and D&D scene planning
as native preparation. Preserve plan annotations, source order/coverage checks,
identity, and the existing supported whole-source fallback.
- Return actionable interpretation guidance when a scene response cannot yet
produce a materializable candidate; do not assess nonexistent chunks.
- Keep plan cache decoding/rematerialization current-source-aware and native-only;
preserve no semantic reassessment on hits and accepted correction writes.
- Adapt chunker/direct-call fixtures and remove their integration-owned acceptance
assembly. Do not add scene metadata to generic source contracts.
**Acceptance:** Deterministic and model-assisted planning share core disposition
while preserving their distinct production paths. Invalid generic plans still fail
at the appropriate boundary; no new chunk topology is promised.
**Checks:** `go test ./internal/modules/generic/chunk/units ./internal/modules/dnd/chunk/scenes`
and chunk-plan/materialization/cache tests in `./internal/framework/pipeline`.
## Stage 10 — Migrate Combat-Gated Extraction And Its No-Model Paths
**Status:** Complete. Both focused extractor suites pass, including configured
assessment and cache-free no-model branches. Other extractors and normalizers
remain assigned to their respective migrations.
**Goal:** Prove no-model completion is a prepared operation, not a helper choice.
**Inspect:** `dnd/extract/combatturns` and `dnd/extract/enemyevents`, their
operation-registry input handling, and default registration/capability tests.
**Work:**
- Migrate both extractors to native preparation for applicable chunks and a
deterministic candidate for their existing non-combat branches.
- Remove calls to direct assessment/outcome helpers, stored producer engines,
and manually assembled producer outcomes. Core performs configured assessment
once even when no model call is needed.
- Retain combat gating, contextual registry resolution, identities, endpoint
canonicalization, correction guidance, family fallback, and explicit selections.
- Exercise both branches through core with a native provider fake. A no-model
branch consumes no provider call and adds no synthetic cache entry.
**Acceptance:** Empty non-combat output is still subject to the configured chain;
the migration does not invent combat classifications or silently skip assessment.
**Check:** `go test ./internal/modules/dnd/extract/combatturns ./internal/modules/dnd/extract/enemyevents`.
## Stage 11 — Migrate The Three Registry Extractors
**Status:** Complete. All three focused extractor suites pass. Occurrence and
scene extractors, D&D normalizers, and assembled fixtures remain scheduled.
**Goal:** Move canonical noun extraction to domain-only preparation.
**Inspect:** `dnd/extract/{npcregistry,itemregistry,locationregistry}`, their typed
response interpretation/identity helpers, tests, and D&D registration.
**Work:**
- Return prepared native requests/evaluations with the convenient correction
binding and existing fallback algorithms. Remove module-owned execution and
terminal result composition and unused engine constructor dependencies.
- Preserve each registry's extraction scope, exact naming/identity behavior,
source resolution, nil/empty output, and external/generated reference handling.
- Retain native prompt IDs/static dependencies and schema selection. This is not
a prompt rewrite or domain scope expansion.
- Adapt direct-call tests to core and keep independent family output expectations.
**Acceptance:** All registry extractors use the pilot's lifecycle without forcing
their domain preparation into one configurable D&D extractor engine.
**Check:** `go test ./internal/modules/dnd/extract/npcregistry ./internal/modules/dnd/extract/itemregistry ./internal/modules/dnd/extract/locationregistry`.
## Stage 12 — Migrate The Three Occurrence Extractors
**Status:** Complete. Focused occurrence suites pass, including generated
registry handoff through registered typed execution. Remaining unmigrated
integrations and fixtures are addressed in subsequent stages.
**Goal:** Preserve contextual selections and domain feedback at the new boundary.
**Inspect:** `dnd/extract/{npcoccurrences,itemoccurrences,locationoccurrences}`,
their registry projections/resolvers, and current fallback/correction tests.
**Work:**
- Migrate preparation, native interpretation, correction, and fallback for all
three. Keep request-local/domain contextual selection and deterministic durable
ID attachment; do not expose opaque application IDs to the model.
- Replace returned candidate/guidance tuples with explicit evaluations. Preserve
the meaning of correctable selection errors versus ordinary preparation errors.
- Retain item holder/kind compatibility, location disambiguation, source ranges,
registry lookup precedence, and family-specific diagnostics.
- Exercise occurrence preparation with generated references via the typed route;
direct tests use the shared core entry point, not a module executor wrapper.
**Acceptance:** Occurrence modules contain domain interpretation rather than
acceptance state, and no registry-specific concepts leak into ordinary core.
**Check:** `go test ./internal/modules/dnd/extract/npcoccurrences ./internal/modules/dnd/extract/itemoccurrences ./internal/modules/dnd/extract/locationoccurrences`.
## Stage 13 — Migrate Scene Extraction And Two Deterministic Normalizers
**Status:** Complete. The focused suites and core pipeline tests pass, including
scene cache reuse against the current chunk and one-shot combat validation.
Other legacy callers remain deferred to the cutover.
**Goal:** Finish model extraction and cover non-registry normalization examples.
**Inspect:** `dnd/extract/scenedescriptions`, `dnd/normalize/scenedescriptions`,
`dnd/normalize/spells`, and scene/combat semantic validator registration.
**Work:**
- Migrate scene description extraction to prepared model work and explicit
evaluations. Preserve deterministic scene identity/range attachment, actual
fallback support, and both configured deterministic and one-shot model checks.
- Adapt scene-description and spell normalization to deterministic preparation,
retaining the existing transformation, diagnostic, cloning, and intrinsic checks.
- Do not promote optional shape validation into stricter codec acceptance or
redesign scene-domain rule ownership as an incidental part of this migration.
- Keep the combat semantic validator a one-shot native assessor using Stage 2's
check; it does not invoke the producer executor or semantic correction loop.
**Acceptance:** All ten baseline extractors have migrated; these deterministic
normalizers receive one core assessment and retain existing output semantics.
**Check:** `go test ./internal/modules/dnd/extract/scenedescriptions ./internal/modules/dnd/normalize/scenedescriptions ./internal/modules/dnd/normalize/spells ./internal/modules/dnd/validate/scenedescriptions/combat_semantics`.
## Stage 14 — Adapt The Remaining Deterministic D&D Normalizers
**Status:** Complete. All five focused normalizer suites pass through core
operation execution; semantic registry normalizers remain scheduled below.
**Goal:** Finish the mechanical deterministic contract migration.
**Inspect:** `dnd/normalize/{combatturns,enemyevents,npcoccurrences,itemoccurrences,locationoccurrences}`
and their typed registration and regression fixtures.
**Work:**
- Return deterministic prepared candidates plus domain diagnostics and existing
supported fallback behavior where applicable. Core owns assessment/disposition.
- Keep domain transformation bodies intact unless the new boundary requires a
small adjustment. Preserve exact duplicate rules, ordering/ties, references,
identity resolution, unknown values, and nil/present-empty storage behavior.
- Adapt constructor/registration and direct test entry points, not expected
domain output. Do not fold the audit's sort/dedup/shape refactors into this step.
**Acceptance:** Every deterministic lane module now fits core preparation without
model machinery. Registry semantic normalization remains for Stages 15–19.
**Check:** Run the five focused `dnd/normalize` packages above; rerun generic
append-order/noop tests if shared adaptation helpers change. This is one prompt
for repetitive signature/adaptor work, not five new domain algorithms.
## Stage 15 — Build Shared Reconciliation Preparation
**Status:** Complete. Synthetic preparation and core pipeline tests pass.
The contracts package's legacy fixture implementations do not compile after
the interface migration and remain deferred to the cutover; proposal evaluation
and production adapters remain scheduled below.
**Goal:** Give families one typed entry into reconciliation without execution glue.
**Inspect:** `semanticreconcile/{preparation,requests,application,proposal}.go`,
all three normalizer procedures, and Stage 1's typed reconciliation sketch.
**Work:**
- Add a focused facility that constructs a core operation using existing neutral
preparation. Accept fixed original records, domain candidate projection,
native prompt selections, typed family application/diagnostic functions, and
existing supported fallback construction.
- Retain original merged fallback inputs separately from deterministically
preprocessed records. Prepare handles/windows/material once per operation.
- Centralize insufficient-candidate/no-model and preparation-limit decisions;
return their typed operation variants, not calls to core terminal helpers.
Ordinary projection/preparation errors still propagate.
- Supply initial native requests and correction builders from retained preparation;
preserve candidate-number range and namespace guidance. Share standard original/
preparation evidence with lazy construction when disabled.
- Exercise the facility with a small synthetic record family before migrating
production families. Do not add NPC/item/location switches or imports.
**Acceptance:** Families can describe reconciliation preparation without choosing
an assessor, cache, terminal helper, or native execution path. Existing limits
and their meaning remain unchanged.
**Check:** `go test ./internal/framework/semanticreconcile` and relevant contracts
tests. Model evaluation/application lifecycle is completed in Stage 16.
## Stage 16 — Centralize Reconciliation Evaluation And Terminal Projection
**Status:** Complete. Synthetic native lifecycle tests cover proposal
replacement, safe partial output, failed correction, deterministic findings,
and preparation-limit fallback. Reconciliation and pipeline suites pass;
production family adapters remain scheduled below.
**Goal:** Replace duplicated current-proposal bookkeeping with typed evaluations.
**Inspect:** Proposal safety/application APIs, all three family interpretation/
finish/fallback closures, core evaluation replacement, and evidence support.
**Work:**
- Implement proposal decoding/safety assessment and a typed application callback
in the facility. Apply each complete proposal afresh to fixed originals; retain
safe groups and all affected originals according to existing application policy.
- Construct one typed reconciliation evaluation holding candidate, issues,
application omissions, family findings, and ordered guidance. Translate it to
the common core view without putting family data in core fields.
- Project final domain diagnostics from the same evaluation and core disposition.
Preserve no-model base findings, final safe-partial warnings, and original-input
fallback when no evaluation is eligible. Do not carry findings/omission counts
from a superseded or failed correction into final output.
- Centralize standard proposal/application evidence and result assembly. Families
retain semantic guidance, domain warning meaning, and fallback validation.
- Add focused synthetic lifecycle coverage for proposal replacement rather than
union, omitted safe groups, no-model/limit, and invalidation before correction.
Use the same core executor with native fakes; do not create another turn loop.
**Acceptance:** The facility owns lifecycle state and families supply typed policy.
Its current evaluation and native capture are separate; domain diagnostics are
about the final value, while historical proposal evidence remains available.
**Check:** `go test ./internal/framework/semanticreconcile ./internal/framework/pipeline`.
## Stage 17 — Migrate NPC Registry Normalization
**Status:** Complete. The NPC registry normalizer uses shared reconciliation
preparation and its focused semantic and deterministic tests pass. Item and
location adapters remain scheduled below.
**Goal:** Establish the first production reconciliation adapter.
**Inspect:** `dnd/normalize/npcregistry/{normalizer,semantic_normalizer_test}.go`,
NPC identity, application, evidence, and normalization-result helpers.
**Work:**
- Replace the repeated native/no-model/limit/finish procedure with the shared
reconciliation operation builder. Keep NPC record preprocessing/projection,
canonical naming/identity, typed group application, and fallback validation local.
- Translate neutral issues and final typed application data into the existing
family guidance/diagnostics through a D&D-local adapter where genuinely shared.
- Remove engine storage and mutable proposal/findings state from the normalizer.
Core chooses fallback and the facility projects current evaluation diagnostics.
- Adapt semantic tests and registration to the core route; retain independent
expectations for safe aliases, invalid/overlapping groups, retained candidates,
fresh application, no-model output, and qualified fallback.
**Acceptance:** The normalizer reads primarily as NPC domain policy. A failed
later response cannot recover an earlier proposal's output or findings.
**Check:** `go test ./internal/modules/dnd/normalize/npcregistry`.
## Stage 18 — Migrate Item Registry Normalization
**Status:** Complete. Item reconciliation uses the shared facility; focused
tests pass for currency compatibility, proposal replacement, fallback, and
evaluation evidence. Location reconciliation remains scheduled below.
**Goal:** Exercise richer compatibility and omission guidance without family switches.
**Inspect:** `dnd/normalize/itemregistry`, currency compatibility/application
helpers, and the item tests for independent safe groups and all omission counts.
**Work:**
- Migrate to the same reconciliation facility. Preserve exact preprocessing,
same-denomination currency aliases, incompatibility with other denominations/
non-currency items, evidence unions, and deterministic item identity.
- Return currency rejection guidance and omission details in the typed evaluation;
retain family diagnostic classification and supported fallback construction.
- Exercise a later proposal replacing earlier safe groups, native/correction
failure clearing candidate details, and accepted versus final fallback output.
Reuse core coverage where it already protects generic lifecycle behavior.
- Remove the local no-model/limit/finish choreography, stored engine, and parallel
`findings`/`advisories`/`discardedGroups`/`omissionDetails` state.
**Acceptance:** Item-specific compatibility stays typed and local; generic core
does not learn currency or reuse stale omissions. No new permissive fallback
eligibility is introduced.
**Check:** `go test ./internal/modules/dnd/normalize/itemregistry`.
## Stage 19 — Migrate Location Registry Normalization
**Status:** Complete. All three registry normalizer suites and shared D&D
diagnostics tests pass. Location identity and anchor policy remain family-owned;
equivalent fallback diagnostic translation is shared.
**Goal:** Complete production reconciliation and preserve location distinctions.
**Inspect:** `dnd/normalize/locationregistry`, location identity/anchor handling,
and tests for same-named locations, nesting, exact duplicates, and unsafe proposals.
**Work:**
- Replace lifecycle glue with the shared operation facility. Retain typed location
preprocessing, anchor/identity semantics, candidate eligibility, evidence,
safe application, and intrinsic fallback checks.
- Keep same-named but distinct places separate under the existing rules. Do not
reduce this family to NPC/item name identity to fit a shared helper.
- Use typed evaluation data for final findings/omissions and preserve no-model
and limit handling through core. Remove old engine/lifecycle state.
- Compare the three adapters after migration. Extract only genuinely equivalent
D&D diagnostic translation; revise the facility if family switches or repeated
framework coordination have appeared instead of hiding those differences.
**Acceptance:** All three registry normalizers share lifecycle code, retain their
independent domain expectations, and use the same core execution path as extraction.
**Check:** `go test ./internal/modules/dnd/normalize/locationregistry`
and the three registry-normalization packages together.
## Stage 20 — Complete The Cutover And Remove Superseded Plumbing
**Status:** Complete. Legacy producer execution and request/result wrappers
are removed; remaining fixtures use core operations. The specified framework,
module, CLI, and preflight checks pass, and all repository packages compile.
The one-shot combat semantic validator remains the intentional native caller.
**Goal:** Remove the old authoring recipe and finish remaining callers.
**Inspect:** The Stage 1 caller checklist; all production registrars; pipeline,
CLI, preflight, generic, and contracts test fixtures; generated handoff and reuse tests.
**Work:**
- Finish remaining programmatic/test callers of the changed stage interfaces.
Remove obsolete public lifecycle fields, helper wrappers, outcome-specializing
adapters, and module-side executor selection. Useful assessment/cache/capture
helpers can remain internal. Do not retain an obsolete recipe for tests alone.
- Verify registered extraction, merge, normalization, and chunk preparation all
reach the same executor; prepare-time exact-type/construction failures still
precede input parsing. Keep module keys, profiles/static dependencies, and
complete maintained example configurations valid.
- Review all remaining domain calls to producer/outcome helpers and engine
execution. Producers should prepare; the one-shot validator remains intentional.
Search results are review aids, not a test forbidding native types in modules.
**Acceptance:** No obsolete production authoring path remains. The entire
repository compiles again. Resolve every earlier deferred migration repair before
proceeding, except documentation work assigned below. The next stage verifies
assembled behavior rather than making compatibility wrappers for failing fixtures.
**Checks:** `go test ./internal/framework/... ./internal/modules/... ./internal/cli ./internal/preflight`.
## Stage 21 — Verify Cross-Boundary And Concurrent Execution
**Status:** Complete. The specified framework, module, CLI, and preflight
suite passes, as do focused pipeline and reconciliation race checks. Existing
assembled recovery, handoff, capture, admission, and worker tests were reviewed;
a synchronized native-operation test covers concurrent evaluation isolation.
**Goal:** Establish behavior where correctness spans the new owners.
**Inspect:** Core executor and stage adapters; existing pipeline worker, operation,
cache, capture, generated-handoff, CLI recovery, and native admission tests.
**Work:**
- Run representative assembled tests for full assessment/final turns, native
history and explicit selections, interpretation-only guidance, cache hits and
corrected writes, failed refresh, fallback-tainted generated consumers, and
required capture failure. Preserve partial output/error behavior already owned
by the runner/CLI; do not silently undertake deferred diagnostic-finalization work.
- Reuse worker/admission tests for concurrent operation-state isolation, bounded
jobs, cancellation/draining, and nested validation on a capacity-one backend.
Add controlled synchronization only where the new boundary lacks protection.
- Inspect gaps introduced by moving ownership. Retain one common lifecycle test
owner and representative family expectations; remove redundant legacy mock
choreography only after its meaningful behavioral protection is retained.
**Acceptance:** Domain results, source handling, independent observations,
fallbacks, and reuse behave as selected;
concurrent operations cannot accidentally reuse another operation's evaluation.
Assembled tests verify behavior at the new boundary without adding an exhaustive
cross-product or reimplementing upstream structural repair tests.
**Checks:** `go test ./internal/framework/... ./internal/modules/... ./internal/cli ./internal/preflight`
and `go test -race ./internal/framework/pipeline ./internal/framework/semanticreconcile`.
## Stage 22 — Provide The Working Author Example And Internal Guides
**Goal:** Make the new boundary usable without reading producer implementation.
**Inspect:** Stage 1's non-D&D sketches, actual finished APIs, and current
`docs/internal/{modules,pipeline,dnd,llm,state,overview}.md`.
**Work:**
- Finish one minimal domain-neutral working example, preferably an external
package test fixture under the framework with a real registrar/codec and a
local provider fake. Keep it reusable by the tests instead of creating a new
production demo command. Use generic text/metadata/chunks, not D&D conventions.
- Demonstrate preparation and execution, contextual domain interpretation, a
correction binding, and deterministic/no-model completion. The email/NWS
sketches must expose no forced scene/combat/registry assumptions; only one
concrete introductory example is needed. Point to a migrated registry for
richer reconciliation rather than duplicating it in the example.
- Rewrite Module Internals' recipe for core-owned preparation. Cover required
versus optional behavior, direct callers, ordinary errors versus domain
guidance/limits, supported fallback, evaluation lifetime, concurrency, and
evidence ownership. Link the tested example and real production adapters.
- Update Pipeline/D&D Internals and affected overview/LLM/state descriptions to
match the actual owners. Identify engine/capture/cache construction rather than
documenting upstream library features; link pinned native documentation for them.
- Document actual shared-instance/input/hook lifetimes without promising every
supplied writer/observer is thread-safe or installing blanket locks. No external
author study, readability gate, or new documentation test framework is needed.
**Acceptance:** The introductory example executes through registration and core,
not a private producer import. Documentation presents one current recipe, with
domain-specific policy owned by families and volatile details in canonical homes.
**Checks:** Run the package test containing the example; verify local links and
API references against source. Run affected example/config loading tests if changed.
## Stage 23 — Record Ownership And Reassess Overlapping Audit Findings
**Goal:** Bring architectural guidance and audit status in line with the result.
**Inspect:** Architecture policy, ADR-0022 and related ADR status links,
`audit/{catalog,discussion}.md`, and completed implementation/test evidence.
**Work:**
- Add the next sequential ADR (currently 0026) for core-invoked preparation,
core-owned operation lifecycle, explicit evaluations, and focused reconciliation.
Explain the integration boundary and why helper-only cleanup was insufficient.
- Update ADR-0022's status/navigation only to identify the narrow supersession
of module-composed producer mechanics. Retain its accepted body and unaffected
native continuation, assessment, guidance, and terminal policy decisions.
- Update architecture policy's concrete ownership description, including the
expanded neutral reconciliation responsibility. Preserve fixed stages, kit
ownership, ordinary error behavior, and selected acceptance/reuse contracts.
Do not turn new helper signatures or private representation into invariants.
Update its local last-updated date; retain the adopted upstream baseline.
- Reassess CAT-007, CAT-015, and CAT-016 with source/test links. Qualify partial
progress on CAT-003/006/008/009/014/017/018/022/023/024/025/032 where relevant;
do not mark entire findings resolved merely because nearby code moved.
- Update catalog summary/status wording and discussion Item 5's implementation
status to agree with the evidence. Keep original audit reports as historical
evidence, preserve unrelated outstanding entries and CAT-034's resolved status.
Do not implement the remaining audit in this step or retire its evidence.
**Acceptance:** Architectural rationale and current guidance agree; the catalog
accurately describes what this sprint did and did not address. No broader
restrictions or guarantees have been introduced through documentation or tests.
**Checks:** Review changed ADR/status links and documentation links; compare
catalog resolutions to actual tests and code, not just the migration inventory.
## Stage 24 — Perform Final Sprint Acceptance
**Goal:** Establish that the target architecture is complete and ready for review.
**Work:**
- Run the checks below, fixing sprint regressions at their owning boundary.
Rerun any focused checks deferred because of the intermediate interface cutover.
- Review the caller checklist against current source: ten baseline extractors,
scene planning, three semantic registry normalizers, deterministic modules,
typed registration/preparation, direct callers, and the one-shot validator.
Additional discovered callers also require a documented disposition.
- Trace one extraction, one no-model operation, scene-plan correction, and
reconciliation end to end. Confirm that integrations no longer choose the
shared lifecycle and that native validation/admission remain upstream-owned.
- Verify one convenient and one custom correction path; final-evaluation
diagnostics; no stale candidate on failed corrections; current-source reuse;
fallback disclosure/ineligibility; required evidence and supplied observation;
and the tested non-D&D author example. Prefer existing sufficient behavioral
tests to additional matrices or private-structure assertions.
- Review diffs for unintended schema/config/CLI/output changes, new restrictions,
fallback eligibility changes, weakened optional checks, and out-of-scope audit
work. Keep only changes needed for the selected boundary and identified bugfix.
- Report checks performed, unresolved implementation defects if any, and remaining
audit work. Completion requires no known unfinished item from this plan. Do not
tag/release, push, or delete planning documents as part of acceptance.
**Commands:**
```sh
go test ./...
go vet ./...
go build ./cmd/notarius
go test -race ./internal/framework/pipeline ./internal/framework/semanticreconcile ./internal/modules/dnd/validate/scenedescriptions/combat_semantics
git diff --check
```
The ordinary build can leave an ignored root binary; do not stage generated
artifacts. Check maintained example loading, native prompt dependency preflight,
and CLI recovery/report behavior through their existing offline tests. Inspect
documentation links manually or with available repository checks; do not add a
new tooling dependency solely for this sprint.
**Acceptance:** Full offline tests, vet, build, and focused race checks pass;
the author-facing API, production callers, documentation, and catalog agree.
The target is established by implementation and behavioral evidence, not by
smaller files, fewer callbacks, or an unchanged happy-path output alone.
## Open Questions
None. Scope and policy choices are settled in the feature roadmap. Stage 1
selects concrete Go signatures using the prescribed ownership and representative
callers; that is bounded implementation design, not an unresolved product decision.