From 706c1bb7adf44b726ff59ef517b0f15197aa640b Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 30 Nov 2026 02:29:50 +0000 Subject: [PATCH] Exercise shared campaign and consumer workflows --- docs/roadmap/implementation.md | 24 + examples/campaigns/lantern-coast/campaign.yml | 18 + examples/campaigns/lantern-coast/party.yml | 11 + examples/campaigns/lantern-coast/speakers.yml | 7 + .../campaigns/sample-campaign/campaign.yml | 3 +- .../sample-campaign/fragments/inputs.yml | 15 +- .../campaigns/sample-campaign/glossary.yml | 8 +- examples/glossary-authoring/combined.yml | 13 +- examples/glossary-authoring/file-only.yml | 5 +- examples/glossary-authoring/inline-only.yml | 9 +- examples/glossary.yml | 8 +- examples/pipeline.extraction-subset.yml | 16 +- examples/pipeline.full.annotated.yml | 64 +-- examples/pipeline.production.yml | 4 - .../artifact-families/character_items.yml | 4 +- .../artifact-families/character_meta.yml | 2 +- .../production-testing/conf.d/platform.yml | 6 - examples/reference-catalog/catalog.yml | 2 +- .../fragments/lantern-coast-places.yml | 7 + .../fragments/sample-spells.yml | 7 + examples/reference-catalog/setting.yml | 18 +- examples/reference-catalog/spells.yml | 19 +- internal/app/assembled_workflow_test.go | 102 ++++ internal/app/compatibility_test.go | 51 +- internal/config/load_validate_test.go | 15 +- .../stage/notarius_cache_integration_test.go | 468 +++++------------- 26 files changed, 417 insertions(+), 489 deletions(-) create mode 100644 examples/campaigns/lantern-coast/campaign.yml create mode 100644 examples/campaigns/lantern-coast/party.yml create mode 100644 examples/campaigns/lantern-coast/speakers.yml create mode 100644 examples/reference-catalog/fragments/lantern-coast-places.yml create mode 100644 examples/reference-catalog/fragments/sample-spells.yml diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 8d22576..ff4cbc7 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -799,6 +799,30 @@ creation on fully reused or plan-only invocations. ## 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: `internal/app/compatibility_test.go`, assembled workflow fixtures, existing Notarius integration tests, and the catalog compatibility script. diff --git a/examples/campaigns/lantern-coast/campaign.yml b/examples/campaigns/lantern-coast/campaign.yml new file mode 100644 index 0000000..3e84d8b --- /dev/null +++ b/examples/campaigns/lantern-coast/campaign.yml @@ -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: [] diff --git a/examples/campaigns/lantern-coast/party.yml b/examples/campaigns/lantern-coast/party.yml new file mode 100644 index 0000000..ff7df85 --- /dev/null +++ b/examples/campaigns/lantern-coast/party.yml @@ -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 diff --git a/examples/campaigns/lantern-coast/speakers.yml b/examples/campaigns/lantern-coast/speakers.yml new file mode 100644 index 0000000..005ac94 --- /dev/null +++ b/examples/campaigns/lantern-coast/speakers.yml @@ -0,0 +1,7 @@ +match: + - speaker: Rowan + match: + - Rowan_recording + - speaker: GM + match: + - GM_recording diff --git a/examples/campaigns/sample-campaign/campaign.yml b/examples/campaigns/sample-campaign/campaign.yml index 560807d..9482e90 100644 --- a/examples/campaigns/sample-campaign/campaign.yml +++ b/examples/campaigns/sample-campaign/campaign.yml @@ -1,5 +1,6 @@ +schema_version: maximumdirect.rpg.campaign.v1 +id: sample-campaign config: imports: - path: fragments/inputs.yml required: true -campaign_id: sample-campaign diff --git a/examples/campaigns/sample-campaign/fragments/inputs.yml b/examples/campaigns/sample-campaign/fragments/inputs.yml index 51cd76a..4a26f27 100644 --- a/examples/campaigns/sample-campaign/fragments/inputs.yml +++ b/examples/campaigns/sample-campaign/fragments/inputs.yml @@ -1,7 +1,8 @@ -session_template_file: ../session.template.yml -inputs: - speakers_file: ../speakers.yml - autocorrect_file: ../autocorrect.yml - glossary_file: ../glossary.yml - party_file: ../party.yml - spell_catalog_file: ../spell_catalog.json +references: + party: ../party.yml +narratio: + session_template_file: ../session.template.yml + inputs: + speakers_file: ../speakers.yml + glossary_file: ../glossary.yml + autocorrect: [] diff --git a/examples/campaigns/sample-campaign/glossary.yml b/examples/campaigns/sample-campaign/glossary.yml index 13364df..5efd928 100644 --- a/examples/campaigns/sample-campaign/glossary.yml +++ b/examples/campaigns/sample-campaign/glossary.yml @@ -1,3 +1,5 @@ -campaign: - entries: - - {id: lantern_watch, name: Lantern Watch, category: organization} +schema_version: maximumdirect.glossary.v1 +collections: + campaign: + entries: + - {id: lantern_watch, name: Lantern Watch, category: organization} diff --git a/examples/glossary-authoring/combined.yml b/examples/glossary-authoring/combined.yml index 59c7430..5680737 100644 --- a/examples/glossary-authoring/combined.yml +++ b/examples/glossary-authoring/combined.yml @@ -1,7 +1,8 @@ # Inline records compose above the file using ConfigKit entry identities. -inputs: - glossary_file: ../glossary.yml - glossary: - instruction: Use established campaign terminology. - entries: - - {id: lantern_watch, name: Silver Watch, category: organization} +narratio: + inputs: + glossary_file: ../glossary.yml + glossary: + instruction: Use established campaign terminology. + entries: + - {id: lantern_watch, name: Silver Watch, category: organization} diff --git a/examples/glossary-authoring/file-only.yml b/examples/glossary-authoring/file-only.yml index 1940553..851a7dc 100644 --- a/examples/glossary-authoring/file-only.yml +++ b/examples/glossary-authoring/file-only.yml @@ -1,3 +1,4 @@ # Campaign inputs fragment; select the adjacent sample file when importing this fragment. -inputs: - glossary_file: ../glossary.yml +narratio: + inputs: + glossary_file: ../glossary.yml diff --git a/examples/glossary-authoring/inline-only.yml b/examples/glossary-authoring/inline-only.yml index cea9e0d..de010df 100644 --- a/examples/glossary-authoring/inline-only.yml +++ b/examples/glossary-authoring/inline-only.yml @@ -1,5 +1,6 @@ # Campaign inputs fragment; include the required roster and other inputs separately. -inputs: - glossary: - entries: - - {id: watch, name: Silver Watch, category: organization} +narratio: + inputs: + glossary: + entries: + - {id: watch, name: Silver Watch, category: organization} diff --git a/examples/glossary.yml b/examples/glossary.yml index 13364df..5efd928 100644 --- a/examples/glossary.yml +++ b/examples/glossary.yml @@ -1,3 +1,5 @@ -campaign: - entries: - - {id: lantern_watch, name: Lantern Watch, category: organization} +schema_version: maximumdirect.glossary.v1 +collections: + campaign: + entries: + - {id: lantern_watch, name: Lantern Watch, category: organization} diff --git a/examples/pipeline.extraction-subset.yml b/examples/pipeline.extraction-subset.yml index 0c93119..790e86c 100644 --- a/examples/pipeline.extraction-subset.yml +++ b/examples/pipeline.extraction-subset.yml @@ -15,29 +15,17 @@ notarius: pipeline_id: dnd-session timeout: 3h references: - glossary: narratio.input.glossary.campaign + glossary: narratio.input.glossary.combined party: narratio.input.party players: narratio.input.players - spell_catalog: narratio.input.spell_catalog + spell_catalog: narratio.input.glossary.combined outputs: 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: lane_id: location-registry - media_type: application/json - schema_id: notarius.dnd.location_registry - schema_version: v1 - module_key: dnd/location-registry 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: binary: scriptorium diff --git a/examples/pipeline.full.annotated.yml b/examples/pipeline.full.annotated.yml index 6e74a26..a8e81a1 100644 --- a/examples/pipeline.full.annotated.yml +++ b/examples/pipeline.full.annotated.yml @@ -34,12 +34,6 @@ campaigns: # Optional command default when --campaign is omitted. 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: # Optional booleans; defaults are true. enabled: true @@ -61,8 +55,7 @@ publish: - source: narratio.artifact.player_handout dest: artifacts/player_handout.md required: false - # Extraction lanes publish only when named explicitly; the bundle and index - # are never implicit publish sources. + # Extraction lanes publish only when named explicitly; the bundle stays local. - source: narratio.extraction.npc_registry dest: artifacts/extraction/npc-registry.json required: true @@ -141,82 +134,37 @@ notarius: pipeline_id: dnd-session timeout: 3h working_directory: /usr/local/etc/notarius - # Reuse compatible accepted Notarius checkpoints during executed extraction. - # The Notarius config must enable recording and provide persistent cache roots. - 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 + # Forced extraction requests refresh from Notarius. + cache: auto # External campaign references use prepared Narratio source IDs. Omit an # optional binding when the selected Notarius pipeline does not need it. references: - glossary: narratio.input.glossary.campaign + glossary: narratio.input.glossary.combined party: narratio.input.party players: narratio.input.players - spell_catalog: narratio.input.spell_catalog - # Each key creates source narratio.extraction.. These constraints match - # the current Notarius D&D lane contracts; update them with Notarius. + spell_catalog: narratio.input.glossary.combined + # Each key creates source narratio.extraction. for its selected lane. outputs: 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: lane_id: npc-registry - media_type: application/json - schema_id: notarius.dnd.npc_registry - schema_version: v1 - module_key: dnd/npc-registry 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: lane_id: scene-descriptions - media_type: application/json - schema_id: notarius.dnd.scene_descriptions - schema_version: v1 - module_key: dnd/scene-descriptions 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: lane_id: spells - media_type: application/json - schema_id: notarius.dnd.spells - schema_version: v1 - module_key: dnd/spells 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: lane_id: npc-occurrences - media_type: application/json - schema_id: notarius.dnd.npc_occurrences - schema_version: v1 - module_key: dnd/npc-occurrences 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: lane_id: enemy-events - media_type: application/json - schema_id: notarius.dnd.enemy_events - schema_version: v1 - module_key: dnd/enemy-events scriptorium: binary: scriptorium diff --git a/examples/pipeline.production.yml b/examples/pipeline.production.yml index ffef358..3d03cdb 100644 --- a/examples/pipeline.production.yml +++ b/examples/pipeline.production.yml @@ -22,10 +22,6 @@ campaigns: root: /usr/local/share/narratio/campaigns default_campaign_id: sample-campaign -spool: - root: /var/spool/narratio - delete_audio_after_publish: true - publish: enabled: true upload_run: true diff --git a/examples/production-testing/artifact-families/character_items.yml b/examples/production-testing/artifact-families/character_items.yml index 9a0cd73..9b61744 100644 --- a/examples/production-testing/artifact-families/character_items.yml +++ b/examples/production-testing/artifact-families/character_items.yml @@ -3,7 +3,7 @@ character_items: for_each: party.characters prompt_id: dnd.character_items profile_id: production-placeholder - output_path_pattern: artifacts/characters/{character_id}/items.md + output_path_pattern: artifacts/{character_id}-items.md inputs: character_meta: source: narratio.member_artifact.character_meta @@ -15,4 +15,4 @@ character_items: publish: enabled: true required: false - dest_pattern: artifacts/characters/{character_id}/items.md + dest_pattern: artifacts/{character_id}-items.md diff --git a/examples/production-testing/artifact-families/character_meta.yml b/examples/production-testing/artifact-families/character_meta.yml index b95e552..8bb58c9 100644 --- a/examples/production-testing/artifact-families/character_meta.yml +++ b/examples/production-testing/artifact-families/character_meta.yml @@ -3,7 +3,7 @@ character_meta: for_each: party.characters prompt_id: dnd.character_meta profile_id: production-placeholder - output_path_pattern: artifacts/characters/{character_id}/meta.md + output_path_pattern: artifacts/{character_id}-meta.md member_vars: character_id: character_id character_name: character.name diff --git a/examples/production-testing/conf.d/platform.yml b/examples/production-testing/conf.d/platform.yml index e6c8311..fe90b60 100644 --- a/examples/production-testing/conf.d/platform.yml +++ b/examples/production-testing/conf.d/platform.yml @@ -4,9 +4,3 @@ workspace: campaigns: root: ../../campaigns default_campaign_id: sample-campaign - -cache: - root: ./cache - -spool: - root: ./spool diff --git a/examples/reference-catalog/catalog.yml b/examples/reference-catalog/catalog.yml index 1990f4d..01c9ae1 100644 --- a/examples/reference-catalog/catalog.yml +++ b/examples/reference-catalog/catalog.yml @@ -1,5 +1,5 @@ reference_catalog: settings: - lantern_coast: ./setting.yml + lantern_coast_sample: ./setting.yml systems: sample_magic: ./spells.yml diff --git a/examples/reference-catalog/fragments/lantern-coast-places.yml b/examples/reference-catalog/fragments/lantern-coast-places.yml new file mode 100644 index 0000000..0550ee4 --- /dev/null +++ b/examples/reference-catalog/fragments/lantern-coast-places.yml @@ -0,0 +1,7 @@ +collections: + setting: + entries: + - id: harbor_crossing + name: Harbor Crossing + category: place + aliases: [The Crossing] diff --git a/examples/reference-catalog/fragments/sample-spells.yml b/examples/reference-catalog/fragments/sample-spells.yml new file mode 100644 index 0000000..d65cc02 --- /dev/null +++ b/examples/reference-catalog/fragments/sample-spells.yml @@ -0,0 +1,7 @@ +collections: + spells: + entries: + - id: tide_step + name: Tide Step + category: spell + aliases: [Tidal Step] diff --git a/examples/reference-catalog/setting.yml b/examples/reference-catalog/setting.yml index 10ee76f..d52fbdd 100644 --- a/examples/reference-catalog/setting.yml +++ b/examples/reference-catalog/setting.yml @@ -1,8 +1,16 @@ config: imports: - - path: fragments/places.yml + - path: fragments/lantern-coast-places.yml required: true -setting: - instruction: Use the established place names. - entries: - - {id: coast, name: Lantern Coast, category: place} +schema_version: maximumdirect.glossary.v1 +collections: + setting: + 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. diff --git a/examples/reference-catalog/spells.yml b/examples/reference-catalog/spells.yml index ece048d..341f70f 100644 --- a/examples/reference-catalog/spells.yml +++ b/examples/reference-catalog/spells.yml @@ -1,3 +1,16 @@ -spells: - entries: - - {id: glow, name: Lantern Glow, category: spell} +config: + imports: + - 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. diff --git a/internal/app/assembled_workflow_test.go b/internal/app/assembled_workflow_test.go index a31f2dd..f6b6aba 100644 --- a/internal/app/assembled_workflow_test.go +++ b/internal/app/assembled_workflow_test.go @@ -3,6 +3,7 @@ package app import ( "bytes" "context" + "fmt" "os" "path/filepath" "reflect" @@ -430,3 +431,104 @@ func loadAssembledManifest(t *testing.T, cfg *config.Config) *manifest.Manifest func manifestPathForConfig(workspaceRoot string) string { 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) + } + }) + } +} diff --git a/internal/app/compatibility_test.go b/internal/app/compatibility_test.go index 28d33a5..3496316 100644 --- a/internal/app/compatibility_test.go +++ b/internal/app/compatibility_test.go @@ -81,18 +81,19 @@ func TestReferenceCatalogCompatibility(t *testing.T) { 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)) - campaign := write("campaign.yml", `campaign_id: sample-campaign -inputs: - speakers_file: speakers.yml - autocorrect_file: autocorrect.yml - party_file: party.yml - glossary_file: campaign-glossary.yml - setting: lantern_coast_sample - system: sample_magic - glossary: - entries: [{id: watch, name: Silver Watch, category: organization}] + campaign := write("campaign.yml", `schema_version: maximumdirect.rpg.campaign.v1 +id: sample-campaign +setting: lantern_coast_sample +system: sample_magic +references: {party: party.yml} +narratio: + inputs: + speakers_file: speakers.yml + glossary_file: campaign-glossary.yml + 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("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") @@ -160,6 +161,7 @@ inputs: func TestAuditaBinaryCompatibility(t *testing.T) { binary := externalPath(t, "NARRATIO_TEST_AUDITA_BINARY") var negative atomic.Bool + var processing atomic.Bool var calls atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() @@ -173,6 +175,9 @@ func TestAuditaBinaryCompatibility(t *testing.T) { } calls.Add(1) content := `{"status":"ok"}` + if processing.Load() { + content = `{"corrections":[]}` + } if negative.Load() && request.Model == "review-model" { content = `{"bad":true}` } @@ -180,11 +185,11 @@ func TestAuditaBinaryCompatibility(t *testing.T) { })) defer server.Close() 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") 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, spellsPath, "spells: {instruction: Preserve spell names., entries: [{id: glow, name: Glow, category: spell}]}\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, "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.Session.Inputs.Setting = new("coast") cfg.Session.Inputs.System = new("magic") @@ -230,13 +235,13 @@ func TestAuditaBinaryCompatibility(t *testing.T) { 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] 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 { t.Fatal(err) } @@ -244,6 +249,18 @@ func TestAuditaBinaryCompatibility(t *testing.T) { if err != nil || result.ExitCode != 0 || calls.Load() != 2 { 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) calls.Store(0) result, err = runner.Preflight(context.Background(), req) diff --git a/internal/config/load_validate_test.go b/internal/config/load_validate_test.go index c03e862..4687398 100644 --- a/internal/config/load_validate_test.go +++ b/internal/config/load_validate_test.go @@ -24,7 +24,7 @@ func TestGlossaryAuthoringExamplesResolve(t *testing.T) { }{ {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: "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) { dir := t.TempDir() @@ -39,12 +39,13 @@ func TestGlossaryAuthoringExamplesResolve(t *testing.T) { campaign := writePipelineFixture(t, dir, "campaign.yml", fmt.Sprintf(`config: imports: - path: %q -campaign_id: sample-campaign -inputs: - speakers_file: %q - autocorrect_file: %q - party_file: %q -%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)) +schema_version: maximumdirect.rpg.campaign.v1 +id: sample-campaign +references: {party: %q} +narratio: + inputs: + 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") cfg, err := LoadWithSessionOptions(filepath.Join(examples, "pipeline.catalog.yml"), campaign, session, SessionLoadOptions{}) if err != nil { diff --git a/internal/stage/notarius_cache_integration_test.go b/internal/stage/notarius_cache_integration_test.go index 1bd972c..17a43d6 100644 --- a/internal/stage/notarius_cache_integration_test.go +++ b/internal/stage/notarius_cache_integration_test.go @@ -13,378 +13,156 @@ import ( "testing" "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/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/config" - "gitea.maximumdirect.net/eric/narratio/internal/manifest" ) -const notariusIntegrationBinaryEnv = "NARRATIO_TEST_NOTARIUS_BINARY" - -// Run with: -// NARRATIO_TEST_NOTARIUS_BINARY=/absolute/path/to/notarius GOWORK=off go test ./internal/stage -run '^TestNotariusCacheReuseIntegration$' -count=1 -v -func TestNotariusCacheReuseIntegration(t *testing.T) { - 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) +// Set both paths to exercise a selected Notarius checkout and binary with a local provider. +func TestNotariusBinaryCompatibility(t *testing.T) { + binary, repository := os.Getenv("NARRATIO_TEST_NOTARIUS_BINARY"), os.Getenv("NARRATIO_TEST_NOTARIUS_REPOSITORY") + if binary == "" || repository == "" { + t.Skip("set NARRATIO_TEST_NOTARIUS_BINARY and NARRATIO_TEST_NOTARIUS_REPOSITORY") } - if !filepath.IsAbs(binary) { - t.Fatalf("%s = %q, want an absolute path", notariusIntegrationBinaryEnv, binary) + if !filepath.IsAbs(binary) || !filepath.IsAbs(repository) { + t.Fatal("Notarius binary and repository paths must be absolute") } - info, err := os.Stat(binary) - if err != nil { - t.Fatalf("inspect %s: %v", notariusIntegrationBinaryEnv, err) - } - if !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 { - 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 := ¬ariusIntegrationProvider{} - 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) + var calls atomic.Int64 + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var request map[string]any + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + http.Error(w, err.Error(), 400) return } - if provider.failAt.Load() == call { - http.Error(w, "controlled provider failure", http.StatusInternalServerError) + calls.Add(1) + 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 } - w.Header().Set("Content-Type", "application/json") - _, _ = 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}}`)) + _ = json.NewEncoder(w).Encode(map[string]any{"choices": []any{map[string]any{"message": map[string]any{"role": "assistant", "content": content}, "finish_reason": "stop"}}}) })) - t.Cleanup(provider.server.Close) - return provider -} - -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) - } - + defer provider.Close() + env, m, _ := setupExtractEnv(t) root := env.Config.Pipeline.Workspace.Root - profilePath := filepath.Join(root, "local-profile.yml") - if err := os.WriteFile(profilePath, []byte("id: local-test\nbackend: local\nmodel: local-model\ntimeout_seconds: 30\n"), 0o600); err != nil { - t.Fatalf("write local profile: %v", err) - } - 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 { + examples := filepath.Join(repository, "examples", "dnd-complete") + configBytes, err := os.ReadFile(filepath.Join(examples, "config.yml")) + if err != nil { 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) } - - 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) + stepBytes, err := os.ReadFile(filepath.Join(examples, "pipelines", "dnd-session.describe-session.yml")) if err != nil { - t.Fatalf("checksum integration transcript: %v", err) + t.Fatal(err) } - record := runManifest.Stages["trim"] - if record == nil || len(record.Outputs) != 1 { - t.Fatalf("trim record = %#v, want one output", record) + configDir := filepath.Join(root, "consumer") + if err := os.MkdirAll(filepath.Join(configDir, "pipelines"), 0755); err != nil { + t.Fatal(err) } - record.Outputs[0].Kind = artifactmodel.TranscriptOutputKindFinalTrimmed - record.Outputs[0].SourceID = artifactmodel.SourceTranscriptFinalTrimmed - record.Outputs[0].LocalPath = path - record.Outputs[0].Checksum = checksum -} - -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 + 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"))...) + pipelineBytes = []byte(strings.ReplaceAll(string(pipelineBytes), "notarius/dnd-extraction-example", "fixture")) + for name, data := range map[string][]byte{"config.yml": configBytes, "pipelines/dnd-session.yml": pipelineBytes, "pipelines/dnd-session.describe-session.yml": stepBytes} { + if err := os.WriteFile(filepath.Join(configDir, name), data, 0644); err != nil { + t.Fatal(err) } } - t.Fatalf("prepared party input not found in %#v", runManifest.Inputs) -} - -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) + transcript, err := os.ReadFile(filepath.Join(repository, "examples", "dnd-minimal", "transcript.json")) + if err != nil { + t.Fatal(err) } - for _, input := range runManifest.Inputs { - if input.Kind != descriptor.ManifestKind { - continue - } - path, err := artifacts.SessionNotariusReferenceSnapshotPath( - sessionPathsForEnv(env, runManifest.SessionID), input.Checksum, filepath.Base(input.Path), - ) + transcriptPath := m.Stages["trim"].Outputs[0].LocalPath + if err := os.WriteFile(transcriptPath, transcript, 0644); err != nil { + t.Fatal(err) + } + checksum, err := artifacts.SHA256File(transcriptPath) + 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 { - t.Fatalf("resolve integration snapshot: %v", err) + t.Fatalf("extraction %d: %v", i, err) } - return path - } - t.Fatalf("prepared input %q not found", sourceID) - 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) + requestCounts = append(requestCounts, calls.Load()-before) + if len(result.Outputs) != len(outputs) { + t.Fatalf("promoted %d lanes, want %d", len(result.Outputs), len(outputs)) } - t.Fatalf("extract run %q: %v", runID, err) - } - bundleRoot, ok := result.Metadata["bundle_root"].(string) - 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) + for _, item := range result.Outputs { + if filepath.Dir(item.AbsolutePath) != paths.ArtifactsDir { + t.Fatalf("non-flat product %q", item.AbsolutePath) } - 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) + } }