Move NPC registry reconciliation into shared operations
This commit is contained in:
@@ -671,6 +671,10 @@ about the final value, while historical proposal evidence remains available.
|
||||
|
||||
## 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`,
|
||||
|
||||
@@ -18,7 +18,6 @@ import (
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/npcs/identity"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -40,146 +39,84 @@ var _ contracts.Normalizer[dnd.NPCRegistry] = (*Normalizer)(nil)
|
||||
|
||||
type Options struct{}
|
||||
|
||||
type Normalizer struct {
|
||||
engine *promptkit.Engine
|
||||
}
|
||||
type Normalizer struct{}
|
||||
|
||||
func New(engine *promptkit.Engine, _ Options) (*Normalizer, error) {
|
||||
if engine == nil {
|
||||
return nil, normalizerErrorf("native engine must not be nil")
|
||||
}
|
||||
return &Normalizer{engine: engine}, nil
|
||||
func New(_ Options) (*Normalizer, error) {
|
||||
return &Normalizer{}, nil
|
||||
}
|
||||
|
||||
func (n *Normalizer) Key() string { return Key }
|
||||
func (n *Normalizer) ReferenceSlots() []contracts.ReferenceSlot { return nil }
|
||||
|
||||
func (n *Normalizer) Normalize(ctx context.Context, req contracts.TypedNormalizeRequest[dnd.NPCRegistry]) (contracts.TypedNormalizeResult[dnd.NPCRegistry], error) {
|
||||
func (n *Normalizer) PrepareNormalize(ctx context.Context, req contracts.NormalizeInput[dnd.NPCRegistry]) (contracts.PreparedOperation[dnd.NPCRegistry], error) {
|
||||
if n == nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, normalizerErrorf("normalizer must not be nil")
|
||||
}
|
||||
if n.engine == nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, normalizerErrorf("native engine must not be nil")
|
||||
return nil, normalizerErrorf("normalizer must not be nil")
|
||||
}
|
||||
if ctx == nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, normalizerErrorf("context must not be nil")
|
||||
return nil, normalizerErrorf("context must not be nil")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, normalizerErrorf("context error before normalize: %w", err)
|
||||
return nil, normalizerErrorf("context error before normalize: %w", err)
|
||||
}
|
||||
if req.Source == nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, normalizerErrorf("source document must not be nil")
|
||||
return nil, normalizerErrorf("source document must not be nil")
|
||||
}
|
||||
|
||||
// Keep the already available merged artifact separate from preprocessed
|
||||
// originals. A failed native response must not recover an earlier proposal.
|
||||
merged := cloneRegistry(req.MergeOutput.Value)
|
||||
order := shared.NewSourceRefOrder(req.Source)
|
||||
records, baseFindings := preprocessRecords(merged, order)
|
||||
deterministic := recordList(records)
|
||||
if err := req.Operation.Execution.RecordEvidence("normalization/originals.json", deterministic); err != nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, err
|
||||
}
|
||||
findings := append([]diagnostics.Finding(nil), baseFindings...)
|
||||
discardedGroups := -1
|
||||
var omissionDetails []string
|
||||
|
||||
fallback := func(_ context.Context, final *dnd.NPCRegistry) (dnd.NPCRegistry, error) {
|
||||
value := cloneRegistry(merged)
|
||||
if final != nil {
|
||||
// Each interpreted candidate was built afresh from fixed original records,
|
||||
// using only the final proposal's compatible, non-overlapping safe groups.
|
||||
value = cloneRegistry(*final)
|
||||
} else {
|
||||
findings = nil
|
||||
discardedGroups = -1
|
||||
omissionDetails = nil
|
||||
}
|
||||
if err := validateFallback(value, req.Source); err != nil {
|
||||
return dnd.NPCRegistry{}, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
finish := func(value dnd.NPCRegistry, outcome contracts.ProducerOutcome, err error) (contracts.TypedNormalizeResult[dnd.NPCRegistry], error) {
|
||||
if err != nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, normalizerErrorf("normalize NPCs: %w", err)
|
||||
}
|
||||
result, err := normalizationResult(value, findings)
|
||||
if err != nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, err
|
||||
}
|
||||
result.Outcome = outcome
|
||||
if outcome.Disposition == contracts.ProducerFallback {
|
||||
details := append([]string(nil), omissionDetails...)
|
||||
details = append(details, outcome.FallbackReason)
|
||||
groups, err := diagnostics.Collect([]diagnostics.Finding{semanticFallbackFinding(discardedGroups, details...)}, contracts.DiagnosticDispositionWarning, contracts.DiagnosticCategoryFallback)
|
||||
var envelopes []semanticreconcile.Record[dnd.NPC]
|
||||
input := semanticreconcile.OperationInput[dnd.NPCRegistry, normalizedRecord, []diagnostics.Finding]{
|
||||
Source: req.Source, Original: merged, Deterministic: recordList(records), BaseFindings: baseFindings, Records: records,
|
||||
Limits: semanticreconcile.DefaultLimits(), PromptID: PromptID, CorrectionID: CorrectionPromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID,
|
||||
Project: func(records []normalizedRecord) ([]semanticreconcile.Candidate, error) {
|
||||
candidates, prepared, err := reconciliationInputs(records)
|
||||
envelopes = prepared
|
||||
if err != nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, normalizerErrorf("collect fallback diagnostic: %w", err)
|
||||
return nil, normalizerErrorf("prepare semantic reconciliation inputs: %w", err)
|
||||
}
|
||||
result.Diagnostics = append(result.Diagnostics, groups...)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
noModel := func() (contracts.TypedNormalizeResult[dnd.NPCRegistry], error) {
|
||||
value, outcome, err := pipeline.AssessProducer(ctx, req.Operation, deterministic, func(ctx context.Context) (dnd.NPCRegistry, error) { return fallback(ctx, nil) })
|
||||
return finish(value, outcome, err)
|
||||
}
|
||||
if len(records) < 2 {
|
||||
return noModel()
|
||||
}
|
||||
candidates, envelopes, err := reconciliationInputs(records)
|
||||
if err != nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, normalizerErrorf("prepare semantic reconciliation inputs: %w", err)
|
||||
}
|
||||
preparation, err := semanticreconcile.Prepare(req.Source, candidates, semanticreconcile.DefaultLimits())
|
||||
if err != nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, normalizerErrorf("prepare semantic reconciliation: %w", err)
|
||||
}
|
||||
if err := req.Operation.Execution.RecordEvidence("normalization/preparation.json", map[string]any{
|
||||
"disposition": preparation.Disposition(), "candidate_number_range": preparation.CandidateNumberRange(),
|
||||
"candidate_mappings": preparation.CandidateMappings(), "candidates": candidates,
|
||||
}); err != nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, err
|
||||
}
|
||||
switch preparation.Disposition() {
|
||||
case semanticreconcile.InsufficientCandidates:
|
||||
return noModel()
|
||||
case semanticreconcile.LimitExceeded:
|
||||
value, outcome, err := pipeline.FinishProducerFailure(ctx, req.Operation.Controls.Mode, normalizerErrorf("candidate set exceeded semantic reconciliation preparation limits"), func(ctx context.Context) (dnd.NPCRegistry, error) { return fallback(ctx, nil) })
|
||||
return finish(value, outcome, err)
|
||||
}
|
||||
initial, err := semanticreconcile.InitialRequest(preparation, PromptID, req.LLMProfile, req.SessionID)
|
||||
if err != nil {
|
||||
return contracts.TypedNormalizeResult[dnd.NPCRegistry]{}, normalizerErrorf("build native request: %w", err)
|
||||
}
|
||||
value, outcome, err := pipeline.RunProducer(ctx, n.engine, req.Operation, initial,
|
||||
func(_ context.Context, result *promptkit.RunResult) (*dnd.NPCRegistry, []string, error) {
|
||||
response, err := semanticreconcile.DecodeProposal(result.RawOutput)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
assessment := preparation.Assess(response)
|
||||
if err := req.Operation.Execution.RecordEvidence("normalization/proposals/"+result.RunID+".json", map[string]any{"proposal": response, "issues": assessment.Issues(), "discarded_group_count": assessment.DiscardedGroupCount()}); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
applied, semanticFindings, err := applyReconciliationPlan(assessment.Plan(), records, envelopes, order)
|
||||
if err != nil {
|
||||
return nil, nil, normalizerErrorf("apply semantic reconciliation plan: %w", err)
|
||||
}
|
||||
findings = append(append([]diagnostics.Finding(nil), baseFindings...), semanticFindings...)
|
||||
discardedGroups = assessment.DiscardedGroupCount()
|
||||
omissionDetails = semanticreconcile.IssueDetails(assessment.Issues())
|
||||
guidance, err := semanticreconcile.CorrectionDetails(assessment.Issues(), preparation.CandidateNumberRange())
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
candidate := recordList(applied)
|
||||
return &candidate, guidance, nil
|
||||
return candidates, nil
|
||||
},
|
||||
func(_ context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
return semanticreconcile.CorrectionRequest(CorrectionPromptID, req.LLMProfile, req.SessionID, guidance), nil
|
||||
}, fallback)
|
||||
return finish(value, outcome, err)
|
||||
Apply: func(_ context.Context, plan semanticreconcile.Plan, records []normalizedRecord) (semanticreconcile.Application[dnd.NPCRegistry, []diagnostics.Finding], error) {
|
||||
applied, findings, err := applyReconciliationPlan(plan, records, envelopes, order)
|
||||
if err != nil {
|
||||
return semanticreconcile.Application[dnd.NPCRegistry, []diagnostics.Finding]{}, normalizerErrorf("apply semantic reconciliation plan: %w", err)
|
||||
}
|
||||
return semanticreconcile.Application[dnd.NPCRegistry, []diagnostics.Finding]{Value: recordList(applied), Findings: append(append([]diagnostics.Finding(nil), baseFindings...), findings...)}, nil
|
||||
},
|
||||
Fallback: func(_ context.Context, original dnd.NPCRegistry, final *semanticreconcile.Evaluation[dnd.NPCRegistry, []diagnostics.Finding]) (dnd.NPCRegistry, error) {
|
||||
value := cloneRegistry(original)
|
||||
if final != nil {
|
||||
value = cloneRegistry(final.Candidate)
|
||||
}
|
||||
if err := validateFallback(value, req.Source); err != nil {
|
||||
return dnd.NPCRegistry{}, err
|
||||
}
|
||||
return value, nil
|
||||
},
|
||||
Diagnostics: func(final *semanticreconcile.Evaluation[dnd.NPCRegistry, []diagnostics.Finding], outcome contracts.ProducerOutcome) ([]contracts.ProducerDiagnostic, error) {
|
||||
var findings []diagnostics.Finding
|
||||
discarded := -1
|
||||
var details []string
|
||||
if final != nil {
|
||||
findings, discarded, details = final.Findings, final.OmittedGroups, append([]string(nil), final.OmissionDetails...)
|
||||
}
|
||||
result, err := normalizationResult(dnd.NPCRegistry{}, findings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if outcome.Disposition == contracts.ProducerFallback {
|
||||
details = append(details, outcome.FallbackReason)
|
||||
groups, err := diagnostics.Collect([]diagnostics.Finding{semanticFallbackFinding(discarded, details...)}, contracts.DiagnosticDispositionWarning, contracts.DiagnosticCategoryFallback)
|
||||
if err != nil {
|
||||
return nil, normalizerErrorf("collect fallback diagnostic: %w", err)
|
||||
}
|
||||
result.Diagnostics = append(result.Diagnostics, groups...)
|
||||
}
|
||||
return result.Diagnostics, nil
|
||||
},
|
||||
}
|
||||
return semanticreconcile.PrepareOperation(input)
|
||||
}
|
||||
|
||||
// validateFallback checks the durable artifact and the identity/source invariants
|
||||
@@ -404,7 +341,7 @@ func Register(registry *pipeline.NormalizerRegistry) error {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return New(request.Dependencies.Engine, options)
|
||||
return New(options)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -33,9 +33,6 @@ func TestModuleContractAndIdentity(t *testing.T) {
|
||||
if err := Register(registry); err != nil {
|
||||
t.Fatalf("Register() error = %v", err)
|
||||
}
|
||||
if _, err := New(nil, Options{}); err == nil {
|
||||
t.Fatal("New(nil, Options{}) error = nil, want nil native engine rejection")
|
||||
}
|
||||
spec := ModuleSpec()
|
||||
spec.Prompts[0] = "mutated"
|
||||
if !reflect.DeepEqual(ModuleSpec(), want) {
|
||||
@@ -132,7 +129,7 @@ func TestNormalizeHandlesNilAndCanceledCalls(t *testing.T) {
|
||||
}
|
||||
canceled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := normalizer.Normalize(canceled, normalizeRequest(dnd.NPCRegistry{})); err == nil || !strings.Contains(err.Error(), "context error") {
|
||||
if _, err := normalizer.Normalize(canceled, normalizeRequest(dnd.NPCRegistry{})); err == nil || !strings.Contains(err.Error(), "context canceled") {
|
||||
t.Fatalf("canceled Normalize() error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -168,7 +165,12 @@ func (c *recordingNPCNormalizerClient) Generate(ctx context.Context, request pro
|
||||
return &promptkit.GenerateResponse{Content: response}, nil
|
||||
}
|
||||
|
||||
func newNormalizer(t *testing.T, client promptkit.LLMClient) *Normalizer {
|
||||
type normalizerFixture struct {
|
||||
*Normalizer
|
||||
engine *promptkit.Engine
|
||||
}
|
||||
|
||||
func newNormalizer(t *testing.T, client promptkit.LLMClient) *normalizerFixture {
|
||||
t.Helper()
|
||||
type settings struct {
|
||||
PromptKit promptkit.Settings `yaml:"promptkit"`
|
||||
@@ -192,11 +194,20 @@ func newNormalizer(t *testing.T, client promptkit.LLMClient) *Normalizer {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
normalizer, err := New(engine, Options{})
|
||||
normalizer, err := New(Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return normalizer
|
||||
return &normalizerFixture{Normalizer: normalizer, engine: engine}
|
||||
}
|
||||
|
||||
func (fixture *normalizerFixture) Normalize(ctx context.Context, req contracts.TypedNormalizeRequest[dnd.NPCRegistry]) (pipeline.OperationResult[dnd.NPCRegistry], error) {
|
||||
op := req.Operation
|
||||
execution := pipeline.ExecutionContext[dnd.NPCRegistry]{Engine: fixture.engine, Controls: op.Controls, Assess: op.Assess, Execution: op.Execution, ReuseEligible: op.ReuseEligible, Cache: op.Cache}
|
||||
input := contracts.NormalizeInput[dnd.NPCRegistry]{Source: req.Source, LaneID: req.LaneID, MergeOutput: req.MergeOutput, SourceInput: req.SourceInput, SessionID: req.SessionID, References: req.References, LLMProfile: req.LLMProfile, Metadata: req.Metadata}
|
||||
return pipeline.ExecuteOperation(ctx, execution, func(ctx context.Context) (contracts.PreparedOperation[dnd.NPCRegistry], error) {
|
||||
return fixture.Normalizer.PrepareNormalize(ctx, input)
|
||||
})
|
||||
}
|
||||
|
||||
func renderedInput(t *testing.T, request promptkit.GenerateRequest, name string) []byte {
|
||||
|
||||
Reference in New Issue
Block a user