Prepare references for artifact-only runs

This commit is contained in:
2026-12-02 15:39:04 +00:00
parent 62778f5c5b
commit 7ad8deb381
13 changed files with 585 additions and 11 deletions

View File

@@ -91,7 +91,9 @@ The default is the full canonical pipeline:
`--from` and `--through` select inclusive contiguous bounds. `--stage` selects
one stage and cannot accompany explicitly supplied range flags. `--force`
reruns selected work; dependent invalidation can extend beyond that range.
Bounded starts require valid preceding manifest state. Ordinary execution uses
Bounded starts require valid preceding state or applicable supplied-product
coverage. When covered transcript work permits a downstream start, Narratio
prepares required references before downstream checks. Ordinary execution uses
semantic resume checks rather than rerunning all selected work.
After preparation, `run` checks projected Audita, Notarius, and Scriptorium work before
@@ -138,10 +140,12 @@ narratio session plan SESSION --stage analyze --force --format json
Accepts the same stage/range, force, artifact, and context selections as `run`.
Reports execution/reuse actions and reasons, analysis targets, prerequisite work,
and publication mappings through shared planners. Planning reads existing state
and publication mappings through shared planners. For applicable bounded runs,
the report also describes reference preparation and identifies unavailable
built-in inputs. Planning reads existing state
without creating a workspace, changing manifests, acquiring execution locks, or
initializing stage-execution adapters or invoking requirements inspection. For a
selected, previously successful S3 preparation eligible for reuse, planning
selected, previously successful S3 audio preparation eligible for reuse, planning
composes object storage and reads current audio identities. An inspection failure
or insufficient identity evidence schedules preparation with an unverified-source
reason; dependent decisions reflect that projected rerun. Object-store

View File

@@ -33,6 +33,10 @@ Materialize canonical current-session inputs before processing stages.
supplied transcript satisfies transcription. Forced or uncovered transcription
requires an audio selection. Preparation metadata records whether audio was
prepared, and reference-only preparation preserves supplied-product records.
- bounded downstream runs may prepare or reuse references under the workspace
lock before readiness checks, even when prepare lies outside the selected range.
Existing audio input records remain available without being recertified by
reference-only preparation.
- derives the party glossary and resolves the remaining named collections through
`internal/glossary`; writes four individual shared envelopes and a combined
envelope with checksums, sizes, and provenance. The combined record declares

View File

@@ -263,7 +263,7 @@ Validation: `go test ./internal/config ./internal/stage ./internal/artifacts`.
## Stage 7: Wire artifact-only preparation into commands and readiness
Status: Pending
Status: Complete
Read runner acquisition/composition, `session_readiness.go`, bounded
prerequisites, `plan.go`, and downstream readiness request builders.

View File

@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"strings"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
@@ -14,10 +15,12 @@ import (
)
type sessionPlanReport struct {
Campaign string `json:"campaign"`
SessionID string `json:"session_id"`
Stages []plannedStage `json:"stages"`
Publication []plannedPublication `json:"publication_actions"`
Campaign string `json:"campaign"`
SessionID string `json:"session_id"`
Stages []plannedStage `json:"stages"`
Publication []plannedPublication `json:"publication_actions"`
ReferencePreparation *preparationAssessment `json:"reference_preparation,omitempty"`
InputIssues []string `json:"input_issues,omitempty"`
}
type plannedStage struct {
Name string `json:"name"`
@@ -104,7 +107,7 @@ func buildSessionPlan(ctx context.Context, cfg *config.Config, input *executionI
return nil, fmt.Errorf("plan: %w", err)
}
var objectStore storage.ObjectStore
if input.plan.Contains("prepare") && !input.Force.Value && cfg.Session.Inputs.AudioS3 != nil && recordedStageStatus(m, "prepare") == manifest.StatusSucceeded {
if input.plan.Contains("prepare") && !input.Force.Value && !suppliedCompletion(cfg, m)["transcribe"] && cfg.Session.Inputs.AudioS3 != nil && recordedStageStatus(m, "prepare") == manifest.StatusSucceeded {
objectStore, err = newCommandObjectStoreWithDependencies(ctx, cfg, deps)
if err != nil {
return nil, fmt.Errorf("plan: %w", err)
@@ -116,6 +119,33 @@ func buildSessionPlan(ctx context.Context, cfg *config.Config, input *executionI
return nil, err
}
report := &sessionPlanReport{Campaign: config.CampaignID(cfg.Campaign), SessionID: cfg.Session.SessionID, Stages: []plannedStage{}, Publication: []plannedPublication{}}
if m != nil && !input.plan.Contains("prepare") && suppliedCompletion(cfg, m)["transcribe"] && projectionNeedsReferences(projection) {
report.ReferencePreparation = &preparationAssessment{Outcome: "planned", Reason: "reference-only preparation before downstream work"}
current, checkErr := referencePreparationCurrent(ctx, cfg, m, store, effective)
if checkErr != nil {
return report, checkErr
}
if current {
report.ReferencePreparation = &preparationAssessment{Outcome: "reused", Reason: "prepared references are current"}
}
env := &stage.Env{Config: cfg, ArtifactStore: store, EffectiveArtifacts: effective}
if validationErr := stage.ValidateReferenceSources(ctx, env, m); !current && validationErr != nil {
report.ReferencePreparation.Outcome = "blocked"
report.ReferencePreparation.Reason = validationErr.Error()
}
requirements, requirementErr := artifacts.CollectPreviousArtifactRequirements(configuredScriptoriumArtifacts(cfg), effective)
if requirementErr != nil {
return report, requirementErr
}
if strings.TrimSpace(cfg.Session.PreviousSessionID) == "" {
for _, requirement := range requirements {
if requirement.Required {
report.InputIssues = append(report.InputIssues, fmt.Sprintf("previous_session_id is required for previous artifact %q", requirement.Name))
}
}
}
}
report.InputIssues = append(report.InputIssues, unavailablePlannedBuiltIns(cfg, m, projection)...)
for _, item := range projection.Stages {
entry := plannedStage{Name: item.Name, Action: string(item.Decision.action), Reason: item.Reason}
if item.Analysis != nil {

123
internal/app/plan_inputs.go Normal file
View File

@@ -0,0 +1,123 @@
package app
import (
"fmt"
"os"
"sort"
"strings"
"gitea.maximumdirect.net/eric/narratio/internal/artifactmodel"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
// unavailablePlannedBuiltIns reports selected real inputs that neither exist
// nor have a producer scheduled by this projection.
func unavailablePlannedBuiltIns(cfg *config.Config, m *manifest.Manifest, projection *workProjection) []string {
if cfg == nil || cfg.Pipeline == nil || cfg.Session == nil || m == nil || !suppliedCompletion(cfg, m)["transcribe"] {
return nil
}
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
running := map[string]bool{}
for _, item := range projection.Stages {
if item.Decision.action == stageActionRun {
running[item.Name] = true
}
}
missing := map[string]bool{}
if running["transcribe"] && strings.TrimSpace(cfg.Session.Inputs.AudioDir) == "" && len(cfg.Session.Inputs.AudioFiles) == 0 && cfg.Session.Inputs.AudioS3 == nil {
audioAvailable := false
for _, input := range m.Inputs {
if input.Kind != "audio" {
continue
}
info, err := os.Stat(artifacts.ResolveSessionLocalPathForRead(paths, input.Path))
if err == nil && info.Mode().IsRegular() {
audioAvailable = true
break
}
}
if !audioAvailable {
missing["audio"] = true
}
}
check := func(source string) {
id, err := artifacts.NormalizeSessionArtifactSource(source)
if err != nil {
return
}
if _, err = artifacts.ResolveSessionArtifact(paths, m, id); err == nil {
return
}
producer := ""
if spec, ok := artifactmodel.LookupRuntimeTranscriptArtifact(id); ok {
producer = spec.ProducerStage
} else if id == artifacts.ArtifactBoundsSession {
producer = "trim"
}
willProduce := running[producer]
if willProduce && producer == "render" {
names := []string{"normalized", "trimmed"}
if cfg.Pipeline.Render != nil {
if cfg.Pipeline.Render.Enabled != nil && !*cfg.Pipeline.Render.Enabled {
names = nil
} else {
names = cfg.Pipeline.Render.Variants
}
}
variants, _ := artifactmodel.SelectRenderVariants(names)
willProduce = false
for _, variant := range variants {
if variant.OutputSource == id {
willProduce = true
}
}
}
if !willProduce {
missing[id] = true
}
}
for _, item := range projection.Stages {
if item.Decision.action != stageActionRun {
continue
}
switch item.Name {
case "render":
names := []string{"normalized", "trimmed"}
if cfg.Pipeline.Render != nil {
if cfg.Pipeline.Render.Enabled != nil && !*cfg.Pipeline.Render.Enabled {
continue
}
names = cfg.Pipeline.Render.Variants
}
variants, _ := artifactmodel.SelectRenderVariants(names)
for _, variant := range variants {
check(variant.InputSource)
}
case "extract":
check(artifacts.ArtifactTranscriptFinalTrimmed)
case "analyze":
if item.Analysis == nil {
continue
}
for _, target := range item.Analysis.ExecutionOrder {
for _, input := range cfg.ConcreteArtifacts()[target.Key].Inputs {
if input.Required {
check(input.Source)
}
}
}
}
}
ids := make([]string, 0, len(missing))
for id := range missing {
ids = append(ids, id)
}
sort.Strings(ids)
result := make([]string, 0, len(ids))
for _, id := range ids {
result = append(result, fmt.Sprintf("required source %q is unavailable", id))
}
return result
}

View File

@@ -0,0 +1,112 @@
package app
import (
"context"
"fmt"
"reflect"
"strings"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
"gitea.maximumdirect.net/eric/narratio/internal/stage"
)
// prepareBoundedReferences makes current references available before downstream
// checks when a supplied transcript replaces the normal preparation prefix.
func prepareBoundedReferences(runtime *invocationRuntime) error {
if runtime.plan.Contains("prepare") || !suppliedCompletion(runtime.cfg, runtime.manifest)["transcribe"] {
return nil
}
if !stagesContainAny(runtime.stages, "polish", "trim", "extract", "analyze") {
return nil
}
projection, err := projectSelectedWork(runtime.ctx, runtime.cfg, runtime.plan, runtime.opts.Force, runtime.opts.SelectedArtifacts, runtime.effectiveArtifacts, runtime.artifactStore, runtime.env.ObjectStore, runtime.manifest)
if err != nil {
return fmt.Errorf("project reference preparation: %w", err)
}
if !projectionNeedsReferences(projection) {
return nil
}
prepare, err := stage.Select("prepare")
if err != nil {
return err
}
env := *runtime.env
env.Force = false
current, err := referencePreparationCurrent(runtime.ctx, runtime.cfg, runtime.manifest, runtime.artifactStore, runtime.effectiveArtifacts)
if err != nil {
return err
}
if current {
return nil
}
requirements, err := artifacts.CollectPreviousArtifactRequirements(configuredScriptoriumArtifacts(runtime.cfg), runtime.effectiveArtifacts)
if err != nil {
return fmt.Errorf("reference preparation requirements: %w", err)
}
if len(requirements) > 0 && strings.TrimSpace(runtime.cfg.Session.PreviousSessionID) != "" && runtime.env.ObjectStore == nil {
runtime.env.ObjectStore, err = runtime.dependencies.newObjectStore(runtime.ctx, runtime.cfg)
if err != nil {
return fmt.Errorf("initialize previous-session storage: %w", err)
}
}
priorInputs := append([]manifest.InputRecord(nil), runtime.manifest.Inputs...)
result, err := stage.PrepareReferences(runtime.ctx, runtime.env, runtime.manifest)
if err != nil {
return fmt.Errorf("prepare references: %w", err)
}
semantic, err := currentStageSemanticConfig(prepare, &env)
if err != nil {
return err
}
at := runtime.dependencies.now()
runtime.manifest.MarkStageSucceeded("prepare", at, nil)
applyStageResultToManifest(runtime.manifest, "prepare", result)
setSessionStageSemanticConfig(runtime.manifest, "prepare", semantic)
if !reflect.DeepEqual(priorInputs, runtime.manifest.Inputs) {
if _, err := invalidateDependentSucceededStagesWithReason(runtime.manifest, "prepare", at, staleReasonChangedResult); err != nil {
return err
}
}
if err := runtime.manifestStore.Save(runtime.ctx, runtime.manifestPath, runtime.manifest); err != nil {
return fmt.Errorf("save prepared references: %w", err)
}
return nil
}
func referencePreparationCurrent(ctx context.Context, cfg *config.Config, m *manifest.Manifest, store artifacts.Store, effective artifacts.EffectiveArtifactSet) (bool, error) {
if recordedStageStatus(m, "prepare") != manifest.StatusSucceeded {
return false, nil
}
prepare, err := stage.Select("prepare")
if err != nil {
return false, err
}
env := &stage.Env{Config: cfg, ArtifactStore: store, EffectiveArtifacts: effective}
semantic, err := currentStageSemanticConfig(prepare, env)
if err != nil {
return false, err
}
validation, err := evaluateStageResume(ctx, prepare, env, m, semantic)
if err != nil {
return false, err
}
return validation != nil && validation.Resumable, nil
}
func projectionNeedsReferences(projection *workProjection) bool {
needsReferences := false
for _, item := range projection.Stages {
if item.Decision.action != stageActionRun {
continue
}
switch item.Name {
case "polish", "trim", "extract":
needsReferences = true
case "analyze":
needsReferences = needsReferences || item.Analysis == nil || len(item.Analysis.ExecutionOrder) > 0
}
}
return needsReferences
}

View File

@@ -0,0 +1,256 @@
package app
import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/seriatim"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"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"
)
func TestBoundedAnalysisPreparesReferencesForSuppliedTranscript(t *testing.T) {
root := t.TempDir()
pipeline, campaign, session := writeValidConfigFilesWithScriptoriumArtifacts(t, root)
cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{})
if err != nil {
t.Fatal(err)
}
cfg.Session.Inputs.AudioDir = ""
cfg.Session.Inputs.AudioFiles = nil
cfg.Session.Inputs.AudioS3 = nil
cfg.ArtifactCatalog.Artifacts = map[string]config.ScriptoriumArtifactConfig{"recap": {Enabled: true, PromptID: "dnd.recap", OutputPath: "artifacts/recap.md", Inputs: map[string]config.ScriptoriumInputConfig{"party": {Source: artifactpolicy.SourceInputParty, Required: true}, "transcript": {Source: artifacts.ArtifactTranscriptFinalTrimmed, Required: true}}}}
paths := artifacts.NewLocalStore(root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
transcript := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed))
if err := os.MkdirAll(filepath.Dir(transcript), 0755); err != nil {
t.Fatal(err)
}
body := []byte(`{"segments":[]}`)
if err := os.WriteFile(transcript, body, 0600); err != nil {
t.Fatal(err)
}
checksum, err := artifacts.SHA256File(transcript)
if err != nil {
t.Fatal(err)
}
m := manifest.New(cfg.Session.SessionID, time.Now())
m.Campaign = cfg.Session.Campaign
m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{artifacts.ArtifactTranscriptFinalTrimmed: {Path: artifacts.TranscriptPathFinalTrimmed, Checksum: checksum, Size: int64(len(body))}}}
saveBoundedManifest(t, cfg, m)
plan := mustBoundedPlan(t, "analyze", "analyze")
fake := &scriptorium.FakeRunner{}
result, err := executePlan(context.Background(), cfg, plan, RunOptions{Env: &Env{Scriptorium: fake}})
if err != nil {
t.Fatal(err)
}
if len(fake.RunRequests) != 1 {
t.Fatalf("requests %+v", fake.RunRequests)
}
if fake.RunRequests[0].InputPaths["party"] != filepath.Join(paths.InputsDir, "party.yml") {
t.Fatalf("inputs %+v", fake.RunRequests[0].InputPaths)
}
saved, err := (&manifest.LocalStore{}).Load(context.Background(), result.ManifestPath)
if err != nil {
t.Fatal(err)
}
if _, ok := saved.SuppliedProducts.Products[artifacts.ArtifactTranscriptFinalTrimmed]; !ok {
t.Fatal("lost supplied transcript")
}
speakers := cfg.StableInputs.SpeakersFile
speakerPath := speakers.Path
if !filepath.IsAbs(speakerPath) {
speakerPath = filepath.Join(filepath.Dir(speakers.ConfigPath), speakerPath)
}
if err := os.Remove(speakerPath); err != nil {
t.Fatal(err)
}
if _, err := executePlan(context.Background(), cfg, plan, RunOptions{Force: true, Env: &Env{Scriptorium: fake}}); err == nil {
t.Fatal("missing reference did not block forced downstream work")
}
if len(fake.RunRequests) != 1 {
t.Fatal("adapter invoked after reference preparation failed")
}
}
func TestFullRunWithSuppliedTranscriptPreparesAndRendersSelectedVariant(t *testing.T) {
root := t.TempDir()
pipeline, campaign, session := writeValidConfigFilesWithScriptoriumArtifacts(t, root)
cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{})
if err != nil {
t.Fatal(err)
}
cfg.Session.Inputs.AudioDir = ""
cfg.Session.Inputs.AudioFiles = nil
cfg.Session.Inputs.AudioS3 = nil
cfg.Pipeline.Render.Variants = []string{"trimmed"}
cfg.ArtifactCatalog.Artifacts = map[string]config.ScriptoriumArtifactConfig{"recap": {Enabled: true, PromptID: "dnd.recap", OutputPath: "artifacts/recap.md", Inputs: map[string]config.ScriptoriumInputConfig{"party": {Source: artifactpolicy.SourceInputParty, Required: true}, "transcript": {Source: artifacts.ArtifactTranscriptFinalTrimmed, Required: true}}}}
paths := artifacts.NewLocalStore(root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
transcript := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed))
if err := os.MkdirAll(filepath.Dir(transcript), 0755); err != nil {
t.Fatal(err)
}
body := []byte(`{"segments":[]}`)
if err := os.WriteFile(transcript, body, 0600); err != nil {
t.Fatal(err)
}
checksum, err := artifacts.SHA256File(transcript)
if err != nil {
t.Fatal(err)
}
m := manifest.New(cfg.Session.SessionID, time.Now())
m.Campaign = cfg.Session.Campaign
m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{artifacts.ArtifactTranscriptFinalTrimmed: {Path: artifacts.TranscriptPathFinalTrimmed, Checksum: checksum, Size: int64(len(body))}}}
saveBoundedManifest(t, cfg, m)
plan := mustBoundedPlan(t, "", "analyze")
sf := &scriptorium.FakeRunner{}
ser := &seriatim.FakeRunner{}
result, err := executePlan(context.Background(), cfg, plan, RunOptions{Env: &Env{Scriptorium: sf, Seriatim: ser}})
if err != nil {
t.Fatal(err)
}
if len(ser.RenderRequests) != 1 || len(sf.RunRequests) != 1 {
t.Fatalf("render %d analyze %d, executed %v", len(ser.RenderRequests), len(sf.RunRequests), result.Executed)
}
for _, name := range []string{"transcribe", "merge", "polish", "normalize", "trim"} {
for _, executed := range result.Executed {
if name == executed {
t.Fatalf("covered stage %s executed", name)
}
}
}
forced := mustBoundedPlan(t, "transcribe", "transcribe")
input := &executionInput{plan: forced}
input.Force.Value = true
effective, err := resolveEffectiveArtifacts(cfg, nil)
if err != nil {
t.Fatal(err)
}
report, err := buildSessionPlan(context.Background(), cfg, input, nil, effective, commandDependencies{})
if err != nil || !strings.Contains(strings.Join(report.InputIssues, " "), "audio") {
t.Fatalf("forced plan did not report missing audio: %+v %v", report, err)
}
if _, err := executePlan(context.Background(), cfg, forced, RunOptions{Force: true}); err == nil {
t.Fatal("forced transcription accepted a session without audio")
}
}
func TestBoundedPlanReportsReferencePreparationAndMissingInput(t *testing.T) {
root := t.TempDir()
pipeline, campaign, session := writeValidConfigFilesWithScriptoriumArtifacts(t, root)
cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{})
if err != nil {
t.Fatal(err)
}
cfg.Session.Inputs.AudioDir = ""
cfg.Session.Inputs.AudioFiles = nil
cfg.ArtifactCatalog.Artifacts = map[string]config.ScriptoriumArtifactConfig{"recap": {Enabled: true, PromptID: "dnd.recap", OutputPath: "artifacts/recap.md", Inputs: map[string]config.ScriptoriumInputConfig{"transcript": {Source: artifacts.ArtifactTranscriptFinal, Required: true}}}}
paths := artifacts.NewLocalStore(root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
transcript := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed))
if err := os.MkdirAll(filepath.Dir(transcript), 0755); err != nil {
t.Fatal(err)
}
body := []byte(`{"segments":[]}`)
if err := os.WriteFile(transcript, body, 0600); err != nil {
t.Fatal(err)
}
checksum, err := artifacts.SHA256File(transcript)
if err != nil {
t.Fatal(err)
}
m := manifest.New(cfg.Session.SessionID, time.Now())
m.Campaign = cfg.Session.Campaign
m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{artifacts.ArtifactTranscriptFinalTrimmed: {Path: artifacts.TranscriptPathFinalTrimmed, Checksum: checksum, Size: int64(len(body))}}}
path := saveBoundedManifest(t, cfg, m)
before, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
effective, err := resolveEffectiveArtifacts(cfg, nil)
if err != nil {
t.Fatal(err)
}
input := &executionInput{plan: mustBoundedPlan(t, "analyze", "analyze")}
report, err := buildSessionPlan(context.Background(), cfg, input, nil, effective, commandDependencies{})
if err != nil {
t.Fatal(err)
}
if report.ReferencePreparation == nil || report.ReferencePreparation.Outcome != "planned" || len(report.InputIssues) != 1 || !strings.Contains(report.InputIssues[0], artifacts.ArtifactTranscriptFinal) {
t.Fatalf("report %+v", report)
}
after, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(before, after) {
t.Fatal("plan changed manifest")
}
if _, err := os.Stat(filepath.Join(paths.InputsDir, "party.yml")); !os.IsNotExist(err) {
t.Fatalf("plan wrote references: %v", err)
}
recap := cfg.ArtifactCatalog.Artifacts["recap"]
recap.Inputs["history"] = config.ScriptoriumInputConfig{Source: artifactpolicy.PreviousSessionSourceID("recap"), Required: true}
cfg.ArtifactCatalog.Artifacts["recap"] = recap
report, err = buildSessionPlan(context.Background(), cfg, input, nil, effective, commandDependencies{})
if err != nil {
t.Fatal(err)
}
if len(report.InputIssues) < 2 || !strings.Contains(strings.Join(report.InputIssues, " "), "previous_session_id") {
t.Fatalf("missing required history not reported: %+v", report.InputIssues)
}
if _, err := executePlan(context.Background(), cfg, input.plan, RunOptions{Env: &Env{Scriptorium: &scriptorium.FakeRunner{}}}); err == nil || !strings.Contains(err.Error(), "previous_session_id") {
t.Fatalf("missing history execution error: %v", err)
}
}
func TestStandalonePreflightWithSuppliedTranscriptStillProbesProviders(t *testing.T) {
root := t.TempDir()
pipeline, campaign, session := writeValidConfigFiles(t, root)
cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{})
if err != nil {
t.Fatal(err)
}
cfg.Session.Inputs.AudioDir = ""
cfg.Session.Inputs.AudioFiles = nil
cfg.Session.Inputs.AudioS3 = nil
paths := artifacts.NewLocalStore(root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
path := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed))
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatal(err)
}
body := []byte(`{"segments":[]}`)
if err := os.WriteFile(path, body, 0600); err != nil {
t.Fatal(err)
}
checksum, err := artifacts.SHA256File(path)
if err != nil {
t.Fatal(err)
}
m := manifest.New(cfg.Session.SessionID, time.Now())
m.Campaign = cfg.Session.Campaign
m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{artifacts.ArtifactTranscriptFinalTrimmed: {Path: artifacts.TranscriptPathFinalTrimmed, Checksum: checksum, Size: int64(len(body))}}}
saveBoundedManifest(t, cfg, m)
provider := &audita.FakeRunner{}
deps := fakeCommandDependencies(&storage.FakeBackend{}, nil)
deps.newAudita = func(*config.Config) (audita.Runner, error) { return provider, nil }
report, err := inspectConfiguredForTest(context.Background(), cfg, deps)
if err != nil || !report.Ready || len(provider.PreflightRequests) != 1 {
t.Fatalf("report %+v err %v", report, err)
}
saved, err := (&manifest.LocalStore{}).Load(context.Background(), manifestPathFor(cfg))
if err != nil {
t.Fatal(err)
}
if saved.Stages["prepare"].Metadata["audio_prepared"] != false {
t.Fatal("preflight claimed audio preparation")
}
}

View File

@@ -169,6 +169,7 @@ inputs:
{
name: "validation failure",
sessionYAML: `session_id: 2026-05-03
previous_session_id: 2026-05-03
`,
command: []string{"session", "plan", "2026-05-03"},
},

View File

@@ -100,6 +100,9 @@ func withLockedInvocation(ctx context.Context, cfg *config.Config, plan BoundedP
}
func executeSelectedStages(runtime *invocationRuntime) error {
if err := prepareBoundedReferences(runtime); err != nil {
return err
}
downstreamChecked := false
for index, selected := range runtime.stages {
if selected.Name() != "prepare" && !downstreamChecked {

View File

@@ -2,8 +2,10 @@ package app
import (
"fmt"
"strings"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notify"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/stage"
)
@@ -60,6 +62,13 @@ func composeInvocation(runtime *invocationRuntime, stages []stage.Stage) error {
if err != nil {
return err
}
if stagesContainAny(stages, "prepare") && !runtime.opts.Force && suppliedCompletion(runtime.cfg, runtime.manifest)["transcribe"] {
requirements, err := artifacts.CollectPreviousArtifactRequirements(configuredScriptoriumArtifacts(runtime.cfg), runtime.effectiveArtifacts)
if err != nil {
return err
}
needStore = len(requirements) > 0 && strings.TrimSpace(runtime.cfg.Session.PreviousSessionID) != ""
}
if env.ObjectStore == nil && needStore {
objectStore, err := dependencies.newObjectStore(runtime.ctx, env.Config)
if err != nil {

View File

@@ -115,7 +115,11 @@ func assessSessionReadiness(runtime *invocationRuntime, report *sessionReadiness
}
report.Checks = append(report.Checks, readinessCheck{Group: "preparation", Outcome: outcome, Message: message})
if prepared {
report.Findings = append(report.Findings, okFinding("inputs", "prepared session inputs and audio are current"))
message := "prepared session inputs and audio are current"
if record := runtime.manifest.Stages["prepare"]; record != nil && record.Metadata["audio_prepared"] == false {
message = "prepared session references are current"
}
report.Findings = append(report.Findings, okFinding("inputs", message))
if record := runtime.manifest.Stages["prepare"]; record != nil {
if hydrated := previousArtifactNames(record.Metadata["previous_artifacts_hydrated"]); len(hydrated) > 0 {
report.Findings = append(report.Findings, okFinding("previous", fmt.Sprintf("prepared previous artifacts: %v", hydrated)))

View File

@@ -104,6 +104,13 @@ func prepareInputs(ctx context.Context, env *Env, m *manifest.Manifest, acquireA
}
inputs := make([]manifest.InputRecord, 0, 9+len(resolvedLocalAudio))
if !acquireAudio {
for _, input := range m.Inputs {
if input.Kind == "audio" {
inputs = append(inputs, input)
}
}
}
registerInput := func(kind, path, checksum string) {
inputs = append(inputs, manifest.InputRecord{Kind: kind, Path: path, Checksum: checksum})
}

View File

@@ -20,6 +20,18 @@ import (
const prepareResumeChangedReason = "prepared inputs or their current sources changed; rerun prepare"
// ValidateReferenceSources inspects the local sources used by reference-only
// preparation without writing workspace files or contacting providers.
func ValidateReferenceSources(ctx context.Context, env *Env, m *manifest.Manifest) error {
if env == nil || env.Config == nil || env.Config.Session == nil || env.Config.Pipeline == nil || env.ArtifactStore == nil || m == nil {
return fmt.Errorf("reference inspection requires resolved configuration, manifest, and artifact store")
}
copyEnv := *env
copyEnv.Force = false
_, err := currentPrepareSourceInputs(ctx, &copyEnv, m)
return err
}
type prepareExpectedInput struct {
kind string
destinationName string
@@ -60,7 +72,16 @@ func (prepareStage) ValidateResume(ctx context.Context, env *Env, m *manifest.Ma
return NonResumable(prepareResumeChangedReason), nil
}
}
if !preparedInputRecordsCurrent(env, paths, m.Inputs) || !prepareSourceInputsMatch(paths, current, m.Inputs) {
records := m.Inputs
if !prepareNeedsAudio(env, m) {
records = make([]manifest.InputRecord, 0, len(m.Inputs))
for _, record := range m.Inputs {
if record.Kind != "audio" {
records = append(records, record)
}
}
}
if !preparedInputRecordsCurrent(env, paths, records) || !prepareSourceInputsMatch(paths, current, records) {
return NonResumable(prepareResumeChangedReason), nil
}
return Resumable(), nil