Exercise shared campaign and consumer workflows

This commit is contained in:
2026-11-30 02:29:50 +00:00
parent b5b4672920
commit 706c1bb7ad
26 changed files with 417 additions and 489 deletions

View File

@@ -799,6 +799,30 @@ creation on fully reused or plan-only invocations.
## Stage 22 — Prove the three-file workflow and real consumer boundaries ## Stage 22 — Prove the three-file workflow and real consumer boundaries
**Complete.** Commit: `Exercise shared campaign and consumer workflows`.
The synthetic reference data is copied from catalog commit `02dd53c6`; the
catalog compatibility entry point is committed there separately as `016473f`.
Offline `go test ./...` passed with Go 1.27.4, and the three-document onboarding
fixture passed with omitted and supplied inline content, controlled consumer
failure/retry, and prepared-input reuse. Existing assembled coverage exercises
installation and campaign templates and bounded workflows.
Controlled compatibility was run using the catalog script with local builds from
Audita v4.3.0 commit `6f97f31ccb1436c9b1e144182f6ad0b1fd9524be` and Notarius
v0.10.0 commit `752c9b44d2c0bb3bfb1e02a5d4379f7cc5b6261e`:
```sh
scripts/check-compatibility.sh /home/eric/Workspace/narratio \
/home/eric/.cache/narratio-roadmap-tmp/audita-v430 \
/tmp/narratio-notarius-v010 /home/eric/Workspace/notarius
```
The catalog, Audita shared-input inspection, positive and negative preflight,
processing, and ten-lane Notarius readiness and flat promotion checks passed.
The controlled Notarius provider observed 9, 0, and 9 calls for initial,
reused, and forced-refresh execution respectively. External binaries remain
opt-in and default tests require no paid provider or external executable.
**Read:** roadmap verification table and compatibility guidance. Entry points: **Read:** roadmap verification table and compatibility guidance. Entry points:
`internal/app/compatibility_test.go`, assembled workflow fixtures, existing `internal/app/compatibility_test.go`, assembled workflow fixtures, existing
Notarius integration tests, and the catalog compatibility script. Notarius integration tests, and the catalog compatibility script.

View File

@@ -0,0 +1,18 @@
# Synthetic three-file campaign example.
schema_version: maximumdirect.rpg.campaign.v1
id: lantern-coast
name: Lantern Coast expedition
setting: lantern_coast_sample
system: sample_magic
references:
party: ./party.yml
narratio:
inputs:
speakers_file: ./speakers.yml
glossary:
entries:
- id: glass-harbor
name: Glass Harbor
category: place
aliases: [The Harbor]
autocorrect: []

View File

@@ -0,0 +1,11 @@
schema_version: maximumdirect.rpg.party.v1
characters:
mira:
player:
name: Rowan
character:
name: Mira
aliases: [Mira of Glass Harbor]
classes:
- name: Wizard
level: 3

View File

@@ -0,0 +1,7 @@
match:
- speaker: Rowan
match:
- Rowan_recording
- speaker: GM
match:
- GM_recording

View File

@@ -1,5 +1,6 @@
schema_version: maximumdirect.rpg.campaign.v1
id: sample-campaign
config: config:
imports: imports:
- path: fragments/inputs.yml - path: fragments/inputs.yml
required: true required: true
campaign_id: sample-campaign

View File

@@ -1,7 +1,8 @@
session_template_file: ../session.template.yml references:
inputs: party: ../party.yml
speakers_file: ../speakers.yml narratio:
autocorrect_file: ../autocorrect.yml session_template_file: ../session.template.yml
glossary_file: ../glossary.yml inputs:
party_file: ../party.yml speakers_file: ../speakers.yml
spell_catalog_file: ../spell_catalog.json glossary_file: ../glossary.yml
autocorrect: []

View File

@@ -1,3 +1,5 @@
campaign: schema_version: maximumdirect.glossary.v1
entries: collections:
- {id: lantern_watch, name: Lantern Watch, category: organization} campaign:
entries:
- {id: lantern_watch, name: Lantern Watch, category: organization}

View File

@@ -1,7 +1,8 @@
# Inline records compose above the file using ConfigKit entry identities. # Inline records compose above the file using ConfigKit entry identities.
inputs: narratio:
glossary_file: ../glossary.yml inputs:
glossary: glossary_file: ../glossary.yml
instruction: Use established campaign terminology. glossary:
entries: instruction: Use established campaign terminology.
- {id: lantern_watch, name: Silver Watch, category: organization} entries:
- {id: lantern_watch, name: Silver Watch, category: organization}

View File

@@ -1,3 +1,4 @@
# Campaign inputs fragment; select the adjacent sample file when importing this fragment. # Campaign inputs fragment; select the adjacent sample file when importing this fragment.
inputs: narratio:
glossary_file: ../glossary.yml inputs:
glossary_file: ../glossary.yml

View File

@@ -1,5 +1,6 @@
# Campaign inputs fragment; include the required roster and other inputs separately. # Campaign inputs fragment; include the required roster and other inputs separately.
inputs: narratio:
glossary: inputs:
entries: glossary:
- {id: watch, name: Silver Watch, category: organization} entries:
- {id: watch, name: Silver Watch, category: organization}

View File

@@ -1,3 +1,5 @@
campaign: schema_version: maximumdirect.glossary.v1
entries: collections:
- {id: lantern_watch, name: Lantern Watch, category: organization} campaign:
entries:
- {id: lantern_watch, name: Lantern Watch, category: organization}

View File

@@ -15,29 +15,17 @@ notarius:
pipeline_id: dnd-session pipeline_id: dnd-session
timeout: 3h timeout: 3h
references: references:
glossary: narratio.input.glossary.campaign glossary: narratio.input.glossary.combined
party: narratio.input.party party: narratio.input.party
players: narratio.input.players players: narratio.input.players
spell_catalog: narratio.input.spell_catalog spell_catalog: narratio.input.glossary.combined
outputs: outputs:
npc_registry: npc_registry:
lane_id: npc-registry lane_id: npc-registry
media_type: application/json
schema_id: notarius.dnd.npc_registry
schema_version: v1
module_key: dnd/npc-registry
location_registry: location_registry:
lane_id: location-registry lane_id: location-registry
media_type: application/json
schema_id: notarius.dnd.location_registry
schema_version: v1
module_key: dnd/location-registry
scene_descriptions: scene_descriptions:
lane_id: scene-descriptions lane_id: scene-descriptions
media_type: application/json
schema_id: notarius.dnd.scene_descriptions
schema_version: v1
module_key: dnd/scene-descriptions
scriptorium: scriptorium:
binary: scriptorium binary: scriptorium

View File

@@ -34,12 +34,6 @@ campaigns:
# Optional command default when --campaign is omitted. # Optional command default when --campaign is omitted.
default_campaign_id: sample-campaign default_campaign_id: sample-campaign
spool:
# Optional; defaults to /var/spool/narratio.
root: /var/spool/narratio
# Optional cleanup of run-scoped spool audio after successful publish commit.
delete_audio_after_publish: false
publish: publish:
# Optional booleans; defaults are true. # Optional booleans; defaults are true.
enabled: true enabled: true
@@ -61,8 +55,7 @@ publish:
- source: narratio.artifact.player_handout - source: narratio.artifact.player_handout
dest: artifacts/player_handout.md dest: artifacts/player_handout.md
required: false required: false
# Extraction lanes publish only when named explicitly; the bundle and index # Extraction lanes publish only when named explicitly; the bundle stays local.
# are never implicit publish sources.
- source: narratio.extraction.npc_registry - source: narratio.extraction.npc_registry
dest: artifacts/extraction/npc-registry.json dest: artifacts/extraction/npc-registry.json
required: true required: true
@@ -141,82 +134,37 @@ notarius:
pipeline_id: dnd-session pipeline_id: dnd-session
timeout: 3h timeout: 3h
working_directory: /usr/local/etc/notarius working_directory: /usr/local/etc/notarius
# Reuse compatible accepted Notarius checkpoints during executed extraction. # Forced extraction requests refresh from Notarius.
# The Notarius config must enable recording and provide persistent cache roots. cache: auto
resume: true
# auto uses or creates a source-addressed chunk plan. Forced Narratio
# extraction overrides this with refresh and disables checkpoint loading.
chunk_cache: auto
# External campaign references use prepared Narratio source IDs. Omit an # External campaign references use prepared Narratio source IDs. Omit an
# optional binding when the selected Notarius pipeline does not need it. # optional binding when the selected Notarius pipeline does not need it.
references: references:
glossary: narratio.input.glossary.campaign glossary: narratio.input.glossary.combined
party: narratio.input.party party: narratio.input.party
players: narratio.input.players players: narratio.input.players
spell_catalog: narratio.input.spell_catalog spell_catalog: narratio.input.glossary.combined
# Each key creates source narratio.extraction.<key>. These constraints match # Each key creates source narratio.extraction.<key> for its selected lane.
# the current Notarius D&D lane contracts; update them with Notarius.
outputs: outputs:
item_registry: item_registry:
lane_id: item-registry lane_id: item-registry
media_type: application/json
schema_id: notarius.dnd.item_registry
schema_version: v1
module_key: dnd/item-registry
npc_registry: npc_registry:
lane_id: npc-registry lane_id: npc-registry
media_type: application/json
schema_id: notarius.dnd.npc_registry
schema_version: v1
module_key: dnd/npc-registry
location_registry: location_registry:
lane_id: location-registry lane_id: location-registry
media_type: application/json
schema_id: notarius.dnd.location_registry
schema_version: v1
module_key: dnd/location-registry
scene_descriptions: scene_descriptions:
lane_id: scene-descriptions lane_id: scene-descriptions
media_type: application/json
schema_id: notarius.dnd.scene_descriptions
schema_version: v1
module_key: dnd/scene-descriptions
item_occurrences: item_occurrences:
lane_id: item-occurrences lane_id: item-occurrences
media_type: application/json
schema_id: notarius.dnd.item_occurrences
schema_version: v1
module_key: dnd/item-occurrences
spells: spells:
lane_id: spells lane_id: spells
media_type: application/json
schema_id: notarius.dnd.spells
schema_version: v1
module_key: dnd/spells
combat_turns: combat_turns:
lane_id: combat-turns lane_id: combat-turns
media_type: application/json
schema_id: notarius.dnd.combat_turns
schema_version: v1
module_key: dnd/combat-turns
npc_occurrences: npc_occurrences:
lane_id: npc-occurrences lane_id: npc-occurrences
media_type: application/json
schema_id: notarius.dnd.npc_occurrences
schema_version: v1
module_key: dnd/npc-occurrences
location_occurrences: location_occurrences:
lane_id: location-occurrences lane_id: location-occurrences
media_type: application/json
schema_id: notarius.dnd.location_occurrences
schema_version: v1
module_key: dnd/location-occurrences
enemy_events: enemy_events:
lane_id: enemy-events lane_id: enemy-events
media_type: application/json
schema_id: notarius.dnd.enemy_events
schema_version: v1
module_key: dnd/enemy-events
scriptorium: scriptorium:
binary: scriptorium binary: scriptorium

View File

@@ -22,10 +22,6 @@ campaigns:
root: /usr/local/share/narratio/campaigns root: /usr/local/share/narratio/campaigns
default_campaign_id: sample-campaign default_campaign_id: sample-campaign
spool:
root: /var/spool/narratio
delete_audio_after_publish: true
publish: publish:
enabled: true enabled: true
upload_run: true upload_run: true

View File

@@ -3,7 +3,7 @@ character_items:
for_each: party.characters for_each: party.characters
prompt_id: dnd.character_items prompt_id: dnd.character_items
profile_id: production-placeholder profile_id: production-placeholder
output_path_pattern: artifacts/characters/{character_id}/items.md output_path_pattern: artifacts/{character_id}-items.md
inputs: inputs:
character_meta: character_meta:
source: narratio.member_artifact.character_meta source: narratio.member_artifact.character_meta
@@ -15,4 +15,4 @@ character_items:
publish: publish:
enabled: true enabled: true
required: false required: false
dest_pattern: artifacts/characters/{character_id}/items.md dest_pattern: artifacts/{character_id}-items.md

View File

@@ -3,7 +3,7 @@ character_meta:
for_each: party.characters for_each: party.characters
prompt_id: dnd.character_meta prompt_id: dnd.character_meta
profile_id: production-placeholder profile_id: production-placeholder
output_path_pattern: artifacts/characters/{character_id}/meta.md output_path_pattern: artifacts/{character_id}-meta.md
member_vars: member_vars:
character_id: character_id character_id: character_id
character_name: character.name character_name: character.name

View File

@@ -4,9 +4,3 @@ workspace:
campaigns: campaigns:
root: ../../campaigns root: ../../campaigns
default_campaign_id: sample-campaign default_campaign_id: sample-campaign
cache:
root: ./cache
spool:
root: ./spool

View File

@@ -1,5 +1,5 @@
reference_catalog: reference_catalog:
settings: settings:
lantern_coast: ./setting.yml lantern_coast_sample: ./setting.yml
systems: systems:
sample_magic: ./spells.yml sample_magic: ./spells.yml

View File

@@ -0,0 +1,7 @@
collections:
setting:
entries:
- id: harbor_crossing
name: Harbor Crossing
category: place
aliases: [The Crossing]

View File

@@ -0,0 +1,7 @@
collections:
spells:
entries:
- id: tide_step
name: Tide Step
category: spell
aliases: [Tidal Step]

View File

@@ -1,8 +1,16 @@
config: config:
imports: imports:
- path: fragments/places.yml - path: fragments/lantern-coast-places.yml
required: true required: true
setting: schema_version: maximumdirect.glossary.v1
instruction: Use the established place names. collections:
entries: setting:
- {id: coast, name: Lantern Coast, category: place} provenance:
id: lantern_coast_sample
title: Lantern Coast synthetic sample
license: CC0-1.0
entries:
- id: lantern_coast
name: Lantern Coast
category: place
description: A fictional coast in the sample setting.

View File

@@ -1,3 +1,16 @@
spells: config:
entries: imports:
- {id: glow, name: Lantern Glow, category: spell} - path: fragments/sample-spells.yml
required: true
schema_version: maximumdirect.glossary.v1
collections:
spells:
provenance:
id: sample_magic
title: Sample Magic synthetic sample
license: CC0-1.0
entries:
- id: lantern_glow
name: Lantern Glow
category: spell
description: A fictional light-producing spell.

View File

@@ -3,6 +3,7 @@ package app
import ( import (
"bytes" "bytes"
"context" "context"
"fmt"
"os" "os"
"path/filepath" "path/filepath"
"reflect" "reflect"
@@ -430,3 +431,104 @@ func loadAssembledManifest(t *testing.T, cfg *config.Config) *manifest.Manifest
func manifestPathForConfig(workspaceRoot string) string { func manifestPathForConfig(workspaceRoot string) string {
return artifacts.SessionManifestPathForCampaign(workspaceRoot, "sample-campaign", "2026-05-03") return artifacts.SessionManifestPathForCampaign(workspaceRoot, "sample-campaign", "2026-05-03")
} }
func TestThreeDocumentCampaignOnboarding(t *testing.T) {
for _, inline := range []bool{false, true} {
name := "defaults"
if inline {
name = "inline"
}
t.Run(name, func(t *testing.T) {
root := t.TempDir()
campaignDir := filepath.Join(root, "campaign")
example, err := filepath.Abs(filepath.Join("..", "..", "examples", "campaigns", "lantern-coast"))
if err != nil {
t.Fatal(err)
}
for _, name := range []string{"campaign.yml", "party.yml", "speakers.yml"} {
data, err := os.ReadFile(filepath.Join(example, name))
if err != nil {
t.Fatal(err)
}
if name == "campaign.yml" && !inline {
data = []byte(strings.Split(string(data), " glossary:")[0])
}
mustWriteTestFile(t, filepath.Join(campaignDir, name), string(data))
}
entries, err := os.ReadDir(campaignDir)
if err != nil || len(entries) != 3 {
t.Fatalf("campaign documents = %v, %v", entries, err)
}
catalog, err := filepath.Abs(filepath.Join("..", "..", "examples", "reference-catalog", "catalog.yml"))
if err != nil {
t.Fatal(err)
}
copyCatalog(t, filepath.Dir(catalog), filepath.Join(root, "catalog"))
catalog = "catalog/catalog.yml"
workspace := filepath.Join(root, "workspace")
pipeline := filepath.Join(root, "pipeline.yml")
mustWriteTestFile(t, pipeline, fmt.Sprintf("config:\n imports: [{path: %q}]\nworkspace: {root: %q}\nwhisperx: {transcribe_url: 'https://example.invalid/transcribe'}\n", catalog, workspace))
audio := filepath.Join(root, "audio")
mustWriteTestFile(t, filepath.Join(audio, "Rowan_recording.flac"), "synthetic audio")
session := filepath.Join(root, "session.yml")
campaign := filepath.Join(campaignDir, "campaign.yml")
var out, diagnostics bytes.Buffer
if code := executeForTest([]string{"session", "init", "2026-05-03", "--config", pipeline, "--campaign-file", campaign, "--output", session, "--audio-dir", audio}, &out, &diagnostics); code != 0 {
t.Fatalf("session init: %s", diagnostics.String())
}
cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{})
if err != nil {
t.Fatal(err)
}
prepare, err := stage.Select("prepare")
if err != nil {
t.Fatal(err)
}
if _, err := executeStages(context.Background(), cfg, []stage.Stage{prepare}, RunOptions{}); err != nil {
t.Fatal(err)
}
paths := artifacts.NewLocalStore(workspace).SessionPathsFor("lantern-coast", "2026-05-03")
for role, want := range map[string]string{"setting": "Harbor Crossing", "spells": "Tide Step", "party": "Mira"} {
data, err := os.ReadFile(filepath.Join(paths.InputsDir, "glossaries", role+".yml"))
if err != nil || !strings.Contains(string(data), want) {
t.Fatalf("%s glossary: %s %v", role, data, err)
}
}
data, err := os.ReadFile(filepath.Join(paths.InputsDir, "glossaries", "campaign.yml"))
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(data), "Glass Harbor") != inline {
t.Fatalf("inline glossary = %s", data)
}
m, err := (&manifest.LocalStore{}).Load(context.Background(), paths.ManifestPath)
if err != nil {
t.Fatal(err)
}
base := filepath.Join(paths.TranscriptsDir, "base.json")
mustWriteTestFile(t, base, `{"segments":[]}`)
setCurrentBuiltInEvidence(t, m, "merge", artifacts.TranscriptOutputKindBase, artifacts.ArtifactTranscriptBase, base)
m.RunID = "20260519T010203Z-a1b2c3d4"
fake := &audita.FakeRunner{Err: fmt.Errorf("controlled consumer failure")}
env := &stage.Env{Config: cfg, ArtifactStore: artifacts.NewLocalStore(workspace), Audita: fake}
polish, err := stage.Select("polish")
if err != nil {
t.Fatal(err)
}
if _, err := polish.Run(context.Background(), env, m); err == nil {
t.Fatal("controlled consumer failure was ignored")
}
fake.Err = nil
if _, err := polish.Run(context.Background(), env, m); err != nil {
t.Fatalf("consumer retry: %v", err)
}
if len(fake.Requests) != 2 || len(fake.Requests[1].GlossaryFiles) != 4 {
t.Fatalf("consumer inputs: %+v", fake.Requests)
}
again, err := executeStages(context.Background(), cfg, []stage.Stage{prepare}, RunOptions{})
if err != nil || len(again.Skipped) != 1 {
t.Fatalf("prepared input reuse: %+v %v", again, err)
}
})
}
}

View File

@@ -81,18 +81,19 @@ func TestReferenceCatalogCompatibility(t *testing.T) {
return path return path
} }
pipeline := write("pipeline.yml", fmt.Sprintf("config:\n imports:\n - path: catalog/catalog.yml\nworkspace: {root: %q}\nwhisperx: {transcribe_url: 'https://example.invalid/transcribe'}\n", workspace)) pipeline := write("pipeline.yml", fmt.Sprintf("config:\n imports:\n - path: catalog/catalog.yml\nworkspace: {root: %q}\nwhisperx: {transcribe_url: 'https://example.invalid/transcribe'}\n", workspace))
campaign := write("campaign.yml", `campaign_id: sample-campaign campaign := write("campaign.yml", `schema_version: maximumdirect.rpg.campaign.v1
inputs: id: sample-campaign
speakers_file: speakers.yml setting: lantern_coast_sample
autocorrect_file: autocorrect.yml system: sample_magic
party_file: party.yml references: {party: party.yml}
glossary_file: campaign-glossary.yml narratio:
setting: lantern_coast_sample inputs:
system: sample_magic speakers_file: speakers.yml
glossary: glossary_file: campaign-glossary.yml
entries: [{id: watch, name: Silver Watch, category: organization}] glossary:
entries: [{id: watch, name: Silver Watch, category: organization}]
`) `)
write("campaign-glossary.yml", "campaign:\n instruction: Preserve campaign names.\n entries: [{id: watch, name: Old Watch, category: organization}, {id: inn, name: Lantern Inn, category: place}]\n") write("campaign-glossary.yml", "schema_version: maximumdirect.glossary.v1\ncollections:\n campaign:\n instruction: Preserve campaign names.\n entries: [{id: watch, name: Old Watch, category: organization}, {id: inn, name: Lantern Inn, category: place}]\n")
write("speakers.yml", "alice: alice.flac\n") write("speakers.yml", "alice: alice.flac\n")
write("autocorrect.yml", "[]\n") write("autocorrect.yml", "[]\n")
write("party.yml", "schema_version: maximumdirect.rpg.party.v1\ncharacters:\n alice:\n player: {name: Player}\n character: {name: Alice, classes: [{name: wizard}]}\n") write("party.yml", "schema_version: maximumdirect.rpg.party.v1\ncharacters:\n alice:\n player: {name: Player}\n character: {name: Alice, classes: [{name: wizard}]}\n")
@@ -160,6 +161,7 @@ inputs:
func TestAuditaBinaryCompatibility(t *testing.T) { func TestAuditaBinaryCompatibility(t *testing.T) {
binary := externalPath(t, "NARRATIO_TEST_AUDITA_BINARY") binary := externalPath(t, "NARRATIO_TEST_AUDITA_BINARY")
var negative atomic.Bool var negative atomic.Bool
var processing atomic.Bool
var calls atomic.Int32 var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close() defer r.Body.Close()
@@ -173,6 +175,9 @@ func TestAuditaBinaryCompatibility(t *testing.T) {
} }
calls.Add(1) calls.Add(1)
content := `{"status":"ok"}` content := `{"status":"ok"}`
if processing.Load() {
content = `{"corrections":[]}`
}
if negative.Load() && request.Model == "review-model" { if negative.Load() && request.Model == "review-model" {
content = `{"bad":true}` content = `{"bad":true}`
} }
@@ -180,11 +185,11 @@ func TestAuditaBinaryCompatibility(t *testing.T) {
})) }))
defer server.Close() defer server.Close()
cfg := testConfig(t) cfg := testConfig(t)
mustWriteTestFile(t, *cfg.Session.Inputs.GlossaryFile, "campaign:\n instruction: Preserve campaign names.\n entries: [{id: watch, name: Silver Watch, category: organization, aliases: null}]\n") mustWriteTestFile(t, *cfg.Session.Inputs.GlossaryFile, "schema_version: maximumdirect.glossary.v1\ncollections:\n campaign:\n instruction: Preserve campaign names.\n entries: [{id: watch, name: Silver Watch, category: organization, aliases: null}]\n")
settingPath := filepath.Join(filepath.Dir(cfg.CampaignPath), "setting.yml") settingPath := filepath.Join(filepath.Dir(cfg.CampaignPath), "setting.yml")
spellsPath := filepath.Join(filepath.Dir(cfg.CampaignPath), "spells.yml") spellsPath := filepath.Join(filepath.Dir(cfg.CampaignPath), "spells.yml")
mustWriteTestFile(t, settingPath, "setting: {instruction: Preserve place names., entries: [{id: harbor, name: Harbor, category: place}]}\n") mustWriteTestFile(t, settingPath, "schema_version: maximumdirect.glossary.v1\ncollections:\n setting: {instruction: Preserve place names., entries: [{id: harbor, name: Harbor, category: place}]}\n")
mustWriteTestFile(t, spellsPath, "spells: {instruction: Preserve spell names., entries: [{id: glow, name: Glow, category: spell}]}\n") mustWriteTestFile(t, spellsPath, "schema_version: maximumdirect.glossary.v1\ncollections:\n spells: {instruction: Preserve spell names., entries: [{id: glow, name: Glow, category: spell}]}\n")
cfg.Pipeline.ReferenceCatalog = config.ReferenceCatalogConfig{Settings: map[string]string{"coast": settingPath}, Systems: map[string]string{"magic": spellsPath}} cfg.Pipeline.ReferenceCatalog = config.ReferenceCatalogConfig{Settings: map[string]string{"coast": settingPath}, Systems: map[string]string{"magic": spellsPath}}
cfg.Session.Inputs.Setting = new("coast") cfg.Session.Inputs.Setting = new("coast")
cfg.Session.Inputs.System = new("magic") cfg.Session.Inputs.System = new("magic")
@@ -230,13 +235,13 @@ func TestAuditaBinaryCompatibility(t *testing.T) {
t.Fatalf("missing %s: %s", name, output) t.Fatalf("missing %s: %s", name, output)
} }
} }
for name, instruction := range map[string]string{"campaign": "Preserve campaign names.", "setting": "Preserve place names.", "spells": "Preserve spell names."} { for name, instruction := range map[string]string{"campaign": "", "setting": "", "spells": "Audita default."} {
collection := inspected.Collections[name] collection := inspected.Collections[name]
if collection.Instruction == nil || *collection.Instruction != instruction || len(collection.Entries) != 1 { if collection.Instruction == nil || *collection.Instruction != instruction || len(collection.Entries) != 1 {
t.Fatalf("%s: %+v", name, collection) t.Fatalf("%s: unexpected effective instruction or entries: %+v", name, collection)
} }
} }
runner, err := audita.NewSubprocessRunner(audita.SubprocessRunnerConfig{Binary: binary, ConfigPath: configPath, Timeout: 30 * time.Second}) runner, err := audita.NewSubprocessRunner(audita.SubprocessRunnerConfig{Binary: binary, ConfigPath: configPath, OutputSchema: "audita-v1", Timeout: 30 * time.Second})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -244,6 +249,18 @@ func TestAuditaBinaryCompatibility(t *testing.T) {
if err != nil || result.ExitCode != 0 || calls.Load() != 2 { if err != nil || result.ExitCode != 0 || calls.Load() != 2 {
t.Fatalf("preflight: %+v %v calls=%d", result, err, calls.Load()) t.Fatalf("preflight: %+v %v calls=%d", result, err, calls.Load())
} }
transcript := filepath.Join(dir, "input.json")
mustWriteTestFile(t, transcript, `{"segments":[{"id":1,"speaker":"Player","start":0,"end":1,"text":"Hello world."}]}`)
req.MergedTranscriptPath = transcript
processing.Store(true)
processed, err := runner.Run(context.Background(), req)
if err != nil || processed.ExitCode != 0 {
t.Fatalf("processing: %+v %v", processed, err)
}
if data, err := os.ReadFile(req.OutputProcessedPath); err != nil || !bytes.Contains(data, []byte("Hello world")) {
t.Fatalf("processed transcript: %s %v", data, err)
}
processing.Store(false)
negative.Store(true) negative.Store(true)
calls.Store(0) calls.Store(0)
result, err = runner.Preflight(context.Background(), req) result, err = runner.Preflight(context.Background(), req)

View File

@@ -24,7 +24,7 @@ func TestGlossaryAuthoringExamplesResolve(t *testing.T) {
}{ }{
{name: "inline", fragment: "inline-only.yml", campaign: "Silver Watch", setting: "entries: []", spells: "entries: []"}, {name: "inline", fragment: "inline-only.yml", campaign: "Silver Watch", setting: "entries: []", spells: "entries: []"},
{name: "file", fragment: "file-only.yml", campaign: "Lantern Watch", setting: "entries: []", spells: "entries: []"}, {name: "file", fragment: "file-only.yml", campaign: "Lantern Watch", setting: "entries: []", spells: "entries: []"},
{name: "combined with catalog", fragment: "combined.yml", selectors: " setting: lantern_coast\n system: sample_magic\n", campaign: "Silver Watch", setting: "North Harbor", spells: "Lantern Glow"}, {name: "combined with catalog", fragment: "combined.yml", selectors: "setting: lantern_coast_sample\nsystem: sample_magic\n", campaign: "Silver Watch", setting: "Harbor Crossing", spells: "Lantern Glow"},
} { } {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
@@ -39,12 +39,13 @@ func TestGlossaryAuthoringExamplesResolve(t *testing.T) {
campaign := writePipelineFixture(t, dir, "campaign.yml", fmt.Sprintf(`config: campaign := writePipelineFixture(t, dir, "campaign.yml", fmt.Sprintf(`config:
imports: imports:
- path: %q - path: %q
campaign_id: sample-campaign schema_version: maximumdirect.rpg.campaign.v1
inputs: id: sample-campaign
speakers_file: %q references: {party: %q}
autocorrect_file: %q narratio:
party_file: %q inputs:
%s`, fragment, filepath.Join(examples, "campaigns", "sample-campaign", "speakers.yml"), filepath.Join(examples, "campaigns", "sample-campaign", "autocorrect.yml"), filepath.Join(examples, "campaigns", "sample-campaign", "party.yml"), tc.selectors)) speakers_file: %q
%s`, fragment, filepath.Join(examples, "campaigns", "sample-campaign", "party.yml"), filepath.Join(examples, "campaigns", "sample-campaign", "speakers.yml"), tc.selectors))
session := writePipelineFixture(t, dir, "session.yml", "session_id: session\ninputs: {audio_dir: audio}\n") session := writePipelineFixture(t, dir, "session.yml", "session_id: session\ninputs: {audio_dir: audio}\n")
cfg, err := LoadWithSessionOptions(filepath.Join(examples, "pipeline.catalog.yml"), campaign, session, SessionLoadOptions{}) cfg, err := LoadWithSessionOptions(filepath.Join(examples, "pipeline.catalog.yml"), campaign, session, SessionLoadOptions{})
if err != nil { if err != nil {

View File

@@ -13,378 +13,156 @@ import (
"testing" "testing"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius" "gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
"gitea.maximumdirect.net/eric/narratio/internal/artifactmodel"
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy" "gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config" "gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
) )
const notariusIntegrationBinaryEnv = "NARRATIO_TEST_NOTARIUS_BINARY" // Set both paths to exercise a selected Notarius checkout and binary with a local provider.
func TestNotariusBinaryCompatibility(t *testing.T) {
// Run with: binary, repository := os.Getenv("NARRATIO_TEST_NOTARIUS_BINARY"), os.Getenv("NARRATIO_TEST_NOTARIUS_REPOSITORY")
// NARRATIO_TEST_NOTARIUS_BINARY=/absolute/path/to/notarius GOWORK=off go test ./internal/stage -run '^TestNotariusCacheReuseIntegration$' -count=1 -v if binary == "" || repository == "" {
func TestNotariusCacheReuseIntegration(t *testing.T) { t.Skip("set NARRATIO_TEST_NOTARIUS_BINARY and NARRATIO_TEST_NOTARIUS_REPOSITORY")
binary := strings.TrimSpace(os.Getenv(notariusIntegrationBinaryEnv))
if binary == "" {
t.Skipf("set %s to an absolute Notarius v0.8.1-compatible executable to run this integration test", notariusIntegrationBinaryEnv)
} }
if !filepath.IsAbs(binary) { if !filepath.IsAbs(binary) || !filepath.IsAbs(repository) {
t.Fatalf("%s = %q, want an absolute path", notariusIntegrationBinaryEnv, binary) t.Fatal("Notarius binary and repository paths must be absolute")
} }
info, err := os.Stat(binary) var calls atomic.Int64
if err != nil { provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("inspect %s: %v", notariusIntegrationBinaryEnv, err) var request map[string]any
} if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
if !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 { http.Error(w, err.Error(), 400)
t.Fatalf("%s = %q, want an executable regular file", notariusIntegrationBinaryEnv, binary)
}
t.Run("reuse reference identity and forced refresh", func(t *testing.T) {
provider := newNotariusIntegrationProvider(t)
env, runManifest, fixture := newNotariusIntegrationFixture(t, binary, provider.URL(), "dnd-session")
first := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T010101Z-a0000001", false)
if got := provider.Calls(); got != 2 {
t.Fatalf("first provider calls = %d, want 2", got)
}
if first.ChunkPlan == nil || first.ChunkPlan.Action != "generated" {
t.Fatalf("first chunk plan = %#v, want generated", first.ChunkPlan)
}
mode := "auto"
env.Config.Pipeline.Notarius.Cache = &mode
second := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T010102Z-a0000002", false)
if got := provider.Calls(); got != 2 {
t.Fatalf("resumed provider calls = %d, want unchanged count 2", got)
}
assertNotariusIntegrationDecision(t, second, "extract", "spells-first", "reused", "checkpoint_reused")
assertNotariusIntegrationDecision(t, second, "extract", "spells-second", "reused", "checkpoint_reused")
oldSnapshot := notariusIntegrationSnapshotPath(t, env, runManifest, artifactpolicy.SourceInputParty)
setNotariusIntegrationReference(t, runManifest, fixture.partyPath, "The party now travels with a silver dragon.\n")
third := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T010103Z-a0000003", false)
if got := provider.Calls(); got != 4 {
t.Fatalf("changed-reference provider calls = %d, want 4", got)
}
assertNotariusIntegrationDecision(t, third, "extract", "spells-first", "executed", "checkpoint_missing")
newSnapshot := notariusIntegrationSnapshotPath(t, env, runManifest, artifactpolicy.SourceInputParty)
if newSnapshot == oldSnapshot {
t.Fatalf("changed reference retained snapshot %q", newSnapshot)
}
for _, path := range []string{oldSnapshot, newSnapshot} {
if _, err := os.Stat(path); err != nil {
t.Fatalf("snapshot %q is unavailable: %v", path, err)
}
}
setNotariusIntegrationTranscript(t, runManifest, fixture.transcriptPath, notariusIntegrationTranscript("session-unrelated", "The wizard studies Magic Missile."))
unrelated := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T010104Z-a0000004", false)
if unrelated.ChunkPlan == nil || unrelated.ChunkPlan.Action != "generated" {
t.Fatalf("unrelated chunk plan = %#v, want generated", unrelated.ChunkPlan)
}
unrelatedPlan := filepath.Join(fixture.chunkRoot, strings.TrimPrefix(unrelated.ChunkPlan.SourceDigest, "sha256:"), "plan.json")
unrelatedBefore, err := os.ReadFile(unrelatedPlan)
if err != nil {
t.Fatalf("read unrelated chunk plan: %v", err)
}
setNotariusIntegrationTranscript(t, runManifest, fixture.transcriptPath, notariusIntegrationTranscript("session-cache", "Aria casts Cure Wounds."))
forced := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T010105Z-a0000005", true)
if got := provider.Calls(); got != 8 {
t.Fatalf("forced provider calls = %d, want 8", got)
}
if len(forced.CheckpointDecisions) != 0 {
t.Fatalf("forced extraction loaded checkpoint state: %#v", forced.CheckpointDecisions)
}
if forced.ChunkPlan == nil || forced.ChunkPlan.Action != "refreshed" {
t.Fatalf("forced chunk plan = %#v, want refreshed", forced.ChunkPlan)
}
unrelatedAfter, err := os.ReadFile(unrelatedPlan)
if err != nil {
t.Fatalf("read unrelated chunk plan after refresh: %v", err)
}
if string(unrelatedAfter) != string(unrelatedBefore) {
t.Fatal("forced refresh changed the unrelated input's cached plan")
}
})
t.Run("partial failure resumes accepted predecessor", func(t *testing.T) {
provider := newNotariusIntegrationProvider(t)
provider.FailRequest(2)
env, runManifest, _ := newNotariusIntegrationFixture(t, binary, provider.URL(), "dnd-recovery")
mode := "auto"
env.Config.Pipeline.Notarius.Cache = &mode
runManifest.RunID = "20260916T020101Z-b0000001"
env.Force = false
if result, err := (extractStage{}).Run(context.Background(), env, runManifest); err == nil || result != nil {
t.Fatalf("partial extraction result = %#v error = %v, want failure", result, err)
}
if got := provider.Calls(); got != 2 {
t.Fatalf("failed invocation provider calls = %d, want 2", got)
}
provider.FailRequest(0)
recovered := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T020102Z-b0000002", false)
if got := provider.Calls(); got != 3 {
t.Fatalf("recovery provider calls = %d, want one additional call (3 total)", got)
}
assertNotariusIntegrationDecision(t, recovered, "extract", "spells-first", "reused", "checkpoint_reused")
assertNotariusIntegrationDecision(t, recovered, "extract", "spells-second", "executed", "")
})
}
type notariusIntegrationProvider struct {
server *httptest.Server
calls atomic.Int64
failAt atomic.Int64
}
func newNotariusIntegrationProvider(t *testing.T) *notariusIntegrationProvider {
t.Helper()
provider := &notariusIntegrationProvider{}
provider.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
call := provider.calls.Add(1)
if request.Method != http.MethodPost || request.URL.Path != "/v1/chat/completions" {
t.Errorf("provider request = %s %s, want POST /v1/chat/completions", request.Method, request.URL.Path)
http.Error(w, "unexpected request", http.StatusNotFound)
return return
} }
if provider.failAt.Load() == call { calls.Add(1)
http.Error(w, "controlled provider failure", http.StatusInternalServerError) encoded, _ := json.Marshal(request["response_format"])
schema := string(encoded)
format, _ := request["response_format"].(map[string]any)
spec, _ := format["json_schema"].(map[string]any)
definition, _ := spec["schema"].(map[string]any)
properties, _ := definition["properties"].(map[string]any)
has := func(name string) bool { _, ok := properties[name]; return ok }
content := ""
switch {
case has("status"):
content = `{"status":"ok"}`
case has("classification"):
content = `{"classification":"non_combat","explanation":"No combat."}`
case has("scenes"):
content = `{"scenes":[{"start_unit_id":1,"end_unit_id":2}]}`
case has("kind") && has("summary"):
content = `{"kind":"narrative","title":"Travel","summary":"The party travels."}`
case has("duplicate_groups"):
content = `{"duplicate_groups":[]}`
case has("spell_casts"):
content = `{"spell_casts":[]}`
case has("occurrences"):
content = `{"occurrences":[]}`
case has("combat_turns"):
content = `{"combat_turns":[]}`
case has("enemy_events"):
content = `{"enemy_events":[]}`
case has("items"):
content = `{"items":[]}`
case has("npcs"):
content = `{"npcs":[]}`
case has("locations"):
content = `{"locations":[]}`
default:
t.Errorf("unrecognized provider schema: %s", schema)
http.Error(w, "unknown schema", 400)
return return
} }
w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"choices": []any{map[string]any{"message": map[string]any{"role": "assistant", "content": content}, "finish_reason": "stop"}}})
_, _ = w.Write([]byte(`{"id":"local-completion","object":"chat.completion","created":1,"model":"local-model","choices":[{"index":0,"message":{"role":"assistant","content":"{\"spell_casts\":[]}"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":4,"total_tokens":14}}`))
})) }))
t.Cleanup(provider.server.Close) defer provider.Close()
return provider env, m, _ := setupExtractEnv(t)
}
func (p *notariusIntegrationProvider) URL() string { return p.server.URL }
func (p *notariusIntegrationProvider) Calls() int64 { return p.calls.Load() }
func (p *notariusIntegrationProvider) FailRequest(request int64) { p.failAt.Store(request) }
type notariusIntegrationFixture struct {
transcriptPath string
partyPath string
chunkRoot string
}
func newNotariusIntegrationFixture(t *testing.T, binary, endpoint, pipelineID string) (*Env, *manifest.Manifest, notariusIntegrationFixture) {
t.Helper()
env, runManifest, _ := setupExtractEnv(t)
initialOutput := artifacts.SessionRunNotariusOutputRootForCampaign(
env.Config.Pipeline.Workspace.Root, runManifest.Campaign, runManifest.SessionID, runManifest.RunID,
)
if err := os.RemoveAll(initialOutput); err != nil {
t.Fatalf("remove synthetic output fixture: %v", err)
}
root := env.Config.Pipeline.Workspace.Root root := env.Config.Pipeline.Workspace.Root
profilePath := filepath.Join(root, "local-profile.yml") examples := filepath.Join(repository, "examples", "dnd-complete")
if err := os.WriteFile(profilePath, []byte("id: local-test\nbackend: local\nmodel: local-model\ntimeout_seconds: 30\n"), 0o600); err != nil { configBytes, err := os.ReadFile(filepath.Join(examples, "config.yml"))
t.Fatalf("write local profile: %v", err) if err != nil {
}
chunkRoot := filepath.Join(root, "notarius-cache", "chunk-plans")
checkpointRoot := filepath.Join(root, "notarius-cache", "checkpoints")
configPath := filepath.Join(root, "notarius-integration.yml")
content := fmt.Sprintf(`version: 5
promptkit:
profile_file: %q
local_backend:
endpoint: %q
concurrency_limit: 1
concurrency:
total_llm: 1
stage_workers:
extract: 1
output:
directory: %q
cache:
chunk_plans:
mode: auto
directory: %q
checkpoints:
enabled: true
directory: %q
pipelines:
%s:
llm_profile: local-test
input:
module: seriatim
chunk:
module: generic
output:
module: json
steps:
- id: collect-first
artifacts:
spells-first:
extract:
module: dnd/spells
normalize:
module: dnd/spells
- id: collect-second
artifacts:
spells-second:
extract:
module: dnd/spells
normalize:
module: dnd/spells
`, profilePath, endpoint+"/v1", filepath.Join(root, "unused-output"), chunkRoot, checkpointRoot, pipelineID)
if err := os.WriteFile(configPath, []byte(content), 0o600); err != nil {
t.Fatalf("write Notarius integration config: %v", err)
}
// Select a real downstream overlay. Disable provider retries so the controlled
// failure below tests checkpoint recovery rather than transient HTTP recovery.
overlay := "integration"
overlayDir := filepath.Join(root, "overlays")
if err := os.MkdirAll(overlayDir, 0o700); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := os.WriteFile(filepath.Join(overlayDir, overlay+".yml"), []byte("promptkit:\n transient_retries: 0\n"), 0o600); err != nil { pipelineBytes, err := os.ReadFile(filepath.Join(examples, "pipelines", "dnd-session.yml"))
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
stepBytes, err := os.ReadFile(filepath.Join(examples, "pipelines", "dnd-session.describe-session.yml"))
transcriptPath := filepath.Join(sessionPathsForEnv(env, runManifest.SessionID).ArtifactsDir, "trimmed.from-manifest.json")
setNotariusIntegrationTranscript(t, runManifest, transcriptPath, notariusIntegrationTranscript("session-cache", "Aria casts Cure Wounds."))
partyPath := recordPreparedExtractInput(t, env, runManifest, artifactpolicy.SourceInputParty, "The party includes Aria the cleric.\n")
env.Notarius = notarius.NewSubprocessRunner()
env.Config.Pipeline.Notarius = &config.NotariusConfig{
Enabled: true, Binary: binary, ConfigPath: configPath, PipelineID: pipelineID,
ConfigOverlay: &overlay,
Timeout: "2m", WorkingDirectory: root,
References: map[string]string{"party": artifactpolicy.SourceInputParty},
Outputs: map[string]config.NotariusOutputConfig{
"spells_first": {
LaneID: "spells-first",
},
"spells_second": {
LaneID: "spells-second",
},
},
}
return env, runManifest, notariusIntegrationFixture{transcriptPath: transcriptPath, partyPath: partyPath, chunkRoot: chunkRoot}
}
func notariusIntegrationTranscript(id, text string) []byte {
return []byte(fmt.Sprintf(`{"metadata":{"id":%q,"title":"Cache integration"},"segments":[{"id":1,"start":0,"end":4,"speaker":"Aria","text":%q}]}`, id, text))
}
func setNotariusIntegrationTranscript(t *testing.T, runManifest *manifest.Manifest, path string, content []byte) {
t.Helper()
if err := os.WriteFile(path, content, 0o644); err != nil {
t.Fatalf("write integration transcript: %v", err)
}
checksum, err := artifacts.SHA256File(path)
if err != nil { if err != nil {
t.Fatalf("checksum integration transcript: %v", err) t.Fatal(err)
} }
record := runManifest.Stages["trim"] configDir := filepath.Join(root, "consumer")
if record == nil || len(record.Outputs) != 1 { if err := os.MkdirAll(filepath.Join(configDir, "pipelines"), 0755); err != nil {
t.Fatalf("trim record = %#v, want one output", record) t.Fatal(err)
} }
record.Outputs[0].Kind = artifactmodel.TranscriptOutputKindFinalTrimmed configBytes = append(configBytes, []byte(fmt.Sprintf("\npromptkit:\n backends: [{id: fixture, endpoint: %q}]\n profiles: [{id: fixture, backend: fixture, model: fixture, api_key_required: false}]\n", provider.URL+"/v1"))...)
record.Outputs[0].SourceID = artifactmodel.SourceTranscriptFinalTrimmed pipelineBytes = []byte(strings.ReplaceAll(string(pipelineBytes), "notarius/dnd-extraction-example", "fixture"))
record.Outputs[0].LocalPath = path for name, data := range map[string][]byte{"config.yml": configBytes, "pipelines/dnd-session.yml": pipelineBytes, "pipelines/dnd-session.describe-session.yml": stepBytes} {
record.Outputs[0].Checksum = checksum if err := os.WriteFile(filepath.Join(configDir, name), data, 0644); err != nil {
} t.Fatal(err)
func setNotariusIntegrationReference(t *testing.T, runManifest *manifest.Manifest, path, content string) {
t.Helper()
descriptor, ok := artifactpolicy.DescribePreparedInputSource(artifactpolicy.SourceInputParty)
if !ok {
t.Fatal("prepared party input descriptor is unavailable")
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatalf("write integration reference: %v", err)
}
checksum, err := artifacts.SHA256File(path)
if err != nil {
t.Fatalf("checksum integration reference: %v", err)
}
for index := range runManifest.Inputs {
if runManifest.Inputs[index].Kind == descriptor.ManifestKind {
runManifest.Inputs[index].Checksum = checksum
return
} }
} }
t.Fatalf("prepared party input not found in %#v", runManifest.Inputs) transcript, err := os.ReadFile(filepath.Join(repository, "examples", "dnd-minimal", "transcript.json"))
} if err != nil {
t.Fatal(err)
func notariusIntegrationSnapshotPath(t *testing.T, env *Env, runManifest *manifest.Manifest, sourceID string) string {
t.Helper()
descriptor, ok := artifactpolicy.DescribePreparedInputSource(sourceID)
if !ok {
t.Fatalf("prepared input descriptor %q is unavailable", sourceID)
} }
for _, input := range runManifest.Inputs { transcriptPath := m.Stages["trim"].Outputs[0].LocalPath
if input.Kind != descriptor.ManifestKind { if err := os.WriteFile(transcriptPath, transcript, 0644); err != nil {
continue t.Fatal(err)
} }
path, err := artifacts.SessionNotariusReferenceSnapshotPath( checksum, err := artifacts.SHA256File(transcriptPath)
sessionPathsForEnv(env, runManifest.SessionID), input.Checksum, filepath.Base(input.Path), if err != nil {
) t.Fatal(err)
}
m.Stages["trim"].Outputs[0].Checksum = checksum
party, err := os.ReadFile(filepath.Join(examples, "party.yml"))
if err != nil {
t.Fatal(err)
}
glossary, err := os.ReadFile(filepath.Join(examples, "glossary.yml"))
if err != nil {
t.Fatal(err)
}
recordPreparedExtractInput(t, env, m, artifactpolicy.SourceInputParty, string(party))
recordPreparedExtractInput(t, env, m, artifactpolicy.SourceInputGlossaryCombined, string(glossary))
outputs := map[string]config.NotariusOutputConfig{}
for _, lane := range []string{"item-registry", "npc-registry", "location-registry", "scene-descriptions", "item-occurrences", "spells", "combat-turns", "npc-occurrences", "location-occurrences", "enemy-events"} {
outputs[strings.ReplaceAll(lane, "-", "_")] = config.NotariusOutputConfig{LaneID: lane}
}
cache := "auto"
env.Config.Pipeline.Notarius = &config.NotariusConfig{Enabled: true, Binary: binary, ConfigPath: filepath.Join(configDir, "config.yml"), PipelineID: "dnd-session", Timeout: "2m", WorkingDirectory: configDir, Cache: &cache, Outputs: outputs, References: map[string]string{"party": artifactpolicy.SourceInputParty, "glossary": artifactpolicy.SourceInputGlossaryCombined, "spell_catalog": artifactpolicy.SourceInputGlossaryCombined}}
runner := notarius.NewSubprocessRunner()
env.Notarius = runner
paths := sessionPathsForEnv(env, m.SessionID)
probe, err := BuildNotariusReadiness(env.Config, paths, m, filepath.Join(root, "probe"), true, false)
if err != nil {
t.Fatal(err)
}
ready, err := runner.Preflight(context.Background(), probe.Request)
if err != nil || !ready.Ready {
t.Fatalf("readiness: %+v %v", ready, err)
}
var requestCounts []int64
for i, force := range []bool{false, false, true} {
before := calls.Load()
m.RunID = fmt.Sprintf("20260916T01010%dZ-a000000%d", i+1, i+1)
env.Force = force
result, err := (extractStage{}).Run(context.Background(), env, m)
if err != nil { if err != nil {
t.Fatalf("resolve integration snapshot: %v", err) t.Fatalf("extraction %d: %v", i, err)
} }
return path requestCounts = append(requestCounts, calls.Load()-before)
} if len(result.Outputs) != len(outputs) {
t.Fatalf("prepared input %q not found", sourceID) t.Fatalf("promoted %d lanes, want %d", len(result.Outputs), len(outputs))
return ""
}
func runNotariusIntegrationExtraction(t *testing.T, env *Env, runManifest *manifest.Manifest, runID string, force bool) notariusIntegrationRunManifest {
t.Helper()
runManifest.RunID = runID
env.Force = force
result, err := (extractStage{}).Run(context.Background(), env, runManifest)
if err != nil {
reportPath := artifacts.SessionRunNotariusReportPathForCampaign(env.Config.Pipeline.Workspace.Root, runManifest.Campaign, runManifest.SessionID, runID)
if data, readErr := os.ReadFile(reportPath); readErr == nil {
t.Logf("failed Notarius receipt: %s", data)
} }
t.Fatalf("extract run %q: %v", runID, err) for _, item := range result.Outputs {
} if filepath.Dir(item.AbsolutePath) != paths.ArtifactsDir {
bundleRoot, ok := result.Metadata["bundle_root"].(string) t.Fatalf("non-flat product %q", item.AbsolutePath)
if !ok || bundleRoot == "" {
t.Fatalf("extract metadata bundle_root = %#v", result.Metadata["bundle_root"])
}
data, err := os.ReadFile(filepath.Join(bundleRoot, "manifest.json"))
if err != nil {
t.Fatalf("read Notarius manifest: %v", err)
}
var published notariusIntegrationRunManifest
if err := json.Unmarshal(data, &published); err != nil {
t.Fatalf("decode Notarius manifest: %v", err)
}
return published
}
type notariusIntegrationRunManifest struct {
ChunkPlan *struct {
Action string `json:"action"`
SourceDigest string `json:"source_digest"`
} `json:"chunk_plan"`
CheckpointDecisions []struct {
Stage string `json:"stage"`
LaneID string `json:"lane_id"`
Category string `json:"category"`
ReasonCode string `json:"reason_code"`
} `json:"checkpoint_decisions"`
}
func assertNotariusIntegrationDecision(t *testing.T, published notariusIntegrationRunManifest, stageName, laneID, category, reasonCode string) {
t.Helper()
for _, decision := range published.CheckpointDecisions {
if decision.Stage == stageName && decision.LaneID == laneID {
if decision.Category != category || reasonCode != "" && decision.ReasonCode != reasonCode {
t.Fatalf("checkpoint decision for %s/%s = %#v, want category %q reason %q", stageName, laneID, decision, category, reasonCode)
} }
return
} }
} }
t.Fatalf("checkpoint decision for %s/%s not found in %#v", stageName, laneID, published.CheckpointDecisions) t.Logf("provider calls for initial, reused, refreshed runs: %v", requestCounts)
if requestCounts[0] == 0 || requestCounts[1] != 0 || requestCounts[2] == 0 {
t.Fatalf("cache reuse or refresh did not produce the expected provider calls: %v", requestCounts)
}
} }