diff --git a/docs/internal/command-restore.md b/docs/internal/command-restore.md index 26e6b95..f1c1cd6 100644 --- a/docs/internal/command-restore.md +++ b/docs/internal/command-restore.md @@ -52,7 +52,7 @@ Planner behavior: directories, symlinks, and other non-regular targets remain conflicts. For a non-dry-run restore, planning/classification happens only after acquiring -the session lock. Runner manifest/reuse checks acquire that same lock first. +the workspace lock. Runner manifest/reuse checks acquire that same lock first. Previous-cache readiness is resolved through `previouscache.Resolve` for restore, prepare, status, and validation. Each requirement selects the unique diff --git a/docs/internal/overview.md b/docs/internal/overview.md index 3d0c42b..b89fea4 100644 --- a/docs/internal/overview.md +++ b/docs/internal/overview.md @@ -27,14 +27,14 @@ canonical stage sequence through adapter interfaces, while manifests record progress and artifact services resolve durable inputs and outputs. The pipeline runner follows one explicit invocation lifecycle: inspect bounded -prerequisites without mutation, prepare the workspace layout, acquire one -session lock, load or create the authoritative session manifest, complete or +prerequisites without mutation, acquire the workspace lock, prepare the workspace +layout, load or create the authoritative session manifest, complete or reuse selected preparation, check projected downstream work, compose only the collaborators needed by selected work, execute each selected stage in order, finalize terminal state, release resources, and return a possibly partial summary with preserved failure causes. Narrow terminal local persistence detaches cancellation; active work retains the canceled operation context. Cleanup, when selected, is the ordinary final stage rather than runner finalization work. -The lock remains held from manifest initialization through finalization, and a +The lock remains held from layout preparation through finalization, and a failed stage or required manifest save prevents later stages from starting. Standalone preflight shares that lifecycle, runs only preparation, and checks enabled capabilities while holding the same lock. @@ -44,7 +44,7 @@ enabled capabilities while holding the same lock. | Area | Implemented owners | Responsibility | | --- | --- | --- | | Executable | `cmd/narratio` | Process entry, standard stream wiring, argument handoff, and exit status. | -| Application orchestration | `internal/app` | Native CommandKit declarations/reporting, lazy configuration selection, secret-file environment loading, production composition, session locking, planning, execution, restore, and user-facing reporting. | +| Application orchestration | `internal/app` | Native CommandKit declarations/reporting, lazy configuration selection, secret-file environment loading, production composition, workspace locking, planning, execution, restore, and user-facing reporting. | | Configuration | [`internal/config`](configuration.md) | Typed ConfigKit results and lifecycle defaults, imports/overlays, canonical party loading, separate catalog/player/publication derivation, session templating, and validation. | | Pipeline stages | `internal/stage` | Canonical stage registry, shared stage contract, execution dependencies, and implemented stage behavior. | | Glossaries | `internal/glossary` | Native vocabulary resolution, schema validation, party projection, and deterministic documents. | diff --git a/docs/internal/preflight.md b/docs/internal/preflight.md index 45820ff..794491d 100644 --- a/docs/internal/preflight.md +++ b/docs/internal/preflight.md @@ -37,7 +37,7 @@ discovery, and discovery issues produce warnings. Findings survive independent failures and cancellation stops new work. Probe files use invocation-scoped destinations under `runs/`, protected by the -session lock through report consumption, reference verification, and terminal +workspace lock through report consumption, reference verification, and terminal persistence. A later authorized cleanup can remove those files without removing durable prepared inputs. See [workspace internals](workspace.md), [CLI](../cli.md#preflight), and [operations](../operations.md#prompt-requirements-preflight). diff --git a/docs/internal/workspace.md b/docs/internal/workspace.md index aa0bfa2..dc24da7 100644 --- a/docs/internal/workspace.md +++ b/docs/internal/workspace.md @@ -46,11 +46,14 @@ session run-history cleanup, and are excluded from publish and restore enumerati ## Locking -`artifacts.LocalStore` enforces the single-writer session lock via an -operating-system lock held on `.lock` (`ErrLockConflict` on contention). The +`artifacts.LocalStore` enforces single-writer workspace access via an +operating-system lock held on `/.lock` (`ErrLockConflict` on contention). The file retains owner metadata after release or process death; its existence is -not evidence that a lock is active. Command and restore flows wait for this -lock only while their context remains active, and report a release failure. +not evidence that a lock is active. Runs, preflight, mutating restore, and +manual cleanup acquire it before creating or changing managed session state. +Initialization targeting managed work also acquires it. They wait only while +their context remains active and report a release failure. Read-only inspection +and dry runs do not acquire it; separate workspaces remain independent. Standalone preflight holds the same lock through preparation, readiness probes, and finalization, keeping active probe files outside concurrent cleanup. Preparation uses ordinary manifest transitions and invalidation. diff --git a/docs/operations.md b/docs/operations.md index 7e3aefe..9f369bd 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -137,7 +137,7 @@ not rerun; otherwise it uses a synthetic input. These checks do not establish real-transcript feasibility, editorial quality, or future provider availability. See [Audita](integrations/audita.md) and [Scriptorium](integrations/scriptorium.md). -The session lock covers preparation, probes, and finalization. Probe diagnostics +The workspace lock covers preparation, probes, and finalization. Probe diagnostics under `runs/` are disposable and can be removed by a later authorized cleanup; prepared inputs remain durable. Preflight itself does not run cleanup or rotate processing-stage diagnostic views. See [cleanup](#cleanup). @@ -737,6 +737,9 @@ the session workload. Use `narratio session clean SESSION` to remove an entire local session, or `narratio session clean --all` for all local sessions. Add `--dry-run` to inspect planned targets. These commands do not delete subprocess caches or remote data. +Mutating cleanup waits for the same workspace lock used by runs, preflight, and +restore. Waiting can be cancelled; dry-run inspection does not take the lock. +The lock file remains at `/.lock` after cleanup. Automatic cleanup requires `workspace.cleanup_after_publish=true` and successful publication evidence. When selected, it removes the entire session `runs/` tree, diff --git a/docs/policy/architecture.md b/docs/policy/architecture.md index f84688f..bf1db19 100644 --- a/docs/policy/architecture.md +++ b/docs/policy/architecture.md @@ -74,7 +74,7 @@ itself an architectural goal. ## Ownership And Dependency Direction The application boundary owns command composition, configuration selection, -production composition, session locking, and top-level lifecycle. It may depend +production composition, workspace locking, and top-level lifecycle. It may depend on concrete implementations to assemble a run. Stage orchestration expresses intent in Narratio-level data and interfaces. @@ -131,7 +131,7 @@ not configurable. Downstream readiness is an invocation check after selected preparation and before the selected processing work. It does not create a stage success. Standalone preflight prepares or reuses session inputs and checks enabled -capabilities under the same session lock; its checks may probe destinations and +capabilities under the same workspace lock; its checks may probe destinations and contact configured providers. A stage may explicitly self-skip with a stable reason and no outputs. That diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 0e18d39..70a7901 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -131,6 +131,10 @@ Release/process exit permits later acquisition, and deleting a session or the ## Stage 3: Coordinate runners, restore, preflight, and manual cleanup +**Complete:** Mutating commands acquire the workspace lock before managed work; +controlled command-level tests cover cleanup, cancellation, new admission, and +managed initialization. Application, artifact, and documentation checks pass. + Read: - `audit/08-testing.md`, lines 170–201 (TE-04). diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 87b5c05..c9114d1 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -795,21 +795,21 @@ narratio run 2026-04-04 --stage prepare --force Relevant reference: [Operations: Restore Workflow](./operations.md#restore-workflow). -## Session lock conflict (`.lock`) +## Workspace lock wait (`.lock`) Symptom: -- command fails acquiring session lock. +- a mutating command waits for the workspace lock or is cancelled while waiting. Likely causes: -- another process is running for the same session; +- another process is mutating the same workspace; - a process still holds the operating-system lock while it is shutting down. Diagnostics: ```bash -ls -l {workspace.root}/work/{campaign}/{session_id}/.lock +ls -l {workspace.root}/.lock ps aux | grep narratio ``` diff --git a/internal/app/clean_command.go b/internal/app/clean_command.go index cee23fa..f3011b1 100644 --- a/internal/app/clean_command.go +++ b/internal/app/clean_command.go @@ -85,6 +85,14 @@ func cleanSelectedSession(ctx context.Context, input *cleanCommandInput, deps co if err != nil { return report, err } + if !input.DryRun { + store := deps.newWorkspaceStore(pipeline.Workspace.Root) + lock, lockErr := store.AcquireWorkspaceLockContext(ctx) + if lockErr != nil { + return report, fmt.Errorf("clean: acquire workspace lock: %w", lockErr) + } + defer func() { err = errors.Join(err, store.ReleaseWorkspaceLock(lock)) }() + } appendTarget := func(root, target, policy string, directory bool) error { if err := ctx.Err(); err != nil { return err diff --git a/internal/app/clean_lock_test.go b/internal/app/clean_lock_test.go new file mode 100644 index 0000000..c19ee61 --- /dev/null +++ b/internal/app/clean_lock_test.go @@ -0,0 +1,235 @@ +package app + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "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" + "go.maximumdirect.net/commandkit" +) + +type observedWorkspaceStore struct { + artifacts.Store + entering chan struct{} + acquired chan struct{} + proceed <-chan struct{} +} + +func (s *observedWorkspaceStore) AcquireWorkspaceLockContext(ctx context.Context) (*artifacts.LockHandle, error) { + if s.entering != nil { + lock, err := s.Store.AcquireWorkspaceLock() + if !errors.Is(err, artifacts.ErrLockConflict) { + return lock, err + } + close(s.entering) + } + lock, err := s.Store.AcquireWorkspaceLockContext(ctx) + if err == nil && s.acquired != nil { + close(s.acquired) + <-s.proceed + } + return lock, err +} + +type waitingPrepare struct { + entered chan struct{} + release <-chan struct{} +} + +func (s waitingPrepare) Name() string { return "prepare" } +func (s waitingPrepare) Run(ctx context.Context, _ *stage.Env, _ *manifest.Manifest) (*stage.StageResult, error) { + close(s.entered) + select { + case <-s.release: + return &stage.StageResult{}, nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func TestManualCleanWaitsForActiveInvocation(t *testing.T) { + for _, all := range []bool{false, true} { + t.Run(map[bool]string{false: "session", true: "all"}[all], func(t *testing.T) { + root := t.TempDir() + pipeline, campaign, session := writeValidConfigFiles(t, root) + cfg, err := config.Load(pipeline, campaign, session) + if err != nil { + t.Fatal(err) + } + entered, release := make(chan struct{}), make(chan struct{}) + running := make(chan error, 1) + go func() { + _, err := executePlan(context.Background(), cfg, BoundedPlan{stages: []stage.Stage{waitingPrepare{entered, release}}}, RunOptions{}) + running <- err + }() + select { + case <-entered: + case err := <-running: + t.Fatalf("runner stopped: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("runner did not enter") + } + work := artifacts.SessionWorkDirForCampaign(root, cfg.Session.Campaign, cfg.Session.SessionID) + attempted := make(chan struct{}) + deps := commandDependencies{newWorkspaceStore: func(root string) artifacts.Store { + return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attempted} + }} + app, err := newApplication(deps, executePlan) + if err != nil { + t.Fatal(err) + } + args := []string{"session", "clean", cfg.Session.SessionID, "--config", pipeline, "--campaign-file", campaign, "--session-file", session} + if all { + args = []string{"session", "clean", "--all", "--config", pipeline} + } + ctx, cancel := context.WithCancel(context.Background()) + result := make(chan commandkit.Outcome, 1) + go func() { + result <- app.Execute(ctx, args, commandkit.Streams{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}}) + }() + select { + case <-attempted: + case <-time.After(5 * time.Second): + t.Fatal("cleanup did not attempt lock") + } + if _, err := os.Stat(work); err != nil { + t.Fatalf("active work removed: %v", err) + } + cancel() + select { + case out := <-result: + if out.Status == 0 { + t.Fatal("cancelled clean succeeded") + } + case <-time.After(5 * time.Second): + t.Fatal("cleanup did not cancel") + } + if _, err := os.Stat(work); err != nil { + t.Fatalf("cancelled clean removed work: %v", err) + } + attemptedAgain := make(chan struct{}) + retryApp, err := newApplication(commandDependencies{newWorkspaceStore: func(root string) artifacts.Store { + return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attemptedAgain} + }}, executePlan) + if err != nil { + t.Fatal(err) + } + retry := make(chan commandkit.Outcome, 1) + go func() { + retry <- retryApp.Execute(context.Background(), args, commandkit.Streams{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}}) + }() + select { + case <-attemptedAgain: + case <-time.After(5 * time.Second): + t.Fatal("cleanup retry did not wait for lock") + } + close(release) + if err := <-running; err != nil { + t.Fatal(err) + } + if outcome := <-retry; outcome.Status != 0 { + t.Fatalf("cleanup failed: status %d", outcome.Status) + } + if _, err := os.Stat(work); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("work remains: %v", err) + } + }) + } +} + +func TestCleanAllBlocksNewSessionAdmission(t *testing.T) { + root := t.TempDir() + pipeline, campaign, session := writeValidConfigFiles(t, root) + cfg, err := config.Load(pipeline, campaign, session) + if err != nil { + t.Fatal(err) + } + cfg.Session.SessionID = "new-session" + acquired, release := make(chan struct{}), make(chan struct{}) + deps := commandDependencies{newWorkspaceStore: func(root string) artifacts.Store { + return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), acquired: acquired, proceed: release} + }} + app, err := newApplication(deps, executePlan) + if err != nil { + t.Fatal(err) + } + done := make(chan commandkit.Outcome, 1) + go func() { + done <- app.Execute(context.Background(), []string{"session", "clean", "--all", "--config", pipeline}, commandkit.Streams{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}}) + }() + select { + case <-acquired: + case <-time.After(5 * time.Second): + t.Fatal("cleanup did not acquire lock") + } + ctx, cancel := context.WithCancel(context.Background()) + attempted := make(chan struct{}) + result := make(chan error, 1) + store := &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attempted} + go func() { + _, err := executeStages(ctx, cfg, nil, RunOptions{Env: &Env{ArtifactStore: store}}) + result <- err + }() + select { + case <-attempted: + case <-time.After(5 * time.Second): + t.Fatal("new invocation did not attempt lock") + } + cancel() + err = <-result + if !errors.Is(err, context.Canceled) { + t.Fatalf("new invocation: %v", err) + } + if _, err := os.Stat(filepath.Join(root, "work")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("new session created work: %v", err) + } + close(release) + if out := <-done; out.Status != 0 { + t.Fatalf("clean status = %d", out.Status) + } +} + +func TestSessionInitWaitsWhenOutputIsManaged(t *testing.T) { + root := t.TempDir() + pipeline, campaign, _ := writeValidConfigFiles(t, root) + store := artifacts.NewLocalStore(root) + lock, err := store.AcquireWorkspaceLock() + if err != nil { + t.Fatal(err) + } + defer store.ReleaseWorkspaceLock(lock) + attempted := make(chan struct{}) + deps := commandDependencies{newWorkspaceStore: func(root string) artifacts.Store { + return &observedWorkspaceStore{Store: artifacts.NewLocalStore(root), entering: attempted} + }} + app, err := newApplication(deps, executePlan) + if err != nil { + t.Fatal(err) + } + output := filepath.Join(root, "work", "sample-campaign", "new", "session.yml") + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan commandkit.Outcome, 1) + go func() { + done <- app.Execute(ctx, []string{"session", "init", "2026-06-07", "--config", pipeline, "--campaign-file", campaign, "--output", output}, commandkit.Streams{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}}) + }() + select { + case <-attempted: + case <-time.After(5 * time.Second): + t.Fatal("initialization did not attempt lock") + } + cancel() + if out := <-done; out.Status == 0 { + t.Fatal("cancelled initialization succeeded") + } + if _, err := os.Stat(output); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("output created: %v", err) + } +} diff --git a/internal/app/command_dependencies.go b/internal/app/command_dependencies.go index 5806d5a..4ab2006 100644 --- a/internal/app/command_dependencies.go +++ b/internal/app/command_dependencies.go @@ -7,6 +7,7 @@ import ( "gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius" "gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium" "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" + "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/config" "gitea.maximumdirect.net/eric/narratio/internal/logging" configkit "go.maximumdirect.net/configkit" @@ -18,6 +19,7 @@ type commandDependencies struct { preparePipelineSource func(configkit.Source) (*configkit.SecretsReport, configkit.Source, error) loadPipelineSource func(configkit.Source, config.PipelineLoadOptions) (*config.PipelineConfig, error) newObjectStore func(context.Context, *config.Config) (storage.ObjectStore, error) + newWorkspaceStore func(string) artifacts.Store newScriptorium func() scriptorium.Runner newAudita func(*config.Config) (audita.Runner, error) newNotarius func() notarius.Runner @@ -38,6 +40,9 @@ func normalizeCommandDependencies(deps commandDependencies) commandDependencies if deps.newObjectStore == nil { deps.newObjectStore = storage.NewObjectStoreFromConfig } + if deps.newWorkspaceStore == nil { + deps.newWorkspaceStore = func(root string) artifacts.Store { return artifacts.NewLocalStore(root) } + } if deps.newAudita == nil { deps.newAudita = buildDefaultAuditaRunner } diff --git a/internal/app/restore_command.go b/internal/app/restore_command.go index 2e7f4c6..2684215 100644 --- a/internal/app/restore_command.go +++ b/internal/app/restore_command.go @@ -96,22 +96,22 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl } artifactStore := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root) - if _, err := artifactStore.EnsureLayoutFor(cfg.Session.Campaign, cfg.Session.SessionID); err != nil { - return diagnostic, fmt.Errorf("restore: prepare workdir: %w", err) - } lock, err := artifactStore.AcquireWorkspaceLockContext(ctx) if err != nil { - return diagnostic, fmt.Errorf("restore: acquire session lock: %w", err) + return diagnostic, fmt.Errorf("restore: acquire workspace lock: %w", err) } defer func() { if releaseErr := artifactStore.ReleaseWorkspaceLock(lock); releaseErr != nil { if resultErr == nil { - resultErr = fmt.Errorf("restore: release session lock: %w", releaseErr) + resultErr = fmt.Errorf("restore: release workspace lock: %w", releaseErr) } else { - resultErr = errors.Join(resultErr, fmt.Errorf("restore: release session lock: %w", releaseErr)) + resultErr = errors.Join(resultErr, fmt.Errorf("restore: release workspace lock: %w", releaseErr)) } } }() + if _, err := artifactStore.EnsureLayoutFor(cfg.Session.Campaign, cfg.Session.SessionID); err != nil { + return diagnostic, fmt.Errorf("restore: prepare workdir: %w", err) + } if _, _, err := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, manifestPath); err != nil { return diagnostic, fmt.Errorf("restore: %w", err) } diff --git a/internal/app/restore_recovery_test.go b/internal/app/restore_recovery_test.go index 21548a4..8c82296 100644 --- a/internal/app/restore_recovery_test.go +++ b/internal/app/restore_recovery_test.go @@ -48,8 +48,8 @@ func TestRestoreHoldsTransitionLockBeforePlanning(t *testing.T) { runnerCtx, cancelRunner := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancelRunner() - if _, err := executeStages(runnerCtx, cfg, nil, RunOptions{}); err == nil || !strings.Contains(err.Error(), "acquire session lock") { - t.Fatalf("runner while restore plans error = %v, want session-lock failure", err) + if _, err := executeStages(runnerCtx, cfg, nil, RunOptions{}); err == nil || !strings.Contains(err.Error(), "acquire workspace lock") { + t.Fatalf("runner while restore plans error = %v, want workspace-lock failure", err) } close(releasePlanning) diff --git a/internal/app/runner.go b/internal/app/runner.go index 85420b3..3d179c6 100644 --- a/internal/app/runner.go +++ b/internal/app/runner.go @@ -64,23 +64,22 @@ func withLockedInvocation(ctx context.Context, cfg *config.Config, plan BoundedP if _, _, err := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, runtime.manifestPath); err != nil { return nil, err } - if err := prepareInvocationLayout(runtime); err != nil { - return nil, err - } - lock, err := runtime.artifactStore.AcquireWorkspaceLockContext(ctx) if err != nil { - return nil, fmt.Errorf("acquire session lock: %w", err) + return nil, fmt.Errorf("acquire workspace lock: %w", err) } defer func() { if releaseErr := runtime.artifactStore.ReleaseWorkspaceLock(lock); releaseErr != nil { if resultErr == nil { - resultErr = fmt.Errorf("release session lock: %w", releaseErr) + resultErr = fmt.Errorf("release workspace lock: %w", releaseErr) } else { - resultErr = errors.Join(resultErr, fmt.Errorf("release session lock: %w", releaseErr)) + resultErr = errors.Join(resultErr, fmt.Errorf("release workspace lock: %w", releaseErr)) } } }() + if err := prepareInvocationLayout(runtime); err != nil { + return nil, err + } defer func() { if runtime.started { result, resultErr = finalizeInvocation(runtime, resultErr) diff --git a/internal/app/session_init_command.go b/internal/app/session_init_command.go index 15d4684..39a36cd 100644 --- a/internal/app/session_init_command.go +++ b/internal/app/session_init_command.go @@ -172,6 +172,18 @@ func initializeSession(ctx context.Context, request *sessionInitializationInput, return report, err } if !remote { + managed, err := pathInsideManagedWork(base.Pipeline.Workspace.Root, output) + if err != nil { + return report, fmt.Errorf("session init: resolve output: %w", err) + } + if managed { + store := deps.newWorkspaceStore(base.Pipeline.Workspace.Root) + lock, lockErr := store.AcquireWorkspaceLockContext(ctx) + if lockErr != nil { + return report, fmt.Errorf("session init: acquire workspace lock: %w", lockErr) + } + defer func() { err = errors.Join(err, store.ReleaseWorkspaceLock(lock)) }() + } if err := writeLocalFile(output, data, force); err != nil { return report, fmt.Errorf("session init: %w", err) } @@ -210,3 +222,60 @@ func initializeSession(ctx context.Context, request *sessionInitializationInput, report = &sessionInitializationReport{Campaign: config.CampaignID(base.Campaign), SessionID: sessionID, Destination: "s3://" + s3BucketName(base.Pipeline) + "/" + key, Remote: true, Written: true} return report, nil } + +// pathInsideManagedWork resolves existing ancestors so aliases to the work tree +// participate in the same coordination as paths written directly beneath it. +func pathInsideManagedWork(workspace, output string) (bool, error) { + within := func(work, target string) (bool, error) { + relative, err := filepath.Rel(work, target) + if err != nil { + return false, err + } + return relative == "." || (relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))), nil + } + workPath, err := filepath.Abs(filepath.Join(workspace, config.PathWorkDirSegment)) + if err != nil { + return false, err + } + outputPath, err := filepath.Abs(output) + if err != nil { + return false, err + } + if inside, err := within(workPath, outputPath); inside || err != nil { + return inside, err + } + resolve := func(path string) (string, error) { + absolute, err := filepath.Abs(path) + if err != nil { + return "", err + } + candidate := absolute + for { + resolved, err := filepath.EvalSymlinks(candidate) + if err == nil { + rest, relErr := filepath.Rel(candidate, absolute) + if relErr != nil { + return "", relErr + } + return filepath.Join(resolved, rest), nil + } + if !errors.Is(err, os.ErrNotExist) { + return "", err + } + parent := filepath.Dir(candidate) + if parent == candidate { + return "", err + } + candidate = parent + } + } + work, err := resolve(filepath.Join(workspace, config.PathWorkDirSegment)) + if err != nil { + return false, err + } + target, err := resolve(output) + if err != nil { + return false, err + } + return within(work, target) +}