diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 9f7b237..440f1fa 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -732,6 +732,12 @@ requirements. Restore never executes pipeline stages. ## Stage 20 — Reconcile cleanup with diagnostic and bundle retention +**Complete.** Commit: `Preserve current diagnostics during run cleanup`. +Verification: focused cleanup, managed-view, native bundle-retention, and +orchestration tests passed with Go 1.27.4, including link rotation, retained +evidence, unsafe links, publication authorization, cleanup-only execution, +and failure/retry without republishing. + **Read:** roadmap retention and durable lifecycle; [Cleanup Internals](../internal/stage-cleanup.md). Entry points: `cleanup_plan.go`, `cleanup.go`, app cleanup targets, and confined file operations. diff --git a/internal/app/cleanup_orchestration_test.go b/internal/app/cleanup_orchestration_test.go index 69ea886..0aaf990 100644 --- a/internal/app/cleanup_orchestration_test.go +++ b/internal/app/cleanup_orchestration_test.go @@ -149,8 +149,11 @@ func TestCleanupFailurePreservesPublishAndRetriesWithoutRepublishing(t *testing. if !reflect.DeepEqual(summary.Executed, []string{"cleanup"}) || !reflect.DeepEqual(summary.Skipped, []string{"publish", "notify"}) { t.Fatalf("retry summary = %#v", summary) } - if _, statErr := os.Lstat(workspaceTarget); !errors.Is(statErr, os.ErrNotExist) { - t.Fatalf("workspace target stat error = %v, want absent", statErr) + if _, statErr := os.Stat(filepath.Join(workspaceTarget, "publish", "logs")); statErr != nil { + t.Fatalf("latest publish diagnostics missing: %v", statErr) + } + if _, statErr := os.Lstat(filepath.Join(workspaceTarget, "extract")); !errors.Is(statErr, os.ErrNotExist) { + t.Fatalf("unprotected extract data remains: %v", statErr) } } diff --git a/internal/fileops/attempt_views.go b/internal/fileops/attempt_views.go index c2797cc..44815cf 100644 --- a/internal/fileops/attempt_views.go +++ b/internal/fileops/attempt_views.go @@ -138,6 +138,64 @@ func existingManagedView(parent *os.Root, name, category string) (*string, error return &target, nil } +// ManagedAttemptTargets returns run-relative diagnostic directories selected by +// the session's managed navigation links. It never follows link targets. +func ManagedAttemptTargets(sessionRoot, runID string) ([]string, error) { + if err := pathsafe.ValidateOpaqueSegment(runID); err != nil { + return nil, fmt.Errorf("run identity: %w", err) + } + root, err := os.OpenRoot(sessionRoot) + if err != nil { + return nil, err + } + defer root.Close() + var targets []string + for _, category := range []string{"logs", "debug"} { + info, err := root.Lstat(category) + if errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + return nil, err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return nil, fmt.Errorf("managed %s directory is unsafe", category) + } + parent, err := root.OpenRoot(category) + if err != nil { + return nil, err + } + dir, err := parent.Open(".") + if err != nil { + _ = parent.Close() + return nil, err + } + entries, err := dir.ReadDir(-1) + _ = dir.Close() + if err != nil { + _ = parent.Close() + return nil, err + } + for _, entry := range entries { + name := entry.Name() + if err := pathsafe.ValidateOpaqueSegment(name); err != nil { + _ = parent.Close() + return nil, fmt.Errorf("invalid managed %s view %q: %w", category, name, err) + } + target, err := existingManagedView(parent, name, category) + if err != nil { + _ = parent.Close() + return nil, err + } + if target != nil && *target == attemptTarget(runID, name, category) { + targets = append(targets, filepath.Join(name, category)) + } + } + _ = parent.Close() + } + return targets, nil +} + func replaceManagedView(parent *os.Root, name, category, target string) error { if _, err := existingManagedView(parent, name, category); err != nil { return err diff --git a/internal/fileops/attempt_views_test.go b/internal/fileops/attempt_views_test.go index 04f0bf4..0a23764 100644 --- a/internal/fileops/attempt_views_test.go +++ b/internal/fileops/attempt_views_test.go @@ -98,6 +98,22 @@ func TestAttemptViewsRejectConflictingAndUnsafePaths(t *testing.T) { } } +func TestManagedAttemptTargetsRejectForeignLinks(t *testing.T) { + root := t.TempDir() + if _, err := BeginAttemptViews(root, "run-one", "polish"); err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(root, "logs", "polish")); err != nil { + t.Fatal(err) + } + if err := os.Symlink("../../outside", filepath.Join(root, "logs", "polish")); err != nil { + t.Fatal(err) + } + if _, err := ManagedAttemptTargets(root, "run-one"); err == nil { + t.Fatal("accepted foreign diagnostic target") + } +} + func TestAttemptViewsRejectUnsafeIdentities(t *testing.T) { for _, pair := range [][2]string{{"../escape", "polish"}, {"run", "../outside"}, {"run", ""}, {".preflight", "polish"}} { if _, err := BeginAttemptViews(t.TempDir(), pair[0], pair[1]); err == nil { diff --git a/internal/stage/cleanup_retained_bundle.go b/internal/stage/cleanup_retained_bundle.go index afaa812..7d59efd 100644 --- a/internal/stage/cleanup_retained_bundle.go +++ b/internal/stage/cleanup_retained_bundle.go @@ -6,14 +6,14 @@ import ( "fmt" "os" "path/filepath" + "strings" "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/fileops" ) -// cleanRunWithRetainedBundle removes ordinary run data while preserving a -// bundle explicitly marked for the session lifetime. A later whole-session -// removal still removes the retained evidence. +// cleanRunWithRetainedBundle removes unprotected run data while preserving +// managed diagnostic targets and explicitly session-durable bundle evidence. func cleanRunWithRetainedBundle(workspaceRoot, runRoot string, remove bool) (bool, error) { runRoot, err := filepath.Abs(runRoot) if err != nil { @@ -29,72 +29,100 @@ func cleanRunWithRetainedBundle(workspaceRoot, runRoot string, remove bool) (boo if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { return false, fmt.Errorf("unsafe run cleanup directory %q", runRoot) } + runsDir := filepath.Dir(runRoot) + if filepath.Base(runsDir) != "runs" { + return false, fmt.Errorf("invalid run cleanup directory %q", runRoot) + } + sessionRoot := filepath.Dir(runsDir) + targets, err := fileops.ManagedAttemptTargets(sessionRoot, filepath.Base(runRoot)) + if err != nil { + return false, fmt.Errorf("resolve managed diagnostic targets: %w", err) + } + keep := make(map[string]bool, len(targets)+2) + for _, target := range targets { + keep[filepath.Clean(target)] = true + } extract := filepath.Join(runRoot, "extract") info, err = os.Lstat(extract) - if errors.Is(err, os.ErrNotExist) { - if remove { - return true, fileops.RemoveAllUnderRoot(workspaceRoot, runRoot) - } - return true, nil - } - if err != nil { + if err != nil && !errors.Is(err, os.ErrNotExist) { return false, err } - if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { - return false, fmt.Errorf("unsafe extract cleanup directory %q", extract) - } - marker := filepath.Join(extract, "notarius-retention.json") - info, err = os.Lstat(marker) - if errors.Is(err, os.ErrNotExist) { - if remove { - return true, fileops.RemoveAllUnderRoot(workspaceRoot, runRoot) + if err == nil { + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return false, fmt.Errorf("unsafe extract cleanup directory %q", extract) } - return true, nil - } - if err != nil { - return false, err - } - if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { - return false, fmt.Errorf("unsafe Notarius retention marker %q", marker) - } - body, err := fileops.ReadFileBounded(marker, artifacts.MaxExtractionPayloadBytes) - if err != nil { - return false, fmt.Errorf("read Notarius retention marker: %w", err) - } - var record struct { - Role string `json:"role"` - BundleRoot string `json:"bundle_root"` - } - if err := json.Unmarshal(body, &record); err != nil || record.Role != "session_durable" { - return false, fmt.Errorf("invalid Notarius retention marker %q", marker) - } - outputRoot := filepath.Join(extract, "notarius-output") - if err := validateExtractBundleRoot(outputRoot, record.BundleRoot); err != nil { - return false, fmt.Errorf("invalid retained Notarius bundle: %w", err) - } - pending := false - for _, directory := range []struct { - path string - keep map[string]bool - }{ - {runRoot, map[string]bool{"extract": true}}, - {extract, map[string]bool{"notarius-output": true, "notarius-retention.json": true}}, - } { - entries, err := os.ReadDir(directory.path) - if err != nil { + marker := filepath.Join(extract, "notarius-retention.json") + info, err = os.Lstat(marker) + if err != nil && !errors.Is(err, os.ErrNotExist) { return false, err } - for _, entry := range entries { - if directory.keep[entry.Name()] { - continue + if err == nil { + if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { + return false, fmt.Errorf("unsafe Notarius retention marker %q", marker) } - pending = true + body, err := fileops.ReadFileBounded(marker, artifacts.MaxExtractionPayloadBytes) + if err != nil { + return false, fmt.Errorf("read Notarius retention marker: %w", err) + } + var record struct { + Role string `json:"role"` + BundleRoot string `json:"bundle_root"` + } + if err := json.Unmarshal(body, &record); err != nil || record.Role != "session_durable" { + return false, fmt.Errorf("invalid Notarius retention marker %q", marker) + } + if err := validateExtractBundleRoot(filepath.Join(extract, "notarius-output"), record.BundleRoot); err != nil { + return false, fmt.Errorf("invalid retained Notarius bundle: %w", err) + } + keep[filepath.Join("extract", "notarius-output")] = true + keep[filepath.Join("extract", "notarius-retention.json")] = true + } + } + var prune func(string, string) (bool, error) + prune = func(full, relative string) (bool, error) { + if keep[relative] { + return false, nil + } + prefix := relative + if prefix != "" { + prefix += string(filepath.Separator) + } + ancestor := false + for target := range keep { + if strings.HasPrefix(target, prefix) { + ancestor = true + break + } + } + if !ancestor { if remove { - if err := fileops.RemoveAllUnderRoot(workspaceRoot, filepath.Join(directory.path, entry.Name())); err != nil { + if err := fileops.RemoveAllUnderRoot(workspaceRoot, full); err != nil { return false, err } } + return true, nil } + info, err := os.Lstat(full) + if err != nil { + return false, err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return false, fmt.Errorf("unsafe protected cleanup ancestor %q", full) + } + entries, err := os.ReadDir(full) + if err != nil { + return false, err + } + pending := false + for _, entry := range entries { + child := filepath.Join(relative, entry.Name()) + found, err := prune(filepath.Join(full, entry.Name()), child) + if err != nil { + return false, err + } + pending = pending || found + } + return pending, nil } - return pending, nil + return prune(runRoot, "") } diff --git a/internal/stage/cleanup_test.go b/internal/stage/cleanup_test.go index b0cfacb..62d732d 100644 --- a/internal/stage/cleanup_test.go +++ b/internal/stage/cleanup_test.go @@ -10,6 +10,7 @@ import ( "testing" "gitea.maximumdirect.net/eric/narratio/internal/artifacts" + "gitea.maximumdirect.net/eric/narratio/internal/fileops" ) func TestCleanupStageDisabledSelfSkips(t *testing.T) { @@ -26,6 +27,59 @@ func TestCleanupStageDisabledSelfSkips(t *testing.T) { } } +func TestCleanupPreservesLatestViewsAcrossRunsAndRemovesOldDiagnostics(t *testing.T) { + env, m, published := cleanupPlanningFixture(t) + env.Config.Pipeline.Workspace.CleanupAfterPublish = true + session := artifacts.NewLocalStore(env.Config.Pipeline.Workspace.Root).SessionPathsFor(m.Campaign, m.SessionID) + if err := os.MkdirAll(session.Root, 0o755); err != nil { + t.Fatal(err) + } + if _, err := fileops.BeginAttemptViews(session.Root, published, "polish"); err != nil { + t.Fatal(err) + } + if _, err := fileops.BeginAttemptViews(session.Root, published, "merge"); err != nil { + t.Fatal(err) + } + if _, err := fileops.BeginAttemptViews(session.Root, "newer-run", "merge"); err != nil { + t.Fatal(err) + } + root := artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, published) + kept := filepath.Join(root, "polish", "logs", "audit.log") + old := filepath.Join(root, "merge", "logs", "merge.log") + writeStageTestFile(t, kept, "current") + writeStageTestFile(t, old, "old") + writeStageTestFile(t, filepath.Join(root, "polish", "outputs", "work.json"), "work") + if _, err := (cleanupStage{}).Run(context.Background(), env, m); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(kept); err != nil { + t.Fatalf("latest diagnostic: %v", err) + } + if _, err := os.Stat(old); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("old diagnostic remains: %v", err) + } + validation, err := (cleanupStage{}).ValidateResume(context.Background(), env, m) + if err != nil || !validation.Resumable { + t.Fatalf("retained targets should be resumable: %#v, %v", validation, err) + } + if _, err := fileops.BeginAttemptViews(session.Root, "newer-run", "polish"); err != nil { + t.Fatal(err) + } + validation, err = (cleanupStage{}).ValidateResume(context.Background(), env, m) + if err != nil || validation.Resumable { + t.Fatalf("rotated diagnostics should be eligible: %#v, %v", validation, err) + } + if _, err := (cleanupStage{}).Run(context.Background(), env, m); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(root); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("old run remains after rotation: %v", err) + } + if _, err := os.Stat(filepath.Join(session.Root, "logs", "merge")); err != nil { + t.Fatalf("newer merge view: %v", err) + } +} + func TestCleanupStageRemovesOnlySelectedPublishedRunTarget(t *testing.T) { env, m, publishedRunID := cleanupPlanningFixture(t) env.Config.Pipeline.Workspace.CleanupAfterPublish = true