Migrate combat turns to native correction and retain deterministic scene gating
This commit is contained in:
@@ -2,7 +2,6 @@ package combatturns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
@@ -14,7 +13,6 @@ import (
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
npccodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/npcregistry"
|
||||
scenecodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/scenedescriptions"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/npcs/identity"
|
||||
)
|
||||
|
||||
func TestExtractMapsAndOrdersCombatTurnsBySourcePosition(t *testing.T) {
|
||||
@@ -54,12 +52,11 @@ func TestExtractMapsAndOrdersCombatTurnsBySourcePosition(t *testing.T) {
|
||||
t.Fatalf("LLM calls = %d, want one call per chunk", len(client.requests))
|
||||
}
|
||||
request := client.requests[0]
|
||||
if request.StageName != Key || request.PromptID != PromptID || request.PromptVersion != SchemaVersion || request.SessionID != "session-123" || request.ProfileID != "profile-combat" {
|
||||
t.Fatalf("LLM request identity = %#v", request)
|
||||
if request.Prompt.SessionID != "session-123" {
|
||||
t.Fatal("session selection lost")
|
||||
}
|
||||
transcript := request.Inputs["transcript"]
|
||||
if transcript.Name != "transcript" || transcript.MediaType != "application/json" || transcript.Digest != "sha256:chunk" || transcript.OriginURI != "file:///session-alpha.json" || !reflect.DeepEqual(transcript.Content, extractionRequest(t).Chunk.Content) {
|
||||
t.Fatalf("transcript input = %#v, want chunk-scoped source input", transcript)
|
||||
if !reflect.DeepEqual(renderedInput(t, request, "transcript"), extractionRequest(t).Chunk.Content) {
|
||||
t.Fatal("chunk-scoped transcript changed")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,38 +134,26 @@ func TestExtractPassesReferencesAndNPCGroundingWithoutUsingItAsEvidence(t *testi
|
||||
if _, err := newExtractor(t, client, references).Extract(context.Background(), req); err != nil {
|
||||
t.Fatalf("Extract() error = %v, want nil", err)
|
||||
}
|
||||
inputs := client.requests[0].Inputs
|
||||
if string(inputs["players"].Content) != "Alice: Aria" || string(inputs["party"].Content) != "Aria: cleric" || string(inputs["glossary"].Content) != "ogre: a large foe" {
|
||||
t.Fatalf("reference inputs = %#v, want configured references", inputs)
|
||||
}
|
||||
registryInput := inputs[NPCRegistryReferenceSlot]
|
||||
if registryInput.Name != NPCRegistryReferenceSlot || registryInput.MediaType != "application/json" || !strings.Contains(string(registryInput.Content), "Mira Thorn") {
|
||||
t.Fatalf("NPC registry input = %#v, want canonical registry grounding", registryInput)
|
||||
}
|
||||
if strings.Contains(string(inputs["transcript"].Content), "Aria: cleric") {
|
||||
t.Fatal("transcript input contains reference content")
|
||||
}
|
||||
if _, ok := inputs[SceneDescriptionReferenceSlot]; ok {
|
||||
t.Fatalf("prompt inputs include scene descriptions: %#v", inputs)
|
||||
}
|
||||
|
||||
metadata := newExtractor(t, &fakeCombatTurnsLLMClient{}, references).ManifestMetadata()
|
||||
if metadata["npc_count"] != 1 || !strings.HasPrefix(metadata["npc_registry_digest"].(string), "sha256:") {
|
||||
t.Fatalf("bound registry metadata = %#v, want digest and count", metadata)
|
||||
messages := client.requests[0].Prompt.Messages
|
||||
var all string
|
||||
for _, message := range messages {
|
||||
all += message.Content
|
||||
}
|
||||
if metadata["scene_description_count"] != 1 || !strings.HasPrefix(metadata["scene_eligibility_digest"].(string), "sha256:") {
|
||||
t.Fatalf("bound scene metadata = %#v, want digest and count", metadata)
|
||||
for _, material := range []string{"Alice: Aria", "Aria: cleric", "ogre: a large foe"} {
|
||||
if strings.Count(all, material) != 1 {
|
||||
t.Fatalf("campaign input not rendered once: %q", material)
|
||||
}
|
||||
}
|
||||
fingerprints := newExtractor(t, &fakeCombatTurnsLLMClient{}, references).CheckpointFingerprints()
|
||||
if len(fingerprints) != 6 || fingerprints[3].Name != "scene_gate_policy" || fingerprints[4].Name != "npc_registry" || fingerprints[5].Name != "scene_eligibility" {
|
||||
t.Fatalf("bound fingerprints = %#v, want local identities plus scene gate and NPC registry", fingerprints)
|
||||
input := renderedInput(t, client.requests[0], NPCRegistryReferenceSlot)
|
||||
if string(input) != `{"npcs":[{"name":"Mira Thorn"}]}` {
|
||||
t.Fatalf("NPC grounding=%s", input)
|
||||
}
|
||||
encoded, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
if strings.Contains(string(renderedInput(t, client.requests[0], "transcript")), "Aria: cleric") {
|
||||
t.Fatal("campaign context became evidence")
|
||||
}
|
||||
if strings.Contains(string(encoded), "Mira Thorn") || strings.Contains(string(encoded), "session-alpha") {
|
||||
t.Fatalf("metadata leaked content: %s", encoded)
|
||||
if strings.Contains(all, "Combat eligibility") || strings.Contains(all, "A valid scene description") {
|
||||
t.Fatal("eligibility prose became model input")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,16 +163,8 @@ func TestExtractUnboundRegistryUsesExactEmptyPromptAndOmitsIdentity(t *testing.T
|
||||
if _, err := extractor.Extract(context.Background(), extractionRequest(t)); err != nil {
|
||||
t.Fatalf("Extract() error = %v, want nil", err)
|
||||
}
|
||||
input := client.requests[0].Inputs[NPCRegistryReferenceSlot]
|
||||
if string(input.Content) != `{"npcs":[]}` || input.Digest == "" || input.OriginURI != "" {
|
||||
t.Fatalf("unbound registry input = %#v, want exact empty prompt without identity", input)
|
||||
}
|
||||
metadata := extractor.ManifestMetadata()
|
||||
if _, ok := metadata["npc_registry_digest"]; ok {
|
||||
t.Fatalf("unbound metadata has registry digest: %#v", metadata)
|
||||
}
|
||||
if fingerprints := extractor.CheckpointFingerprints(); len(fingerprints) != 6 || fingerprints[4].Name != "npc_registry" || fingerprints[4].Value != input.Digest || fingerprints[5].Name != "scene_eligibility" || fingerprints[5].Value == "" {
|
||||
t.Fatalf("unbound fingerprints = %#v, want empty-projection identity", fingerprints)
|
||||
if input := renderedInput(t, client.requests[0], NPCRegistryReferenceSlot); string(input) != `{"npcs":[]}` {
|
||||
t.Fatalf("unbound registry=%s", input)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,12 +180,8 @@ func TestExtractorResolvesOperationNPCOverrideWithoutSingletonMetadata(t *testin
|
||||
if _, err := extractor.Extract(context.Background(), request); err != nil {
|
||||
t.Fatalf("Extract() error = %v", err)
|
||||
}
|
||||
input := client.requests[0].Inputs[NPCRegistryReferenceSlot]
|
||||
if input.Digest == "" || string(input.Content) != `{"npcs":[{"name":"Mira Thorn"}]}` || input.OriginURI != "" {
|
||||
t.Fatalf("operation NPC input = %#v, want generated canonical grounding without provenance", input)
|
||||
}
|
||||
if metadata := extractor.ManifestMetadata(); metadata["npc_registry_digest"] != nil || metadata["npc_count"] != nil || metadata["scene_eligibility_digest"] != nil || metadata["scene_description_count"] != nil {
|
||||
t.Fatalf("singleton metadata = %#v, want no operation-varying NPC identity", metadata)
|
||||
if input := renderedInput(t, client.requests[0], NPCRegistryReferenceSlot); string(input) != `{"npcs":[{"name":"Mira Thorn"}]}` {
|
||||
t.Fatalf("generated grounding=%s", input)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,38 +293,6 @@ func TestExtractAppliesSceneEligibilityBeforePromptConstruction(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSceneEligibilityMetadataAndFingerprintsTrackGatingValues(t *testing.T) {
|
||||
chunk := extractionRequest(t).Chunk
|
||||
base := sceneDescription(chunk, dnd.SceneKindCombat)
|
||||
baseExtractor := newExtractor(t, &fakeCombatTurnsLLMClient{}, sceneListReferences(t, base))
|
||||
metadata := baseExtractor.ManifestMetadata()
|
||||
if metadata["scene_gate_policy"] != sceneGatePolicy || metadata["scene_description_count"] != 1 {
|
||||
t.Fatalf("metadata = %#v, want scene gate policy and count", metadata)
|
||||
}
|
||||
baseDigest := fingerprintValue(t, baseExtractor.CheckpointFingerprints(), "scene_eligibility")
|
||||
proseChanged := base
|
||||
proseChanged.Title = "Different title"
|
||||
proseChanged.Summary = "Different summary."
|
||||
if got := fingerprintValue(t, newExtractor(t, &fakeCombatTurnsLLMClient{}, sceneListReferences(t, proseChanged)).CheckpointFingerprints(), "scene_eligibility"); got != baseDigest {
|
||||
t.Fatalf("prose-only eligibility digest = %q, want %q", got, baseDigest)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
change func(*dnd.SceneDescription)
|
||||
}{
|
||||
{"kind", func(value *dnd.SceneDescription) { value.Kind = dnd.SceneKindNarrative }},
|
||||
{"range", func(value *dnd.SceneDescription) { value.SourceRef.StartUnitID = 3 }},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
changed := base
|
||||
test.change(&changed)
|
||||
if got := fingerprintValue(t, newExtractor(t, &fakeCombatTurnsLLMClient{}, sceneListReferences(t, changed)).CheckpointFingerprints(), "scene_eligibility"); got == baseDigest {
|
||||
t.Fatal("eligibility digest did not change")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRejectsMalformedNPCRegistryBeforeLLMCallWithoutContent(t *testing.T) {
|
||||
client := &fakeCombatTurnsLLMClient{}
|
||||
references := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
@@ -360,7 +301,7 @@ func TestNewRejectsMalformedNPCRegistryBeforeLLMCallWithoutContent(t *testing.T)
|
||||
Items: []contracts.ReferenceItem{{SlotName: NPCRegistryReferenceSlot, MediaType: "application/json", Content: []byte(`{"secret":"private transcript detail"}`)}},
|
||||
},
|
||||
}}
|
||||
_, err := New(client, Options{}, references)
|
||||
_, err := New(newExtractor(t, client).engine, Options{}, references)
|
||||
if err == nil || !strings.Contains(err.Error(), "prepare NPC registry") || strings.Contains(err.Error(), "private transcript detail") {
|
||||
t.Fatalf("New() error = %v, want bounded content-free registry failure", err)
|
||||
}
|
||||
@@ -377,7 +318,7 @@ func TestNewRejectsInvalidSceneReferenceBeforeLLMCallWithoutContent(t *testing.T
|
||||
Items: []contracts.ReferenceItem{{SlotName: SceneDescriptionReferenceSlot, MediaType: scenecodec.MediaType, Content: []byte(`{"scenes":[]}`)}},
|
||||
},
|
||||
}}
|
||||
_, err := New(client, Options{}, references)
|
||||
_, err := New(newExtractor(t, client).engine, Options{}, references)
|
||||
if err == nil || !strings.Contains(err.Error(), "prepare scene eligibility") || strings.Contains(err.Error(), `{"scenes":[]}`) {
|
||||
t.Fatalf("New() error = %v, want bounded content-free scene failure", err)
|
||||
}
|
||||
@@ -394,11 +335,11 @@ func TestExtractRejectsInvalidRequestsAndWrapsProviderFailures(t *testing.T) {
|
||||
name string
|
||||
extractor *Extractor
|
||||
ctx context.Context
|
||||
req contracts.TypedExtractionRequest
|
||||
req contracts.TypedExtractionRequest[dnd.CombatTurnList]
|
||||
want string
|
||||
}{
|
||||
{name: "nil extractor", extractor: nilExtractor, ctx: context.Background(), req: validReq, want: "extractor"},
|
||||
{name: "nil LLM client", extractor: &Extractor{}, ctx: context.Background(), req: validReq, want: "LLM client"},
|
||||
{name: "nil LLM client", extractor: &Extractor{}, ctx: context.Background(), req: validReq, want: "native engine"},
|
||||
{name: "wrapped preflight failure", extractor: validExtractor, ctx: context.Background(), req: mismatchedSourceInputRequest(validReq), want: "must match chunk"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
@@ -415,40 +356,10 @@ func TestExtractRejectsInvalidRequestsAndWrapsProviderFailures(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractorManifestMetadataAndFingerprints(t *testing.T) {
|
||||
extractor := newExtractor(t, &fakeCombatTurnsLLMClient{})
|
||||
metadata := extractor.ManifestMetadata()
|
||||
for key, want := range map[string]string{
|
||||
"prompt_id": PromptID, "prompt_version": SchemaVersion, "mapping_policy": mappingPolicy,
|
||||
"response_schema_key": string(ResponseSchemaKey), "response_schema_id": ResponseSchemaID,
|
||||
"response_schema_name": ResponseSchemaName, "response_schema_version": SchemaVersion,
|
||||
} {
|
||||
if metadata[key] != want {
|
||||
t.Fatalf("metadata[%q] = %#v, want %q", key, metadata[key], want)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"prompt_sha256", "response_schema_sha256"} {
|
||||
value, ok := metadata[key].(string)
|
||||
if !ok || !strings.HasPrefix(value, "sha256:") {
|
||||
t.Fatalf("metadata[%q] = %#v, want digest", key, metadata[key])
|
||||
}
|
||||
}
|
||||
wantNames := map[string]struct{}{"prompt": {}, "response_schema": {}, "mapping_policy": {}, "scene_gate_policy": {}, "npc_registry": {}, "scene_eligibility": {}}
|
||||
for _, fingerprint := range extractor.CheckpointFingerprints() {
|
||||
if _, ok := wantNames[fingerprint.Name]; !ok {
|
||||
t.Fatalf("unexpected fingerprint = %#v", fingerprint)
|
||||
}
|
||||
delete(wantNames, fingerprint.Name)
|
||||
}
|
||||
if len(wantNames) != 0 {
|
||||
t.Fatalf("missing fingerprints = %#v", wantNames)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModuleSpecAndRegistration(t *testing.T) {
|
||||
wantSlots := referenceSlots()
|
||||
got := ModuleSpec()
|
||||
if got.Key != Key || got.Stage != pipeline.StageExtract || got.CorrectionProtocol != contracts.CorrectionProtocolSingleResponseV1 || got.ArtifactKind != dnd.CombatTurnListKind || !reflect.DeepEqual(got.Requires, []string{"chunks", "source.transcript"}) || !reflect.DeepEqual(got.Provides, []string{"dnd.combat_turns"}) || !reflect.DeepEqual(got.ReferenceSlots, wantSlots) {
|
||||
if got.Key != Key || got.Stage != pipeline.StageExtract || !reflect.DeepEqual(got.Prompts, []string{PromptID, CorrectionPromptID}) || got.ArtifactKind != dnd.CombatTurnListKind || !reflect.DeepEqual(got.Requires, []string{"chunks", "source.transcript"}) || !reflect.DeepEqual(got.Provides, []string{"dnd.combat_turns"}) || !reflect.DeepEqual(got.ReferenceSlots, wantSlots) {
|
||||
t.Fatalf("ModuleSpec() = %#v, want combat extractor contract", got)
|
||||
}
|
||||
got.Requires[0] = "changed"
|
||||
@@ -469,142 +380,3 @@ func TestModuleSpecAndRegistration(t *testing.T) {
|
||||
t.Fatalf("registry missing spec for %q", Key)
|
||||
}
|
||||
}
|
||||
|
||||
func extractionRequest(t *testing.T) contracts.TypedExtractionRequest {
|
||||
t.Helper()
|
||||
doc := combatSourceDocument()
|
||||
chunk := &source.Chunk{
|
||||
ID: "session-alpha:chunk:0",
|
||||
SourceID: doc.ID,
|
||||
Index: 0,
|
||||
Ref: source.SourceRef{SourceID: doc.ID, StartUnitID: 2, EndUnitID: 10},
|
||||
Content: []byte(`{"units":[10,2]}`),
|
||||
MediaType: "application/json",
|
||||
Units: append([]source.SourceUnit(nil), doc.Units...),
|
||||
}
|
||||
request := contracts.TypedExtractionRequest{
|
||||
Source: doc,
|
||||
Chunk: chunk,
|
||||
SourceInput: contracts.NewLLMInputMaterial("source", chunk.MediaType, chunk.Content, "sha256:chunk", "file:///session-alpha.json"),
|
||||
SessionID: "session-123",
|
||||
LLMProfile: "profile-combat",
|
||||
}
|
||||
request.References = sceneReferences(t, chunk, dnd.SceneKindCombat)
|
||||
return request
|
||||
}
|
||||
|
||||
func combatSourceDocument() *source.SourceDocument {
|
||||
return &source.SourceDocument{
|
||||
ID: "session-alpha", Kind: "transcript", Format: "application/vnd.seriatim.minimal+json", Digest: "sha256:source",
|
||||
Units: []source.SourceUnit{
|
||||
{ID: 10, Kind: "transcript_segment", Text: "Aria reacts and strikes the ogre.", Ref: source.SourceRef{SourceID: "session-alpha", StartUnitID: 10, EndUnitID: 10}},
|
||||
{ID: 2, Kind: "transcript_segment", Text: "Borin retreats from the ogre.", Ref: source.SourceRef{SourceID: "session-alpha", StartUnitID: 2, EndUnitID: 2}},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func mismatchedSourceInputRequest(req contracts.TypedExtractionRequest) contracts.TypedExtractionRequest {
|
||||
req.SourceInput = contracts.NewLLMInputMaterial("source", "application/json", []byte(`{"other":true}`), "sha256:other", "")
|
||||
return req
|
||||
}
|
||||
|
||||
func newExtractor(t *testing.T, client contracts.StructuredLLMClient, references ...contracts.ReferenceSet) *Extractor {
|
||||
t.Helper()
|
||||
extractor, err := New(client, Options{}, references...)
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
return extractor
|
||||
}
|
||||
|
||||
func npcRegistryJSON(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
value := dnd.NPCRegistry{NPCs: []dnd.NPC{{ID: identity.DeriveID("Mira Thorn"), Name: "Mira Thorn", SourceRefs: []source.SourceRef{{SourceID: "other-session", StartUnitID: 1, EndUnitID: 1}}}}}
|
||||
content, err := npccodec.New().Encode(value)
|
||||
if err != nil {
|
||||
t.Fatalf("encode NPC registry: %v", err)
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
func sceneReferences(t *testing.T, chunk *source.Chunk, kind dnd.SceneKind) contracts.ReferenceSet {
|
||||
t.Helper()
|
||||
return sceneListReferences(t, sceneDescription(chunk, kind))
|
||||
}
|
||||
|
||||
func sceneListReferences(t *testing.T, scenes ...dnd.SceneDescription) contracts.ReferenceSet {
|
||||
t.Helper()
|
||||
content, err := scenecodec.New().Encode(dnd.SceneDescriptionList{Scenes: scenes})
|
||||
if err != nil {
|
||||
t.Fatalf("encode scene descriptions: %v", err)
|
||||
}
|
||||
return contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
SceneDescriptionReferenceSlot: {
|
||||
Slot: contracts.ReferenceSlot{Name: SceneDescriptionReferenceSlot},
|
||||
Items: []contracts.ReferenceItem{{SlotName: SceneDescriptionReferenceSlot, MediaType: scenecodec.MediaType, Content: content}},
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
func sceneDescription(chunk *source.Chunk, kind dnd.SceneKind) dnd.SceneDescription {
|
||||
return dnd.SceneDescription{
|
||||
ID: chunk.ID,
|
||||
SourceRef: chunk.Ref,
|
||||
Kind: kind,
|
||||
Title: "Combat eligibility",
|
||||
Summary: "A valid scene description for combat extraction.",
|
||||
}
|
||||
}
|
||||
|
||||
func fingerprintValue(t *testing.T, fingerprints []pipeline.CheckpointFingerprint, name string) string {
|
||||
t.Helper()
|
||||
for _, fingerprint := range fingerprints {
|
||||
if fingerprint.Name == name {
|
||||
return fingerprint.Value
|
||||
}
|
||||
}
|
||||
t.Fatalf("fingerprints = %#v, missing %q", fingerprints, name)
|
||||
return ""
|
||||
}
|
||||
|
||||
type fakeCombatTurnsLLMClient struct {
|
||||
response extractionResponse
|
||||
err error
|
||||
requests []contracts.StructuredCompletionRequest
|
||||
}
|
||||
|
||||
func (client *fakeCombatTurnsLLMClient) CompleteStructured(_ context.Context, req contracts.StructuredCompletionRequest, out any) (contracts.StructuredCompletionResponse, error) {
|
||||
client.requests = append(client.requests, cloneStructuredCompletionRequest(req))
|
||||
if client.err != nil {
|
||||
return contracts.StructuredCompletionResponse{}, client.err
|
||||
}
|
||||
target, ok := out.(*extractionResponse)
|
||||
if !ok {
|
||||
return contracts.StructuredCompletionResponse{}, errors.New("unexpected output target")
|
||||
}
|
||||
*target = client.response
|
||||
content, err := json.Marshal(client.response)
|
||||
if err != nil {
|
||||
return contracts.StructuredCompletionResponse{}, err
|
||||
}
|
||||
return contracts.StructuredCompletionResponse{Content: content}, nil
|
||||
}
|
||||
|
||||
func cloneStructuredCompletionRequest(req contracts.StructuredCompletionRequest) contracts.StructuredCompletionRequest {
|
||||
req.Inputs = req.Inputs.Clone()
|
||||
correction, err := contracts.CloneSemanticCorrection(req.Correction)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
req.Correction = correction
|
||||
if len(req.Vars) == 0 {
|
||||
req.Vars = nil
|
||||
return req
|
||||
}
|
||||
vars := make(map[string]any, len(req.Vars))
|
||||
for key, value := range req.Vars {
|
||||
vars[key] = value
|
||||
}
|
||||
req.Vars = vars
|
||||
return req
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user