From 9367c7b7131af73780991a48d5c1801a03a98ae4 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Wed, 2 Dec 2026 15:16:40 +0000 Subject: [PATCH] Reuse supplied artifacts during incremental analysis --- docs/internal/stage-analyze.md | 8 +- docs/roadmap/implementation.md | 2 +- internal/stage/analyze_execution_state.go | 24 +++++- internal/stage/analyze_fingerprint.go | 4 + internal/stage/analyze_plan.go | 2 +- internal/stage/analyze_reconciliation.go | 13 ++++ internal/stage/analyze_supplied_test.go | 95 +++++++++++++++++++++++ internal/stage/checkpoint.go | 20 +++++ 8 files changed, 161 insertions(+), 7 deletions(-) create mode 100644 internal/stage/analyze_supplied_test.go diff --git a/docs/internal/stage-analyze.md b/docs/internal/stage-analyze.md index becb4e8..586fad5 100644 --- a/docs/internal/stage-analyze.md +++ b/docs/internal/stage-analyze.md @@ -83,10 +83,12 @@ Supported source families: validated current dependency-output identities, and sorted effective Scriptorium variables (including Narratio's sticky session variable). - provides read-only reconciliation that classifies each configured record as - current, stale, missing, failed, or otherwise non-resumable, and + supplied, current, stale, missing, failed, or otherwise non-resumable, and separately identifies manifest records removed from current configuration. A record is current only when its fingerprint version and value match and its configured output still passes manifest-authoritative evidence validation. + A valid supplied product is classified first and does not need its historical + generation inputs or fingerprint. - owns a read-only typed work planner. Its explicit targets are enabled artifacts by default or the exact normalized `--artifacts` selection when supplied. It closes targets over configured prerequisites, orders the closure @@ -114,7 +116,9 @@ Supported source families: Scriptorium; newly produced prerequisites enter that catalog with the same contract, checksum, and size identity used for persisted current evidence. - before the first adapter call, checkpoints the reconciled starting collection - when it removed configuration records or cleared obsolete authority. After + when it removed configuration records or cleared obsolete authority. A + scheduled replacement retires its supplied record in this checkpoint, so a + failed attempt cannot revive the old supplied product. After each successful artifact, checkpoints the complete collection before making that artifact available to the next scheduled dependent. Analyze supplies its typed update to the shared diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index e7bcf1e..5f00573 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -187,7 +187,7 @@ Validation: `go test ./internal/artifacts ./internal/stage`. ## Stage 4: Integrate supplied products into incremental analysis -Status: Pending +Status: Complete Read `analyze_reconciliation.go`, `analyze_fingerprint.go`, `analyze_plan.go`, and analysis execution/checkpoint handling. diff --git a/internal/stage/analyze_execution_state.go b/internal/stage/analyze_execution_state.go index cc24d5f..b23cef9 100644 --- a/internal/stage/analyze_execution_state.go +++ b/internal/stage/analyze_execution_state.go @@ -110,19 +110,36 @@ func (state *analyzeExecutionState) acceptArtifact( func (state *analyzeExecutionState) checkpointStartingCollection(ctx context.Context) error { m := state.execution.Manifest + retired := make([]string, 0) + if m != nil && m.SuppliedProducts != nil { + for _, item := range state.workPlan.ExecutionOrder { + source := artifacts.ConfiguredArtifactSourceID(item.Key) + if _, exists := m.SuppliedProducts.Products[source]; exists { + retired = append(retired, source) + } + } + } if m != nil { if record := m.Stages["analyze"]; record != nil && record.AnalyzeStateVersion == manifest.AnalyzeStateContractVersion && - reflect.DeepEqual(record.AnalyzeArtifacts, state.records) { + reflect.DeepEqual(record.AnalyzeArtifacts, state.records) && len(retired) == 0 { return nil } } - return state.checkpointCollection(ctx, state.records) + return state.checkpointCollectionRetiring(ctx, state.records, retired) } func (state *analyzeExecutionState) checkpointCollection( ctx context.Context, records map[string]manifest.AnalyzeArtifactRecord, +) error { + return state.checkpointCollectionRetiring(ctx, records, nil) +} + +func (state *analyzeExecutionState) checkpointCollectionRetiring( + ctx context.Context, + records map[string]manifest.AnalyzeArtifactRecord, + retired []string, ) error { m := state.execution.Manifest if m == nil { @@ -143,12 +160,13 @@ func (state *analyzeExecutionState) checkpointCollection( m.Campaign, m.SessionID, ) - if err := checkpointStageCollection( + if err := checkpointStageCollectionRetiring( ctx, state.execution.Env.ManifestStore, manifestPath, m, "analyze", + retired, func(record *manifest.StageRecord) error { record.AnalyzeStateVersion = manifest.AnalyzeStateContractVersion record.AnalyzeArtifacts = manifest.CloneAnalyzeArtifactCollection(records) diff --git a/internal/stage/analyze_fingerprint.go b/internal/stage/analyze_fingerprint.go index 72ffb25..93dc7ad 100644 --- a/internal/stage/analyze_fingerprint.go +++ b/internal/stage/analyze_fingerprint.go @@ -112,6 +112,10 @@ func computeAnalyzeFingerprints( result := analyzeFingerprintSet{Ordered: make([]analyzeFingerprintCandidate, 0, len(order))} for _, key := range order { candidate := analyzeFingerprintCandidate{Key: key} + if entry, ok := execution.Catalog.Lookup(artifacts.ConfiguredArtifactSourceID(key)); ok && entry.Available && entry.Provenance == artifacts.ArtifactProvenanceSupplied { + result.Ordered = append(result.Ordered, candidate) + continue + } candidate.Fingerprint, candidate.Inputs, candidate.DependencyOutputs, candidate.Err = computeAnalyzeArtifactFingerprint(key, scriptoriumCfg, execution) result.Ordered = append(result.Ordered, candidate) diff --git a/internal/stage/analyze_plan.go b/internal/stage/analyze_plan.go index d1a76b8..ba31058 100644 --- a/internal/stage/analyze_plan.go +++ b/internal/stage/analyze_plan.go @@ -109,7 +109,7 @@ func planAnalyzeWork( } _, explicit := targetSet[key] forced := force && explicit - needsWork := forced || state.Reason != analyzeReconciliationCurrent || dependencyWork + needsWork := forced || (state.Reason != analyzeReconciliationCurrent && state.Reason != analyzeReconciliationSupplied) || (dependencyWork && state.Reason != analyzeReconciliationSupplied) item := analyzePlanItem{ Key: key, Reason: state.Reason, Forced: forced, Dependencies: append([]string(nil), dependencies...), diff --git a/internal/stage/analyze_reconciliation.go b/internal/stage/analyze_reconciliation.go index d59c762..84e8296 100644 --- a/internal/stage/analyze_reconciliation.go +++ b/internal/stage/analyze_reconciliation.go @@ -15,6 +15,7 @@ type analyzeReconciliationReason string const ( analyzeReconciliationCurrent analyzeReconciliationReason = "current" + analyzeReconciliationSupplied analyzeReconciliationReason = "supplied" analyzeReconciliationStale analyzeReconciliationReason = "stale" analyzeReconciliationMissing analyzeReconciliationReason = "missing" analyzeReconciliationFailed analyzeReconciliationReason = "failed" @@ -97,6 +98,18 @@ func reconcileAnalyzeArtifact( result := analyzeArtifactReconciliation{ Key: candidate.Key, ExpectedFingerprint: candidate.Fingerprint, } + if entry, ok := execution.Catalog.Lookup(artifacts.ConfiguredArtifactSourceID(candidate.Key)); ok && entry.Available && entry.Provenance == artifacts.ArtifactProvenanceSupplied { + result.Reason = analyzeReconciliationSupplied + result.Detail = "validated supplied product" + return result + } + if execution.Manifest != nil && execution.Manifest.SuppliedProducts != nil { + if _, exists := execution.Manifest.SuppliedProducts.Products[artifacts.ConfiguredArtifactSourceID(candidate.Key)]; exists { + result.Reason = analyzeReconciliationMissing + result.Detail = "supplied product is unavailable or invalid" + return result + } + } if stageRecord == nil { result.Reason = analyzeReconciliationMissing result.Detail = "analyze manifest record is absent" diff --git a/internal/stage/analyze_supplied_test.go b/internal/stage/analyze_supplied_test.go new file mode 100644 index 0000000..6c846f9 --- /dev/null +++ b/internal/stage/analyze_supplied_test.go @@ -0,0 +1,95 @@ +package stage + +import ( + "context" + "path/filepath" + "testing" + + "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" +) + +func suppliedAnalyzeFixture(t *testing.T) (*Env, *manifest.Manifest) { + t.Helper() + env, m, _ := setupAnalyzeEnv(t) + paths := sessionPathsForEnv(env, m.SessionID) + path := filepath.Join(paths.ArtifactsDir, "session_recap.md") + body := "supplied recap\n" + writeAnalyzeFile(t, path, body) + checksum, err := artifacts.SHA256File(path) + if err != nil { + t.Fatal(err) + } + m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{ + artifacts.ConfiguredArtifactSourceID("session_recap"): {Path: "artifacts/session_recap.md", Checksum: checksum, Size: int64(len(body)), Contract: &artifactmodel.ContractMetadata{MediaType: "text/markdown", SchemaID: "test", SchemaVersion: "1"}}, + }} + return env, m +} + +func TestAnalyzeSuppliedPrerequisiteAndNewTarget(t *testing.T) { + env, m := suppliedAnalyzeFixture(t) + addAnalyzeDependentArtifact(env) + parent := env.Config.ArtifactCatalog.Artifacts["session_recap"] + parent.Enabled = false + parent.PromptID = "changed-historical-prompt" + env.Config.ArtifactCatalog.Artifacts["session_recap"] = parent + env.SelectedArtifactKeys = []string{"player_handout"} + env.Force = true + runner := &orderedScriptoriumRunner{RunBody: "new handout\n"} + env.Scriptorium = runner + _, err := (analyzeStage{}).Run(context.Background(), env, m) + if err != nil { + t.Fatal(err) + } + if len(runner.Calls) != 1 || runner.Calls[0] != "run" { + t.Fatalf("calls %v", runner.Calls) + } + if _, ok := m.SuppliedProducts.Products[artifacts.ConfiguredArtifactSourceID("session_recap")]; !ok { + t.Fatal("lost supplied prerequisite") + } + if m.Stages["analyze"].AnalyzeArtifacts["player_handout"].Status != manifest.AnalyzeArtifactCurrent { + t.Fatal("missing local checkpoint") + } +} + +func TestAnalyzeForcedSuppliedTargetBecomesLocalCheckpoint(t *testing.T) { + env, m := suppliedAnalyzeFixture(t) + env.SelectedArtifactKeys = []string{"session_recap"} + env.Force = true + if _, err := (analyzeStage{}).Run(context.Background(), env, m); err != nil { + t.Fatal(err) + } + if _, ok := m.SuppliedProducts.Products[artifacts.ConfiguredArtifactSourceID("session_recap")]; ok { + t.Fatal("supplied authority retained after replacement") + } + if m.Stages["analyze"].AnalyzeArtifacts["session_recap"].Status != manifest.AnalyzeArtifactCurrent { + t.Fatal("replacement has no local checkpoint") + } +} + +func TestAnalyzeForceRetiresSuppliedBeforeAttempt(t *testing.T) { + env, m := suppliedAnalyzeFixture(t) + env.SelectedArtifactKeys = []string{"session_recap"} + env.Force = true + parent := env.Config.ArtifactCatalog.Artifacts["session_recap"] + parent.Inputs = map[string]config.ScriptoriumInputConfig{"missing": {Source: artifacts.ArtifactTranscriptFinal, Required: true}} + env.Config.ArtifactCatalog.Artifacts["session_recap"] = parent + // A missing generation input fails after the retirement checkpoint. + _, err := (analyzeStage{}).Run(context.Background(), env, m) + if err == nil { + t.Fatal("expected missing generation input") + } + if _, ok := m.SuppliedProducts.Products[artifacts.ConfiguredArtifactSourceID("session_recap")]; ok { + t.Fatal("supplied record revived after failed attempt") + } + path := artifacts.SessionManifestPathForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID) + saved, err := env.ManifestStore.Load(context.Background(), path) + if err != nil { + t.Fatal(err) + } + if _, ok := saved.SuppliedProducts.Products[artifacts.ConfiguredArtifactSourceID("session_recap")]; ok { + t.Fatal("retirement was not persisted") + } +} diff --git a/internal/stage/checkpoint.go b/internal/stage/checkpoint.go index affeab9..942ea8a 100644 --- a/internal/stage/checkpoint.go +++ b/internal/stage/checkpoint.go @@ -17,6 +17,18 @@ func checkpointStageCollection( live *manifest.Manifest, stageName string, update func(*manifest.StageRecord) error, +) error { + return checkpointStageCollectionRetiring(ctx, store, path, live, stageName, nil, update) +} + +func checkpointStageCollectionRetiring( + ctx context.Context, + store manifest.Store, + path string, + live *manifest.Manifest, + stageName string, + retired []string, + update func(*manifest.StageRecord) error, ) error { if live == nil { return fmt.Errorf("session manifest is required") @@ -29,6 +41,11 @@ func checkpointStageCollection( } candidate := cloneManifestForCheckpoint(live) + if candidate.SuppliedProducts != nil { + for _, source := range retired { + delete(candidate.SuppliedProducts.Products, source) + } + } if candidate.Stages == nil { candidate.Stages = make(map[string]*manifest.StageRecord) } @@ -63,6 +80,9 @@ func checkpointStageCollection( live.Stages = map[string]*manifest.StageRecord{stageName: savedRecord} } live.UpdatedAt = candidate.UpdatedAt + if len(retired) != 0 { + live.SuppliedProducts = manifest.CloneSuppliedProducts(candidate.SuppliedProducts) + } return nil }