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

@@ -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)
}
})
}
}

View File

@@ -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)

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: "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 {

View File

@@ -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 := &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)
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)
}
}