diff --git a/docs/roadmap/audit/catalog.md b/docs/roadmap/audit/catalog.md index dbafdae..4f1fafe 100644 --- a/docs/roadmap/audit/catalog.md +++ b/docs/roadmap/audit/catalog.md @@ -41,10 +41,10 @@ their scope. Unless assigned otherwise, a finding remains independent audit remediation. Shared code does not make a refactoring a prerequisite or assign the whole finding to a roadmap. -Thirty-seven entries are closed by the safety, transfer, audio discovery, S3 +Thirty-eight entries are closed by the safety, transfer, audio discovery, S3 planning, prerequisite-history, publication-import, CLI classification, inspection aggregation, test maintenance, dead-code removal, and associated -documentation work; 6 remain open. **Planned** identifies +documentation work; 5 remain open. **Planned** identifies an agreed remedy awaiting implementation. **Potentially eliminated** requires verification that the offending lifecycle is removed. **Coordinate** identifies shared changes, not a commitment that a related feature implements the entire finding. Findings close only after their @@ -772,7 +772,13 @@ confinement coverage. ### CAT-27 — P3: Index repeated previous-input and prepared-record lookups -Status: Open +Status: Closed + +**Closure.** Previous publication declarations and optional absence use +operation-local indexes; prepared and previous input resolution share an +input-snapshot lookup retaining ordered candidates and verifying file contents. +The previous-cache, artifact, stage, and app package tests pass, including +snapshot replacement and content revalidation coverage. **Disposition / owner.** Coordinate — [inventory-based import](../../internal/command-restore.md) changed previous-input discovery and prepared-record consumers. Reassess the diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index e6396b4..425859a 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -614,6 +614,8 @@ Validation: `go test ./internal/previouscache ./internal/app ./internal/stage`. ## Stage 23: Index Manifest Input Selection Within A Phase +Status: Complete. + CAT IDs: CAT-27, completion. Status: Pending. Read Stage 22's EF-03 section and `artifacts/prepared_input.go`, diff --git a/internal/artifacts/artifact_resolver.go b/internal/artifacts/artifact_resolver.go index f41eba2..3cdfef1 100644 --- a/internal/artifacts/artifact_resolver.go +++ b/internal/artifacts/artifact_resolver.go @@ -263,6 +263,13 @@ func ResolvePreviousSessionArtifactWithCatalog( m *manifest.Manifest, source string, catalog *ArtifactCatalog, +) (ResolvedSessionArtifact, error) { + return ResolvePreviousSessionArtifactWithLookup(paths, NewInputLookup(paths, m), source, catalog) +} + +// ResolvePreviousSessionArtifactWithLookup resolves from one input snapshot. +func ResolvePreviousSessionArtifactWithLookup( + paths SessionPaths, lookup *InputLookup, source string, catalog *ArtifactCatalog, ) (ResolvedSessionArtifact, error) { artifactName, ok := PreviousSessionArtifactName(source) if !ok { @@ -275,15 +282,9 @@ func ResolvePreviousSessionArtifactWithCatalog( if _, ok := catalog.Lookup(ConfiguredArtifactSourceID(artifactName)); !ok { return ResolvedSessionArtifact{}, fmt.Errorf("unsupported previous-session artifact source %q", source) } - if m == nil { - return ResolvedSessionArtifact{}, &SessionArtifactNotFoundError{ArtifactID: source} - } var selected manifest.InputRecord count := 0 - for _, input := range m.Inputs { - if input.Kind != "previous_artifact" || input.Source != source { - continue - } + for _, input := range lookup.bySource[inputSourceKey{"previous_artifact", source}] { candidate := filepath.Clean(ResolveSessionLocalPathForRead(paths, input.Path)) if strings.TrimSpace(candidate) == "" { continue diff --git a/internal/artifacts/input_lookup.go b/internal/artifacts/input_lookup.go new file mode 100644 index 0000000..a03458f --- /dev/null +++ b/internal/artifacts/input_lookup.go @@ -0,0 +1,39 @@ +package artifacts + +import ( + "path/filepath" + "strings" + + "gitea.maximumdirect.net/eric/narratio/internal/manifest" +) + +type inputSourceKey struct{ kind, source string } + +// InputLookup holds candidate records for one manifest input snapshot. Construct +// a new lookup whenever the manifest's inputs are replaced. +type InputLookup struct { + byKind map[string][]manifest.InputRecord + bySource map[inputSourceKey][]manifest.InputRecord + byPath map[string][]manifest.InputRecord +} + +// NewInputLookup indexes candidates without validating their content or paths. +func NewInputLookup(paths SessionPaths, m *manifest.Manifest) *InputLookup { + lookup := &InputLookup{byKind: make(map[string][]manifest.InputRecord), bySource: make(map[inputSourceKey][]manifest.InputRecord), byPath: make(map[string][]manifest.InputRecord)} + if m == nil { + return lookup + } + root, rootErr := filepath.Abs(strings.TrimSpace(paths.Root)) + for _, record := range m.Inputs { + kind := strings.TrimSpace(record.Kind) + lookup.byKind[kind] = append(lookup.byKind[kind], record) + key := inputSourceKey{record.Kind, record.Source} + lookup.bySource[key] = append(lookup.bySource[key], record) + if rootErr == nil && strings.TrimSpace(paths.Root) != "" { + if resolved, err := resolvePreparedManifestPath(paths, record.Path, filepath.Clean(root)); err == nil { + lookup.byPath[resolved] = append(lookup.byPath[resolved], record) + } + } + } + return lookup +} diff --git a/internal/artifacts/prepared_input.go b/internal/artifacts/prepared_input.go index 1688c5e..ddad171 100644 --- a/internal/artifacts/prepared_input.go +++ b/internal/artifacts/prepared_input.go @@ -46,6 +46,11 @@ type PreparedInputIdentity struct { // ResolvePreparedInput resolves a prepared stable source exclusively from its // current manifest record and verifies the canonical file's identity. func ResolvePreparedInput(paths SessionPaths, m *manifest.Manifest, sourceID string) (PreparedInputIdentity, error) { + return ResolvePreparedInputWithLookup(paths, NewInputLookup(paths, m), sourceID) +} + +// ResolvePreparedInputWithLookup resolves a source against one input snapshot. +func ResolvePreparedInputWithLookup(paths SessionPaths, lookup *InputLookup, sourceID string) (PreparedInputIdentity, error) { descriptor, ok := artifactpolicy.DescribePreparedInputSource(sourceID) if !ok { if sourceID == artifactpolicy.SourceInputGlossary { @@ -59,27 +64,13 @@ func ResolvePreparedInput(paths SessionPaths, m *manifest.Manifest, sourceID str return PreparedInputIdentity{}, err } - matching := make([]manifest.InputRecord, 0, 1) - if m != nil { - for _, record := range m.Inputs { - if strings.TrimSpace(record.Kind) == descriptor.ManifestKind { - matching = append(matching, record) - } - } - } + matching := lookup.byKind[descriptor.ManifestKind] if len(matching) == 0 { - if m != nil { - for _, record := range m.Inputs { - recordedPath, pathErr := resolvePreparedManifestPath(paths, record.Path, rootPath) - if pathErr == nil && recordedPath == canonicalPath { - return PreparedInputIdentity{}, fmt.Errorf( - "prepared input source %q canonical path is recorded with manifest kind %q, want %q", - descriptor.SourceID, - strings.TrimSpace(record.Kind), - descriptor.ManifestKind, - ) - } - } + if records := lookup.byPath[canonicalPath]; len(records) > 0 { + return PreparedInputIdentity{}, fmt.Errorf( + "prepared input source %q canonical path is recorded with manifest kind %q, want %q", + descriptor.SourceID, strings.TrimSpace(records[0].Kind), descriptor.ManifestKind, + ) } return PreparedInputIdentity{}, &PreparedInputAbsentError{SourceID: descriptor.SourceID} } diff --git a/internal/artifacts/prepared_input_test.go b/internal/artifacts/prepared_input_test.go index 330f5c1..221b075 100644 --- a/internal/artifacts/prepared_input_test.go +++ b/internal/artifacts/prepared_input_test.go @@ -240,3 +240,22 @@ func TestResolvePreparedGlossaryDocuments(t *testing.T) { t.Fatalf("retired source: %v", err) } } + +func TestInputLookupKeepsSnapshotAndRechecksFileContent(t *testing.T) { + paths, m, file, _ := preparedInputFixture(t, artifactpolicy.SourceInputParty, []byte("party: ready\n")) + m.Inputs = append(m.Inputs, manifest.InputRecord{Kind: "unrelated", Path: "../../outside"}) + lookup := NewInputLookup(paths, m) + m.Inputs = nil + if _, err := ResolvePreparedInputWithLookup(paths, lookup, artifactpolicy.SourceInputParty); err != nil { + t.Fatalf("snapshot resolution: %v", err) + } + if _, err := ResolvePreparedInputWithLookup(paths, NewInputLookup(paths, m), artifactpolicy.SourceInputParty); !errors.Is(err, ErrPreparedInputAbsent) { + t.Fatalf("replaced inputs: %v", err) + } + if err := os.WriteFile(file, []byte("party: changed\n"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := ResolvePreparedInputWithLookup(paths, lookup, artifactpolicy.SourceInputParty); err == nil || !strings.Contains(err.Error(), "checksum mismatch") { + t.Fatalf("changed content: %v", err) + } +} diff --git a/internal/stage/analyze.go b/internal/stage/analyze.go index 60a10e2..34ddcda 100644 --- a/internal/stage/analyze.go +++ b/internal/stage/analyze.go @@ -37,6 +37,7 @@ type analyzeArtifactExecutionResult struct { } type analyzeExecutionContext struct { + InputLookup *artifacts.InputLookup Graph *artifactdeps.Graph Env *Env Manifest *manifest.Manifest @@ -124,6 +125,7 @@ func (analyzeStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S SessionID: sessionID, TranscriptRefs: discoverAnalyzeTranscriptRefs(m, paths), Catalog: runtimeCatalog, + InputLookup: artifacts.NewInputLookup(paths, m), } reconciliation, err := reconcileAnalyzeArtifacts(scriptoriumCfg, execution) if err != nil { diff --git a/internal/stage/analyze_fingerprint.go b/internal/stage/analyze_fingerprint.go index e6d49a8..907cda7 100644 --- a/internal/stage/analyze_fingerprint.go +++ b/internal/stage/analyze_fingerprint.go @@ -131,6 +131,9 @@ func computeAnalyzeArtifactFingerprint( scriptoriumCfg *config.ScriptoriumConfig, execution analyzeExecutionContext, ) (string, resolvedAnalyzeInputs, []analyzeDependencyOutputIdentity, error) { + if execution.InputLookup == nil { + execution.InputLookup = artifacts.NewInputLookup(execution.Paths, execution.Manifest) + } artifactCfg, ok := artifactCfgMap(execution)[key] if !ok { return "", resolvedAnalyzeInputs{}, nil, fmt.Errorf("configured artifact %q is not defined", key) diff --git a/internal/stage/analyze_input_identity.go b/internal/stage/analyze_input_identity.go index cb705ff..8c10d94 100644 --- a/internal/stage/analyze_input_identity.go +++ b/internal/stage/analyze_input_identity.go @@ -75,6 +75,9 @@ func resolveAnalyzeInputIdentities( inputs map[string]config.ScriptoriumInputConfig, execution analyzeExecutionContext, ) (resolvedAnalyzeInputs, error) { + if execution.InputLookup == nil { + execution.InputLookup = artifacts.NewInputLookup(execution.Paths, execution.Manifest) + } result := resolvedAnalyzeInputs{ Ordered: make([]analyzeInputIdentity, 0, len(inputs)), paths: make(map[string]string, len(inputs)), @@ -115,7 +118,7 @@ func resolveAnalyzeInputIdentity( } if descriptor.Source.Kind == artifactpolicy.SourceKindStableInput { - prepared, preparedErr := artifacts.ResolvePreparedInput(execution.Paths, execution.Manifest, descriptor.Source.ID) + prepared, preparedErr := artifacts.ResolvePreparedInputWithLookup(execution.Paths, execution.InputLookup, descriptor.Source.ID) if preparedErr == nil { identity.Present = true identity.Checksum = prepared.Checksum @@ -143,8 +146,8 @@ func resolveAnalyzeInputIdentity( var resolved artifacts.ResolvedSessionArtifact if descriptor.Source.Kind == artifactpolicy.SourceKindPreviousArtifact { - resolved, err = artifacts.ResolvePreviousSessionArtifactWithCatalog( - execution.Paths, execution.Manifest, descriptor.Source.ID, execution.Catalog, + resolved, err = artifacts.ResolvePreviousSessionArtifactWithLookup( + execution.Paths, execution.InputLookup, descriptor.Source.ID, execution.Catalog, ) } else { resolved, err = artifacts.ResolveSessionArtifactWithCatalog( diff --git a/internal/stage/analyze_resume.go b/internal/stage/analyze_resume.go index 921e364..33a9c04 100644 --- a/internal/stage/analyze_resume.go +++ b/internal/stage/analyze_resume.go @@ -54,6 +54,7 @@ func (analyzeStage) ValidateResume(_ context.Context, env *Env, m *manifest.Mani Graph: graph, Env: env, Manifest: m, Paths: paths, SessionID: sessionID, TranscriptRefs: discoverAnalyzeTranscriptRefs(m, paths), Catalog: catalog, + InputLookup: artifacts.NewInputLookup(paths, m), } reconciliation, err := reconcileAnalyzeArtifacts(cfg, execution) if err != nil { diff --git a/internal/stage/extract_references.go b/internal/stage/extract_references.go index 67056ee..83d31a7 100644 --- a/internal/stage/extract_references.go +++ b/internal/stage/extract_references.go @@ -263,10 +263,11 @@ func resolveExtractReferences( Bindings: make([]notarius.ReferenceBinding, 0, len(configured)), Identities: make([]extractReferenceIdentity, 0, len(configured)), } + lookup := artifacts.NewInputLookup(paths, m) for _, reference := range configured { selector := reference.selector sourceID := reference.sourceID - identity, err := artifacts.ResolvePreparedInput(paths, m, sourceID) + identity, err := artifacts.ResolvePreparedInputWithLookup(paths, lookup, sourceID) if err != nil { return resolvedExtractReferences{}, fmt.Errorf( "reference %q source %q is unavailable or invalid; run narratio run %s --stage prepare --force: %w", diff --git a/internal/stage/polish_context.go b/internal/stage/polish_context.go index 772b0a5..55d0333 100644 --- a/internal/stage/polish_context.go +++ b/internal/stage/polish_context.go @@ -37,8 +37,9 @@ func polishGlossaryEvidence(paths artifacts.SessionPaths, m *manifest.Manifest) Source, Checksum string Size int64 } + lookup := artifacts.NewInputLookup(paths, m) for _, descriptor := range artifactpolicy.GlossaryInputSources() { - identity, err := artifacts.ResolvePreparedInput(paths, m, descriptor.SourceID) + identity, err := artifacts.ResolvePreparedInputWithLookup(paths, lookup, descriptor.SourceID) if err != nil { return nil, "", fmt.Errorf("prepared glossary %s is unavailable or invalid; run prepare: %w", descriptor.SourceID, err) } diff --git a/internal/stage/prepare_resume.go b/internal/stage/prepare_resume.go index 08b97aa..8945158 100644 --- a/internal/stage/prepare_resume.go +++ b/internal/stage/prepare_resume.go @@ -68,8 +68,9 @@ func (prepareStage) ValidateResume(ctx context.Context, env *Env, m *manifest.Ma return NonResumable(fmt.Sprintf("prepared sources could not be verified; rerun prepare: %v", err)), nil } paths := sessionPathsForEnv(env, m.SessionID) + lookup := artifacts.NewInputLookup(paths, m) for _, source := range []string{artifactpolicy.SourceInputGlossaryParty, artifactpolicy.SourceInputGlossaryCampaign, artifactpolicy.SourceInputGlossarySetting, artifactpolicy.SourceInputGlossarySpells, artifactpolicy.SourceInputGlossaryCombined} { - if _, err := artifacts.ResolvePreparedInput(paths, m, source); err != nil { + if _, err := artifacts.ResolvePreparedInputWithLookup(paths, lookup, source); err != nil { return NonResumable(prepareResumeChangedReason), nil } } diff --git a/internal/stage/publish_sources.go b/internal/stage/publish_sources.go index e410596..dd52d05 100644 --- a/internal/stage/publish_sources.go +++ b/internal/stage/publish_sources.go @@ -43,6 +43,7 @@ func collectPublishPreparedInputs(store artifacts.Store, paths artifacts.Session filenames[combined.ManifestKind] = combined.Filename glossaries[combined.ManifestKind] = combined var result []publishUploadFile + lookup := artifacts.NewInputLookup(paths, &manifest.Manifest{Inputs: records}) seen := make(map[string]bool) for _, record := range records { name, ok := filenames[record.Kind] @@ -57,7 +58,7 @@ func collectPublishPreparedInputs(store artifacts.Store, paths artifacts.Session return nil, fmt.Errorf("prepared input %q lacks canonical path or checksum", record.Kind) } if descriptor, ok := glossaries[record.Kind]; ok { - if _, err := artifacts.ResolvePreparedInput(paths, &manifest.Manifest{Inputs: records}, descriptor.SourceID); err != nil { + if _, err := artifacts.ResolvePreparedInputWithLookup(paths, lookup, descriptor.SourceID); err != nil { return nil, fmt.Errorf("verify prepared glossary: %w", err) } }