336 lines
14 KiB
Go
336 lines
14 KiB
Go
// Package itemregistry normalizes merged D&D item-registry candidates conservatively.
|
|
package itemregistry
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"reflect"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/framework/semanticreconcile"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
|
itemcodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/itemregistry"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/items/identity"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
|
|
)
|
|
|
|
const (
|
|
Key = "dnd/item-registry"
|
|
PromptID = "notarius/dnd.item_registry.normalize"
|
|
CorrectionPromptID = "notarius/dnd.item_registry.normalize.repair"
|
|
|
|
ReasonCodeItemFieldsNormalized = "item_fields_normalized"
|
|
ReasonCodeItemIDRecomputed = "item_id_recomputed"
|
|
ReasonCodeSourceReferencesNormalized = "source_references_normalized"
|
|
ReasonCodeDuplicateItemCollapsed = "duplicate_item_collapsed"
|
|
ReasonCodeItemSemanticProposalInvalid = "item_semantic_proposal_invalid"
|
|
ReasonCodeItemSemanticReconciliationExhausted = "item_semantic_reconciliation_exhausted"
|
|
)
|
|
|
|
var requiredCapabilities = []string{"merged"}
|
|
var providedCapabilities = []string{"normalized"}
|
|
|
|
var _ contracts.Normalizer[dnd.ItemRegistry] = (*Normalizer)(nil)
|
|
|
|
type Options struct{}
|
|
|
|
type Normalizer struct{}
|
|
|
|
func New(_ Options) (*Normalizer, error) {
|
|
return &Normalizer{}, nil
|
|
}
|
|
|
|
func (n *Normalizer) Key() string { return Key }
|
|
func (n *Normalizer) ReferenceSlots() []contracts.ReferenceSlot { return nil }
|
|
|
|
type reconciliationFindings struct {
|
|
observations []diagnostics.Finding
|
|
advisories []diagnostics.Finding
|
|
}
|
|
|
|
func (n *Normalizer) PrepareNormalize(ctx context.Context, req contracts.NormalizeInput[dnd.ItemRegistry]) (contracts.PreparedOperation[dnd.ItemRegistry], error) {
|
|
if n == nil {
|
|
return nil, normalizerErrorf("normalizer must not be nil")
|
|
}
|
|
if ctx == nil {
|
|
return nil, normalizerErrorf("context must not be nil")
|
|
}
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, normalizerErrorf("context error before normalize: %w", err)
|
|
}
|
|
if req.Source == nil {
|
|
return nil, normalizerErrorf("source document must not be nil")
|
|
}
|
|
|
|
merged := cloneRegistry(req.MergeOutput.Value)
|
|
order := shared.NewSourceRefOrder(req.Source)
|
|
records, baseFindings := preprocessRecords(merged, order)
|
|
var envelopes []semanticreconcile.Record[dnd.Item]
|
|
input := semanticreconcile.OperationInput[dnd.ItemRegistry, normalizedRecord, reconciliationFindings]{
|
|
Source: req.Source, Original: merged, Deterministic: recordList(records), BaseFindings: reconciliationFindings{observations: 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 nil, normalizerErrorf("prepare semantic reconciliation inputs: %w", err)
|
|
}
|
|
return candidates, nil
|
|
},
|
|
Apply: func(_ context.Context, plan semanticreconcile.Plan, records []normalizedRecord) (semanticreconcile.Application[dnd.ItemRegistry, reconciliationFindings], error) {
|
|
applied, findings, advisories, rejected, err := applyReconciliationPlan(plan, records, envelopes, order)
|
|
if err != nil {
|
|
return semanticreconcile.Application[dnd.ItemRegistry, reconciliationFindings]{}, normalizerErrorf("apply semantic reconciliation plan: %w", err)
|
|
}
|
|
result := semanticreconcile.Application[dnd.ItemRegistry, reconciliationFindings]{Value: recordList(applied),
|
|
Findings: reconciliationFindings{observations: append(append([]diagnostics.Finding(nil), baseFindings...), findings...), advisories: advisories}, OmittedGroups: rejected}
|
|
if rejected > 0 {
|
|
result.Guidance = []string{"Consolidate currency only with aliases of the same denomination; keep different denominations separate and do not combine currency with non-currency items."}
|
|
result.OmissionDetails = []string{"currency may only be consolidated with aliases of one denomination"}
|
|
}
|
|
return result, nil
|
|
},
|
|
Fallback: func(_ context.Context, original dnd.ItemRegistry, final *semanticreconcile.Evaluation[dnd.ItemRegistry, reconciliationFindings]) (dnd.ItemRegistry, error) {
|
|
value := cloneRegistry(original)
|
|
if final != nil {
|
|
value = cloneRegistry(final.Candidate)
|
|
}
|
|
if err := validateFallback(value, req.Source); err != nil {
|
|
return dnd.ItemRegistry{}, err
|
|
}
|
|
return value, nil
|
|
},
|
|
Diagnostics: func(final *semanticreconcile.Evaluation[dnd.ItemRegistry, reconciliationFindings], outcome contracts.ProducerOutcome) ([]contracts.ProducerDiagnostic, error) {
|
|
var findings reconciliationFindings
|
|
discarded := -1
|
|
var details []string
|
|
if final != nil {
|
|
findings, discarded, details = final.Findings, final.OmittedGroups, append([]string(nil), final.OmissionDetails...)
|
|
}
|
|
result, err := normalizationDiagnostics(findings.observations, findings.advisories)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if outcome.Disposition == contracts.ProducerFallback {
|
|
details = append(details, outcome.FallbackReason)
|
|
groups, err := diagnostics.Collect([]diagnostics.Finding{diagnostics.ReconciliationFallback("items", ReasonCodeItemSemanticReconciliationExhausted, discarded, details...)}, contracts.DiagnosticDispositionWarning, contracts.DiagnosticCategoryFallback)
|
|
if err != nil {
|
|
return nil, normalizerErrorf("collect fallback diagnostic: %w", err)
|
|
}
|
|
result = append(result, groups...)
|
|
}
|
|
return result, nil
|
|
},
|
|
}
|
|
return semanticreconcile.PrepareOperation(input)
|
|
}
|
|
|
|
// validateFallback checks the durable artifact and the identity/source invariants
|
|
// used by registry consumers, not the configured ordinary validator chain.
|
|
func validateFallback(value dnd.ItemRegistry, document *source.SourceDocument) error {
|
|
if _, err := itemcodec.New().Encode(value); err != nil {
|
|
return normalizerErrorf("construct item fallback: %w", err)
|
|
}
|
|
if issues := identity.ValidateList(value); len(issues) > 0 {
|
|
return normalizerErrorf("construct item fallback: registry identity is not usable downstream")
|
|
}
|
|
index := source.NewDocumentIndex(document)
|
|
for _, item := range value.Items {
|
|
for _, reference := range item.SourceRefs {
|
|
if err := index.ValidateRef(reference); err != nil {
|
|
return normalizerErrorf("construct item fallback: %w", err)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func cloneRegistry(value dnd.ItemRegistry) dnd.ItemRegistry {
|
|
if value.Items == nil {
|
|
return dnd.ItemRegistry{}
|
|
}
|
|
result := dnd.ItemRegistry{Items: make([]dnd.Item, len(value.Items))}
|
|
for i, item := range value.Items {
|
|
result.Items[i] = cloneItem(item)
|
|
}
|
|
return result
|
|
}
|
|
|
|
func normalizationDiagnostics(findings, advisoryFindings []diagnostics.Finding) ([]contracts.ProducerDiagnostic, error) {
|
|
groups, err := diagnostics.Collect(findings, contracts.DiagnosticDispositionObservation, contracts.DiagnosticCategoryNormalization)
|
|
if err != nil {
|
|
return nil, normalizerErrorf("collect normalization diagnostics: %w", err)
|
|
}
|
|
advisoryGroups, err := diagnostics.Collect(advisoryFindings, contracts.DiagnosticDispositionAdvisory, contracts.DiagnosticCategoryDataQuality)
|
|
if err != nil {
|
|
return nil, normalizerErrorf("collect data-quality diagnostics: %w", err)
|
|
}
|
|
return append(groups, advisoryGroups...), nil
|
|
}
|
|
|
|
type normalizedRecord struct {
|
|
item dnd.Item
|
|
inputIndexes []int
|
|
earliest int
|
|
}
|
|
|
|
func preprocessRecords(input dnd.ItemRegistry, order shared.SourceRefOrder) ([]normalizedRecord, []diagnostics.Finding) {
|
|
if input.Items == nil {
|
|
return nil, nil
|
|
}
|
|
records := make([]normalizedRecord, len(input.Items))
|
|
findings := make([]diagnostics.Finding, 0)
|
|
for index, inputItem := range input.Items {
|
|
item, fieldsChanged, refsChanged := normalizeRecord(inputItem, order)
|
|
records[index] = normalizedRecord{item: item, inputIndexes: []int{index}, earliest: index}
|
|
if fieldsChanged {
|
|
findings = append(findings, diagnostics.Finding{Scope: itemScope(index), ReasonCode: ReasonCodeItemFieldsNormalized, Message: fmt.Sprintf("input index %d: item name normalized for %s", index, diagnostics.Quote(inputItem.Name))})
|
|
}
|
|
if refsChanged {
|
|
findings = append(findings, diagnostics.Finding{Scope: itemScope(index), ReasonCode: ReasonCodeSourceReferencesNormalized, Message: fmt.Sprintf("input index %d: source references normalized (original count %d, final count %d)", index, len(inputItem.SourceRefs), len(item.SourceRefs))})
|
|
}
|
|
if inputItem.ID != item.ID {
|
|
findings = append(findings, diagnostics.Finding{Scope: itemScope(index), ReasonCode: ReasonCodeItemIDRecomputed, Message: fmt.Sprintf("input index %d: item ID recomputed from %s", index, diagnostics.Quote(item.Name))})
|
|
}
|
|
}
|
|
groups := comparisonNameGroups(records)
|
|
output := make([]normalizedRecord, 0, len(groups))
|
|
for _, members := range groups {
|
|
retained := cloneRecord(records[members[0]])
|
|
for _, member := range members[1:] {
|
|
retained.item.SourceRefs = append(retained.item.SourceRefs, records[member].item.SourceRefs...)
|
|
retained.inputIndexes = append(retained.inputIndexes, records[member].inputIndexes...)
|
|
}
|
|
retained.item.SourceRefs = order.Canonicalize(retained.item.SourceRefs)
|
|
retained.item.ID = identity.DeriveID(retained.item.Name)
|
|
retained.inputIndexes = sortedUniqueIndexes(retained.inputIndexes)
|
|
output = append(output, retained)
|
|
if len(members) > 1 {
|
|
findings = append(findings, duplicateFinding(retained.earliest, memberInputIndexes(records, members[1:])))
|
|
}
|
|
}
|
|
return output, findings
|
|
}
|
|
|
|
func normalizeRecord(input dnd.Item, order shared.SourceRefOrder) (dnd.Item, bool, bool) {
|
|
output := cloneItem(input)
|
|
output.Name = identity.NormalizeDisplay(input.Name)
|
|
output.SourceRefs = order.Canonicalize(input.SourceRefs)
|
|
output.ID = identity.DeriveID(output.Name)
|
|
return output, input.Name != output.Name, !reflect.DeepEqual(input.SourceRefs, output.SourceRefs)
|
|
}
|
|
|
|
func comparisonNameGroups(records []normalizedRecord) [][]int {
|
|
groups := make([][]int, 0, len(records))
|
|
groupPositions := make(map[string]int, len(records))
|
|
for index, record := range records {
|
|
key := identity.ComparisonKey(record.item.Name)
|
|
if groupIndex, found := groupPositions[key]; found {
|
|
groups[groupIndex] = append(groups[groupIndex], index)
|
|
continue
|
|
}
|
|
groupPositions[key] = len(groups)
|
|
groups = append(groups, []int{index})
|
|
}
|
|
return groups
|
|
}
|
|
|
|
func cloneItem(input dnd.Item) dnd.Item {
|
|
input.SourceRefs = cloneSourceRefs(input.SourceRefs)
|
|
return input
|
|
}
|
|
func cloneRecord(input normalizedRecord) normalizedRecord {
|
|
input.item = cloneItem(input.item)
|
|
input.inputIndexes = append([]int(nil), input.inputIndexes...)
|
|
return input
|
|
}
|
|
func cloneSourceRefs(input []source.SourceRef) []source.SourceRef {
|
|
return append([]source.SourceRef(nil), input...)
|
|
}
|
|
|
|
func sortedUniqueIndexes(indexes []int) []int {
|
|
if len(indexes) == 0 {
|
|
return nil
|
|
}
|
|
out := append([]int(nil), indexes...)
|
|
sort.Ints(out)
|
|
write := 1
|
|
for _, index := range out[1:] {
|
|
if index != out[write-1] {
|
|
out[write] = index
|
|
write++
|
|
}
|
|
}
|
|
return out[:write]
|
|
}
|
|
func memberInputIndexes(records []normalizedRecord, members []int) []int {
|
|
indexes := make([]int, 0, len(members))
|
|
for _, member := range members {
|
|
indexes = append(indexes, records[member].inputIndexes...)
|
|
}
|
|
return sortedUniqueIndexes(indexes)
|
|
}
|
|
func recordValues(records []normalizedRecord) []dnd.Item {
|
|
if records == nil {
|
|
return nil
|
|
}
|
|
values := make([]dnd.Item, len(records))
|
|
for index, record := range records {
|
|
values[index] = cloneItem(record.item)
|
|
}
|
|
return values
|
|
}
|
|
func recordList(records []normalizedRecord) dnd.ItemRegistry {
|
|
if records == nil {
|
|
return dnd.ItemRegistry{}
|
|
}
|
|
return dnd.ItemRegistry{Items: recordValues(records)}
|
|
}
|
|
|
|
func duplicateFinding(retainedIndex int, removed []int) diagnostics.Finding {
|
|
const maxDisplayedIndices = 20
|
|
displayed := removed
|
|
if len(displayed) > maxDisplayedIndices {
|
|
displayed = displayed[:maxDisplayedIndices]
|
|
}
|
|
indices := make([]string, len(displayed))
|
|
for index, removedIndex := range displayed {
|
|
indices[index] = strconv.Itoa(removedIndex)
|
|
}
|
|
message := fmt.Sprintf("retained input index %d; removed input indices [%s]", retainedIndex, strings.Join(indices, ", "))
|
|
if omitted := len(removed) - len(displayed); omitted > 0 {
|
|
message += fmt.Sprintf("; %d additional removed input indices omitted", omitted)
|
|
}
|
|
return diagnostics.Finding{Scope: itemScope(retainedIndex), ReasonCode: ReasonCodeDuplicateItemCollapsed, Message: message}
|
|
}
|
|
func itemScope(index int) string { return fmt.Sprintf("items[%d]", index) }
|
|
|
|
func ModuleSpec() pipeline.ModuleSpec {
|
|
return pipeline.ModuleSpec{Key: Key, Stage: pipeline.StageNormalize, ExecutionClass: contracts.ExecutionClassLLMBacked, Prompts: []string{PromptID, CorrectionPromptID}, Requires: append([]string(nil), requiredCapabilities...), Provides: append([]string(nil), providedCapabilities...), ArtifactKind: dnd.ItemRegistryKind}
|
|
}
|
|
func Register(registry *pipeline.NormalizerRegistry) error {
|
|
return pipeline.RegisterNormalizerBuilder(registry, ModuleSpec(), validateOptions, func(request pipeline.BuildRequest) (contracts.Normalizer[dnd.ItemRegistry], error) {
|
|
options, err := DecodeOptions(request.Options)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return New(options)
|
|
})
|
|
}
|
|
func validateOptions(options map[string]any) error { _, err := DecodeOptions(options); return err }
|
|
func DecodeOptions(options map[string]any) (Options, error) {
|
|
if err := pipeline.RejectUnknownOptions(options); err != nil {
|
|
return Options{}, normalizerErrorf("%w", err)
|
|
}
|
|
return Options{}, nil
|
|
}
|
|
func normalizerErrorf(format string, args ...any) error {
|
|
return fmt.Errorf("dnd item registry normalizer: "+format, args...)
|
|
}
|