diff --git a/docs/cli.md b/docs/cli.md index c413128d..2388aaf3 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -194,8 +194,11 @@ Every submission, including agent-issued `submit`/`rpc`, still uses server valid ## Drafts in the TUI The server runs one active run per resolved workspace, including overlapping -parent/descendant directories (and symlink aliases). Separate sibling worktrees -remain independent. A new request key in a +parent/descendant directories of one repository (and symlink aliases). Separate +sibling worktrees, and separate repositories nested in one another, remain +independent. Two folders outside any repository overlap only when they are the +same folder or one lies within the other run's declared write paths. A new +request key in a different workspace is admitted immediately and executes concurrently; a second run in a workspace an active run is already changing is refused, naming the conflicting run and advising you to wait or use a different workspace (for diff --git a/docs/harnesses.md b/docs/harnesses.md index 32464916..ce418c6f 100644 --- a/docs/harnesses.md +++ b/docs/harnesses.md @@ -309,8 +309,13 @@ directory that chooses its own account keeps it). - **Failures.** Diagnostics are fixed text. A billing, quota or rate-limit refusal stops the run without retries; a missing sign-in says so. The CLI's redacted stream is kept as the session export and evidence. -- **Recovery.** A server restart during a Claude Code stage stops that process - and fails the visit; it is not reattached. +- **Recovery.** The CLI runs in its own session, writing its stream-json to a + file in the stage's evidence directory, so a restart of the installed server + does not stop it. The next server re-adopts the visit: it keeps reading the + CLI's output, waits for it to finish and continues the run. A CLI that + finished while the server was down is read back from that file; one that + ended without a result marks the run interrupted, saying so (its prompt is + never sent again). An interrupted outcome repair follow-up is asked again. - **Overrides.** `--model` and `--stage-model` must give an `anthropic/` for these stages; the launch is refused otherwise. diff --git a/docs/schedules.md b/docs/schedules.md index 68e68c14..e37fbaa1 100644 --- a/docs/schedules.md +++ b/docs/schedules.md @@ -42,9 +42,14 @@ Edit that schedule explicitly when you want it to use a newer version. never guesses from workflow Markdown or a current pipeline's schedule state. Each dispatch is claimed once. Missed occurrences after downtime are skipped, -not replayed. Workspace conflicts are refused and journaled, not silently run -concurrently or retried as agent work. Use separate workspaces for truly -independent concurrent execution. **Refresh** in Schedules reloads its latest +not replayed. A scheduled run whose workspace another run holds is delayed, +never run concurrently: it is recorded as `delayed` in the schedule's history +and tried again every 5 minutes for up to 2 hours (set +`PIPELINES_SCHEDULE_BUSY_RETRY_EVERY` / `PIPELINES_SCHEDULE_BUSY_RETRY_FOR` on +the server, as Go durations; `0` for FOR skips at once), then recorded as +`started` or `skipped` with the reason. The operator gets a low-priority +notification when a scheduled run is delayed or skipped. Use separate +workspaces for truly independent concurrent execution. **Refresh** in Schedules reloads its latest configuration and next due times. ## JSON API / CLI automation diff --git a/internal/pipeline/run_write_paths.go b/internal/pipeline/run_write_paths.go new file mode 100644 index 00000000..5c9f41fd --- /dev/null +++ b/internal/pipeline/run_write_paths.go @@ -0,0 +1,24 @@ +package pipeline + +import ( + "context" + "encoding/json" +) + +// RunWritePaths returns the write paths a run declared (relative to its +// workspace; empty when it declared none). The workspace reservation check +// reads it only when two runs' workspaces nest outside any repository. +func (s *Store) RunWritePaths(ctx context.Context, id int64) ([]string, error) { + var encoded string + if err := s.db.QueryRowContext(ctx, "SELECT write_paths FROM pipeline_runs WHERE id=?", id).Scan(&encoded); err != nil { + return nil, err + } + var paths []string + if encoded == "" { + return nil, nil + } + if err := json.Unmarshal([]byte(encoded), &paths); err != nil { + return nil, err + } + return paths, nil +} diff --git a/internal/pipeline/runs_create.go b/internal/pipeline/runs_create.go index b990f669..5d782535 100644 --- a/internal/pipeline/runs_create.go +++ b/internal/pipeline/runs_create.go @@ -99,7 +99,7 @@ func (s *Store) CreateRunTitled(ctx context.Context, d *protocol.PipelineDetail, // Acquire the SQLite writer lock while checking the original saved // revision and occurrence. Edits/deletes between claim and admission // invalidate admission, including while a title was being generated. - result, err := tx.ExecContext(ctx, `UPDATE saved_schedule_events SET status='admitted' WHERE schedule_id=? AND due=? AND revision=? AND status='claimed' AND run_id IS NULL AND EXISTS(SELECT 1 FROM saved_schedules WHERE id=? AND revision=? AND enabled=1 AND deleted=0)`, origin.ID, origin.Due.UTC().Format(time.RFC3339Nano), origin.Revision, origin.ID, origin.Revision) + result, err := tx.ExecContext(ctx, `UPDATE saved_schedule_events SET status='admitted' WHERE schedule_id=? AND due=? AND revision=? AND status IN ('claimed','delayed') AND run_id IS NULL AND EXISTS(SELECT 1 FROM saved_schedules WHERE id=? AND revision=? AND enabled=1 AND deleted=0)`, origin.ID, origin.Due.UTC().Format(time.RFC3339Nano), origin.Revision, origin.ID, origin.Revision) if err != nil { return 0, false, err } diff --git a/internal/pipeline/saved_schedules.go b/internal/pipeline/saved_schedules.go index bc893740..eaf88f4d 100644 --- a/internal/pipeline/saved_schedules.go +++ b/internal/pipeline/saved_schedules.go @@ -409,6 +409,15 @@ func (s *Store) FinishSavedSchedule(ctx context.Context, id int64, due time.Time return err } +// SavedScheduleOccurrence reads one occurrence's history entry: its status +// (claimed, delayed, admitted, started, skipped, skipped_missed, skipped_day), +// diagnostic and admitted run (0 when none). +func (s *Store) SavedScheduleOccurrence(ctx context.Context, id int64, due time.Time) (status, diagnostic string, runID int64, err error) { + var run sql.NullInt64 + err = s.db.QueryRowContext(ctx, `SELECT status,diagnostic,run_id FROM saved_schedule_events WHERE schedule_id=? AND due=?`, id, due.UTC().Format(time.RFC3339Nano)).Scan(&status, &diagnostic, &run) + return status, diagnostic, run.Int64, err +} + // ScheduleAdmission is an internal capability, never decoded from public messages. type ScheduleAdmission struct { ID, Revision int64 diff --git a/internal/protocol/notifications.go b/internal/protocol/notifications.go index b6d86d75..1a595fe6 100644 --- a/internal/protocol/notifications.go +++ b/internal/protocol/notifications.go @@ -53,6 +53,9 @@ const ( // NotificationChatNotify is an agent's own notify tool call. Its priority // is the tool's: low 2, default 3, high 4. NotificationChatNotify = "chat_notify" + // NotificationSchedule says a scheduled run was delayed (its workspace was + // busy) or skipped. It is low priority (2). + NotificationSchedule = "schedule" ) // DefaultNotificationPriority is ntfy's default priority, which every ntfy diff --git a/internal/server/execution_safety_test.go b/internal/server/execution_safety_test.go index 95dc4f27..96d82041 100644 --- a/internal/server/execution_safety_test.go +++ b/internal/server/execution_safety_test.go @@ -122,10 +122,13 @@ func TestCleanupUnconfirmedReservesWorkspaceAcrossRecovery(t *testing.T) { func TestWorkspaceOverlapIncludesParentsDescendantsAndSymlinks(t *testing.T) { _, r, pipelineID := concurrentStore(t) + // One repository: its folder and a folder inside it are one shared tree. workspace := t.TempDir() child := filepath.Join(workspace, "child") - if err := os.Mkdir(child, 0700); err != nil { - t.Fatal(err) + for _, dir := range []string{filepath.Join(workspace, ".git"), child} { + if err := os.Mkdir(dir, 0700); err != nil { + t.Fatal(err) + } } alias := filepath.Join(t.TempDir(), "alias") if err := os.Symlink(child, alias); err != nil { @@ -176,3 +179,73 @@ func TestWorkspaceOverlapSeparatesNestedRepositories(t *testing.T) { } } } + +// Two folders outside any repository (the operator's ~/caplens and a sibling +// project folder under it) are not one tree merely because neither is in a +// repository: nested, they overlap only where the outer run's declared write +// paths reach the inner folder. The same folder always overlaps. +func TestWorkspaceOverlapNonRepositoryFolders(t *testing.T) { + hub := t.TempDir() + brief := filepath.Join(hub, "brief") + notes := filepath.Join(hub, "notes", "deep") + for _, dir := range []string{brief, notes} { + if err := os.MkdirAll(dir, 0700); err != nil { + t.Fatal(err) + } + } + paths := func(p ...string) func() []string { return func() []string { return p } } + for _, test := range []struct { + a, b string + aPaths, bPaths func() []string + want bool + }{ + {hub, hub, nil, nil, true}, + {brief, brief, nil, nil, true}, + {hub, brief, nil, nil, false}, + {brief, hub, nil, nil, false}, + {brief, notes, nil, nil, false}, + {hub, brief, paths("notes"), nil, false}, + {hub, brief, paths("brief"), nil, true}, + {hub, notes, paths("notes"), nil, true}, + {hub, notes, paths("notes/deep/file.md"), nil, true}, + {notes, hub, nil, paths("notes"), true}, + {notes, hub, paths("notes"), nil, false}, // The inner run's paths do not reach out. + {hub, brief, paths("."), nil, true}, + } { + if got := workspaceScopesOverlap(test.a, test.b, test.aPaths, test.bPaths); got != test.want { + t.Errorf("overlap(%s, %s) = %v, want %v", test.a, test.b, got, test.want) + } + } + // Nested repository rules stay: a repository inside a plain folder is its + // own tree whatever the folder's write paths. + repo := filepath.Join(hub, "repo") + if err := os.MkdirAll(filepath.Join(repo, ".git"), 0700); err != nil { + t.Fatal(err) + } + if workspaceScopesOverlap(hub, repo, paths("repo"), nil) { + t.Fatal("a repository inside a plain folder overlaps it") + } + + // End to end: a scheduled brief in the hub is admitted while a run works in + // a sibling folder below it, and refused only when it declares a write + // path reaching that folder. + _, r, pipelineID := concurrentStore(t) + release := make(chan struct{}) + defer close(release) + r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) { + select { + case <-release: + case <-ctx.Done(): + } + return stage.Result{Outcome: "success"}, nil + } + if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "notes", Workspace: notes, Input: map[string]any{"prompt": "task"}}); err != nil { + t.Fatal(err) + } + if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief-scoped", Workspace: hub, WritePaths: []string{"notes"}, Input: map[string]any{"prompt": "task"}}); err == nil || !strings.Contains(err.Error(), "already active") { + t.Fatal("a hub run writing into the active folder was admitted:", err) + } + if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief", Workspace: hub, Input: map[string]any{"prompt": "task"}}); err != nil { + t.Fatal("a hub run was refused for a sibling folder's run:", err) + } +} diff --git a/internal/server/run_reattach.go b/internal/server/run_reattach.go index 33781068..3c06b2ea 100644 --- a/internal/server/run_reattach.go +++ b/internal/server/run_reattach.go @@ -23,12 +23,19 @@ import ( // re-enters that visit, attaches to the session, waits for it to settle (or // reads the result it reached while the server was down) and continues the // graph as if it had watched it; +// - a running Claude Code visit is re-adopted the same way: its CLI runs in +// its own session writing stream-json to a file (see +// stage.ClaudeStageClient), so the next process keeps reading that file +// where the CLI is, waits for it to exit, or reads the result it left +// while the server was down (an interrupted outcome repair follow-up is +// asked again); // - a visit begun but never handed to a harness is marked interrupted and the // same stage starts again (nothing was admitted, so nothing replays); // - a run between visits continues with its next stage; -// - a session whose harness process is gone, or that belongs to a harness the -// server owned as a child (Pi, OpenCode V1), falls back to the previous -// behaviour: the run is interrupted, with the reason in its diagnostic. +// - a session whose harness process is gone (a Claude Code CLI that ended +// without a result), or that belongs to a harness the server owned as a +// child (Pi, OpenCode V1), falls back to the previous behaviour: the run +// is interrupted, with the reason in its diagnostic. // // Only an operator cancel (cancel_run) stops a stage session. @@ -61,6 +68,10 @@ var stageServiceAlive = func(ctx context.Context, owner pipeline.SessionOwner) e return opencode.ReferenceAlive(ctx, owner.Reference) } +// claudeStageReattachable reports why a retained Claude Code stage session +// cannot be re-adopted (nil when it can). It is a seam for tests. +var claudeStageReattachable = stage.ClaudeStageReattachable + // interruptRecoveredSession stops a previously active session that start-up // recovery does not re-adopt. It is a seam for tests. var interruptRecoveredSession = func(ctx context.Context, owner pipeline.SessionOwner) error { @@ -126,14 +137,22 @@ func planReattach(ctx context.Context, s *pipeline.Store) ([]reattachPlan, map[i return nil, nil, nil, err } owner.RunID = row.ID + if owner.Backend == stage.ClaudeBackend { + // Claude Code stage CLIs run detached from the server: re-adopt + // one still running, or one that left its result while the + // server was down. + if reason := claudeStageReattachable(owner.Reference, owner.ID); reason != nil { + reasons[row.ID] = fmt.Sprintf("the Claude Code session running stage %s could not be reattached: %v", last.Stage, reason) + continue + } + plans = append(plans, reattachPlan{runID: row.ID, kind: reattachAdopt, step: last, owner: owner}) + continue + } if owner.Backend != "v2" { name := "OpenCode V1" if owner.Backend == "pi" { name = "Pi" } - if owner.Backend == stage.ClaudeBackend { - name = "Claude Code" - } reasons[row.ID] = fmt.Sprintf("%s stage sessions belong to the stopped server process, so stage %s could not be reattached", name, last.Stage) continue } diff --git a/internal/server/run_reattach_test.go b/internal/server/run_reattach_test.go index 1f330347..bce67ecc 100644 --- a/internal/server/run_reattach_test.go +++ b/internal/server/run_reattach_test.go @@ -294,3 +294,94 @@ func TestOperatorCancelStillStopsDetachingRun(t *testing.T) { t.Fatalf("operator cancel did not stop the run: detached=%v %+v", detached.Load(), final) } } + +// ownedClaudeStage is a first-process stage one whose Claude Code CLI +// (session claude-live) is still running, detached, at shutdown. +func ownedClaudeStage(ctx context.Context, s *pipeline.Store, id int64) (stage.Result, error) { + if err := s.RunSession(context.Background(), id, 1, "claude-live", true, stage.ClaudeBackend, "ref-claude"); err != nil { + return stage.Result{}, err + } + <-ctx.Done() + if stage.Detached(ctx) { + return stage.Result{}, stage.ErrDetached + } + return stage.Result{}, ctx.Err() +} + +func seamClaudeReattachable(t *testing.T, reason error) *atomic.Value { + t.Helper() + asked := &atomic.Value{} + previous := claudeStageReattachable + claudeStageReattachable = func(reference, session string) error { + asked.Store(reference + " " + session) + return reason + } + t.Cleanup(func() { claudeStageReattachable = previous }) + return asked +} + +// TestClaudeStageRunContinuesAfterRestart: a Claude Code stage in flight at a +// restart is re-adopted from its retained session (never re-prompted, never +// interrupted) and the run continues to the next stage. +func TestClaudeStageRunContinuesAfterRestart(t *testing.T) { + interrupts := seamRestartRecovery(t, fmt.Errorf("the OpenCode probe must not be used for Claude")) + asked := seamClaudeReattachable(t, nil) + f := stopMidStage(t, ownedClaudeStage) + var resumed atomic.Value + r, s := f.restart(t, func(ctx context.Context, s *pipeline.Store, def stage.Definition) (stage.Result, error) { + if def.Key == "one" { + resumed.Store(stage.TakeResumeSession(ctx)) + if err := s.RunSession(context.Background(), f.runID, 1, "claude-live", false, stage.ClaudeBackend, "ref-claude"); err != nil { + return stage.Result{}, err + } + return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "Claude finished"}}, nil + } + return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "next"}}, nil + }) + if interrupts.Load() != 0 { + t.Fatal("start-up recovery interrupted a Claude Code stage that survived the restart") + } + if got, _ := asked.Load().(string); got != "ref-claude claude-live" { + t.Fatalf("reattachability asked about %q", got) + } + r.reattachRuns() + r.wg.Wait() + d, err := s.GetRun(context.Background(), f.runID) + if err != nil { + t.Fatal(err) + } + if got, _ := resumed.Load().(string); got != "claude-live" { + t.Fatalf("stage one was not re-adopted from its Claude session: %q", got) + } + if d.Status != "succeeded" || len(d.Steps) != 2 || d.Steps[0].Output["markdown"] != "Claude finished" { + t.Fatalf("run did not continue after the re-adopted Claude stage: %+v", d) + } +} + +// TestClaudeStageGoneWithoutResultIsInterruptedWithReason: a Claude Code CLI +// that ended without a result while the server was down is not replayed; the +// run is interrupted, saying why. +func TestClaudeStageGoneWithoutResultIsInterruptedWithReason(t *testing.T) { + interrupts := seamRestartRecovery(t, nil) + seamClaudeReattachable(t, fmt.Errorf("Claude Code stopped while the server was restarting, before it reported a final result")) + f := stopMidStage(t, ownedClaudeStage) + r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) { + t.Error("a Claude stage without a result executed again") + return stage.Result{}, nil + }) + r.reattachRuns() + r.wg.Wait() + d, err := s.GetRun(context.Background(), f.runID) + if err != nil { + t.Fatal(err) + } + if d.Status != "interrupted" || !strings.Contains(d.Diagnostic, "Claude Code session running stage one could not be reattached") || !strings.Contains(d.Diagnostic, "before it reported a final result") { + t.Fatalf("lost Claude stage lacks a clear reason: status=%s run=%q", d.Status, d.Diagnostic) + } + if interrupts.Load() != 1 { + t.Fatalf("the leftover Claude group was not confirmed stopped: %d", interrupts.Load()) + } + if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 { + t.Fatalf("the lost session still blocks recovery: %+v", owners) + } +} diff --git a/internal/server/runner.go b/internal/server/runner.go index c2b8330a..24734a1e 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -319,7 +319,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc return nil, err } if existing == 0 { - if err := r.checkWorkspaceFree(workspace); err != nil { + if err := r.checkWorkspaceFree(workspace, request.WritePaths...); err != nil { r.mu.Unlock() return nil, err } @@ -343,7 +343,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc // Another run may have reserved this workspace while the title was // generated, so re-check before reserving it; a race on the request key is // handled by the store's idempotent insert. - if err := r.checkAdmissionWorkspace(workspace, existing); err != nil { + if err := r.checkAdmissionWorkspace(workspace, existing, request.WritePaths...); err != nil { r.mu.Unlock() return nil, err } @@ -380,7 +380,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc request.Input["pwd"] = workspace recheck := r.ctx.Err() if recheck == nil { - recheck = r.checkAdmissionWorkspace(workspace, existing) + recheck = r.checkAdmissionWorkspace(workspace, existing, request.WritePaths...) } if recheck != nil { r.mu.Unlock() @@ -543,9 +543,9 @@ var runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.Ru // storage maintenance may have removed a clean inactive tree while an // admission was generating its title, so it is checked under the same lock // removal takes. Callers must hold r.mu. -func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error { +func (r *runner) checkAdmissionWorkspace(workspace string, existing int64, writePaths ...string) error { if existing == 0 { - if err := r.checkWorkspaceFree(workspace); err != nil { + if err := r.checkWorkspaceFree(workspace, writePaths...); err != nil { return err } } @@ -557,14 +557,30 @@ func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error // checkWorkspaceFree refuses a run when an active or cleanup-unconfirmed run // reserves an overlapping resolved workspace. Callers must hold r.mu. -func (r *runner) checkWorkspaceFree(workspace string) error { - return r.checkWorkspaceFreeExcept(workspace, 0) +// writePaths are the new run's declared write paths (they decide an overlap +// only between nested folders outside any repository). +func (r *runner) checkWorkspaceFree(workspace string, writePaths ...string) error { + return r.checkWorkspaceFreeExcept(workspace, 0, writePaths...) } -func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error { +func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64, writePaths ...string) error { + own := func() []string { return writePaths } + // pathsOf reads a reserving run's declared write paths only when needed. + pathsOf := func(id int64) func() []string { + return func() []string { + read, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second) + defer cancel() + paths, err := r.store.RunWritePaths(read, id) + if err != nil { + // Unknown scope: keep the whole folder reserved (fail closed). + return []string{"."} + } + return paths + } + } for id, entry := range r.active { - if workspacesOverlap(entry.workspace, workspace) { - return fmt.Errorf("run %d is already active in %s, which overlaps this run's workspace %s; wait for run %d to finish or use a different workspace (for example another checkout of the repository)", id, entry.workspace, workspace, id) + if workspaceScopesOverlap(entry.workspace, workspace, pathsOf(id), own) { + return &workspaceBusyError{runID: id, message: fmt.Sprintf("run %d is already active in %s, which overlaps this run's workspace %s; wait for run %d to finish or use a different workspace (for example another checkout of the repository)", id, entry.workspace, workspace, id)} } } check, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second) @@ -574,35 +590,76 @@ func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error return fmt.Errorf("read pending export workspace reservations: %w", err) } for id, reserved := range reservations { - if id != ownGate && workspacesOverlap(reserved, workspace) { - return fmt.Errorf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved) + if id != ownGate && workspaceScopesOverlap(reserved, workspace, pathsOf(id), own) { + return &workspaceBusyError{runID: id, message: fmt.Sprintf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved)} } } return nil } +// workspaceBusyError refuses an admission because another run (runID) +// reserves an overlapping workspace; waiting can clear it. +type workspaceBusyError struct { + runID int64 + message string +} + +func (e *workspaceBusyError) Error() string { return e.message } + // workspacesOverlap reports whether two resolved workspaces are the same // tree or nested in one another within the same repository. A folder that // merely holds separate repositories (a hub such as ~/project with clones // under repos/) does not overlap a run inside one of those repositories, and // neither do two different repositories nested in one another: each run -// works in its own repository. +// works in its own repository. Two folders outside any repository are not one +// shared tree either: nested, they overlap only where the outer run declared +// write paths reaching the inner folder (see workspaceScopesOverlap). func workspacesOverlap(a, b string) bool { - within := func(parent, child string) bool { - rel, err := filepath.Rel(parent, child) - return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) - } + return workspaceScopesOverlap(a, b, nil, nil) +} + +// workspaceScopesOverlap is workspacesOverlap with each workspace's declared +// write paths (relative to it). They matter only for two nested folders +// outside any repository; a nil lookup means "declared none". +func workspaceScopesOverlap(a, b string, aPaths, bPaths func() []string) bool { switch { case filepath.Clean(a) == filepath.Clean(b): return true - case within(a, b): - return repositoryRoot(b) == repositoryRoot(a) - case within(b, a): - return repositoryRoot(a) == repositoryRoot(b) + case pathAtOrBelow(a, b): + return nestedWorkspacesOverlap(a, b, aPaths) + case pathAtOrBelow(b, a): + return nestedWorkspacesOverlap(b, a, bPaths) } return false } +// nestedWorkspacesOverlap decides for an inner workspace below outer. +func nestedWorkspacesOverlap(outer, inner string, outerPaths func() []string) bool { + root := repositoryRoot(outer) + if repositoryRoot(inner) != root { + return false // Different repositories: each run works in its own. + } + if root != "" { + return true // The same repository is one shared tree. + } + if outerPaths == nil { + return false + } + for _, path := range outerPaths() { + target := filepath.Join(outer, path) + if pathAtOrBelow(target, inner) || pathAtOrBelow(inner, target) { + return true + } + } + return false +} + +// pathAtOrBelow reports whether child is parent or below it. +func pathAtOrBelow(parent, child string) bool { + rel, err := filepath.Rel(parent, child) + return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) +} + // repositoryRoot is the nearest directory at or above dir holding a .git // entry (a repository or a linked worktree), or "" outside any repository. func repositoryRoot(dir string) string { @@ -1055,7 +1112,7 @@ func (r *runner) decide(request protocol.Message) (*protocol.RunDetail, error) { return nil, fmt.Errorf("run %d is awaiting session export, not a human decision", detail.ID) } if detail.Status == protocol.RunStatusWaiting { - if err := r.checkWorkspaceFree(detail.Workspace); err != nil { + if err := r.checkWorkspaceFree(detail.Workspace, detail.WritePaths...); err != nil { r.mu.Unlock() return nil, err } @@ -2237,6 +2294,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na client.Transcript = piClient.Transcript } else if modelConfig.Harness == stage.ClaudeBackend { claudeClient := &stage.ClaudeStageClient{Directory: workspace, Tools: tools, WritePaths: request.WritePaths, ArtifactsDir: artifactsDir, Skills: def.Skills} + if adopted != nil { + // Follow the CLI the previous process left (see run_reattach.go). + claudeClient.Reference = adopted.owner.Reference + } claudeClient.OnOwnership = func(session, reference string, active bool) error { c, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() diff --git a/internal/server/scheduler.go b/internal/server/scheduler.go index d2165955..5d28e023 100644 --- a/internal/server/scheduler.go +++ b/internal/server/scheduler.go @@ -1,12 +1,16 @@ package server import ( + "context" + "errors" "fmt" "log" + "os" "time" "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" ) func (r *runner) scheduleLoop() { @@ -89,6 +93,10 @@ func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recov if err != nil { return err } + if claimed && status == "skipped_missed" { + name := scheduleLabel(item) + go r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, fmt.Sprintf("%s was due at %s while the server was not running, so that run was skipped.", name, due.Local().Format("15:04 on 2 Jan")), "") + } if !claimed || status != "claimed" { return nil } @@ -100,21 +108,114 @@ func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recov return nil } -// admitScheduled starts one claimed schedule's run and records the outcome. +// scheduleBusyRetry is how often, and for how long after its due time, a +// scheduled admission whose workspace another run holds is tried again +// (the limit counts from the first attempt). +// PIPELINES_SCHEDULE_BUSY_RETRY_EVERY and PIPELINES_SCHEDULE_BUSY_RETRY_FOR +// (Go durations; FOR=0 disables waiting) override the defaults. +var scheduleBusyRetry = func() (every, limit time.Duration) { + every, limit = 5*time.Minute, 2*time.Hour + if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_EVERY")); err == nil && value > 0 { + every = value + } + if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_FOR")); err == nil && value >= 0 { + limit = value + } + return every, limit +} + +// scheduleNoticePriority is ntfy's "low" priority. +const scheduleNoticePriority = 2 + +// admitScheduled starts one claimed schedule's run and records the outcome in +// the schedule's history. A workspace another run holds delays the admission +// instead of skipping it: it is tried again every few minutes for a bounded +// time, recorded as "delayed" meanwhile. The operator is told, at low +// priority, when a scheduled run is delayed and when one is skipped. func (r *runner) admitScheduled(item protocol.SavedSchedule, due time.Time) { request := protocol.Message{PipelineID: item.PipelineID, Version: item.Version, RequestKey: fmt.Sprintf("saved-schedule:%d:%d", item.ID, due.UnixNano()), Input: item.Input, Workspace: item.Workspace, WritePaths: item.WritePaths, AllowTools: item.AllowTools, Model: item.Model, StageModels: item.StageModels, NotifyMode: item.NotifyMode, Title: item.Title, OutputFormat: item.OutputFormat} - run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name}) + every, limit := scheduleBusyRetry() + started := time.Now() + deadline := started.Add(limit) + name := scheduleLabel(item) diagnostic := "" status := "started" var runID int64 - if err != nil { - status = "skipped" - diagnostic = err.Error() - } else if run != nil { - runID = run.ID + for attempt := 1; ; attempt++ { + run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name}) + if err == nil { + status, diagnostic = "started", "" + if run != nil { + runID = run.ID + } + if attempt > 1 { + diagnostic = fmt.Sprintf("started after waiting %s for a busy workspace", time.Since(started).Round(time.Second)) + } + break + } + status, diagnostic = "skipped", err.Error() + var busy *workspaceBusyError + if !errors.As(err, &busy) { + break + } + if time.Now().Add(every).After(deadline) { + if attempt > 1 { + diagnostic = fmt.Sprintf("gave up after waiting %s for a busy workspace: %s", time.Since(started).Round(time.Second), diagnostic) + } + break + } + if attempt == 1 { + r.scheduleNotice(item, due, "delayed", "Scheduled run delayed: "+name, + fmt.Sprintf("%s is waiting for run #%d to free its workspace; it is tried again every %s until %s.", name, busy.runID, every, deadline.Local().Format("15:04")), runAttentionClick(busy.runID)) + } + delayed := fmt.Sprintf("waiting for a busy workspace (attempt %d; retrying every %s until %s): %s", attempt, every, deadline.UTC().Format(time.RFC3339), err.Error()) + if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, "delayed", delayed); err != nil { + log.Printf("schedule id=%d record delay: %v", item.ID, err) + } + log.Printf("schedule id=%d pipeline=%d due=%s delayed: %s", item.ID, item.PipelineID, due.Format(time.RFC3339), delayed) + timer := time.NewTimer(every) + select { + case <-timer.C: + continue + case <-r.ctx.Done(): + timer.Stop() + diagnostic = "the server stopped while this run waited for a busy workspace: " + diagnostic + } + break } - if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, status, diagnostic); err != nil { + save, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 10*time.Second) + if err := r.store.FinishSavedSchedule(save, item.ID, due, status, diagnostic); err != nil { log.Printf("schedule id=%d record admission: %v", item.ID, err) } + cancel() + if status == "skipped" { + r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, name+" did not start: "+diagnostic, "") + } log.Printf("schedule id=%d pipeline=%d version=%d due=%s status=%s run=%d %s", item.ID, item.PipelineID, item.Version, due.Format(time.RFC3339), status, runID, diagnostic) } + +// scheduleLabel names a schedule in a notice. +func scheduleLabel(item protocol.SavedSchedule) string { + if name := singleLine(item.Name); name != "" { + return truncateUTF8(name, 120) + } + return fmt.Sprintf("Schedule %d", item.ID) +} + +// scheduleNotice tells the operator, at low priority, through the app +// notification stream and (when enabled) ntfy, that a scheduled run was +// delayed or skipped. +func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, event, title, message, click string) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 30*time.Second) + defer cancel() + title, message = truncateUTF8(singleLine(title), 256), truncateUTF8(singleLine(message), 2000) + r.notes.record(ctx, pipeline.AppNotificationRecord{AppNotification: protocol.AppNotification{ + ID: fmt.Sprintf("schedule:%d:%d:%s", item.ID, due.UnixNano(), event), Kind: protocol.NotificationSchedule, + Title: title, Message: message, Click: click, Priority: scheduleNoticePriority, Tags: []string{}, Group: fmt.Sprintf("schedule:%d", item.ID)}}) + if !chatAttentionConfigured() || !ntfyEnabled(ctx, r.settingsStore()) { + return + } + if _, err := ntfyPublish(stage.WithNtfyPriority(ctx, scheduleNoticePriority), "system", title, message, "", nil, click); err != nil { + log.Printf("schedule id=%d %s notice: %v", item.ID, event, err) + } +} diff --git a/internal/server/scheduler_busy_test.go b/internal/server/scheduler_busy_test.go new file mode 100644 index 00000000..8f7cb0ef --- /dev/null +++ b/internal/server/scheduler_busy_test.go @@ -0,0 +1,136 @@ +package server + +import ( + "context" + "strings" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" +) + +func scheduleNotices(t *testing.T, s *pipeline.Store) []protocol.AppNotification { + t.Helper() + active, _, err := s.ActiveAppNotifications(context.Background(), "", time.Now()) + if err != nil { + t.Fatal(err) + } + var notices []protocol.AppNotification + for _, n := range active { + if n.Kind == protocol.NotificationSchedule { + notices = append(notices, n) + } + } + return notices +} + +func waitOccurrence(t *testing.T, s *pipeline.Store, id int64, due time.Time, want string) (string, int64) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + status, diagnostic, run, err := s.SavedScheduleOccurrence(context.Background(), id, due) + if err == nil && status == want { + return diagnostic, run + } + if time.Now().After(deadline) { + t.Fatalf("occurrence status %q (%q, %v), want %q", status, diagnostic, err, want) + } + time.Sleep(5 * time.Millisecond) + } +} + +// A scheduled run whose workspace another run holds is delayed, not skipped: +// it is recorded as delayed, the operator is told at low priority, and it +// starts once the workspace is free. +func TestScheduledRunWaitsForABusyWorkspace(t *testing.T) { + seamScheduleBusyRetry(t, 20*time.Millisecond, time.Hour) + ctx, s, r, pid := scheduleFixture(t) + r.notes = newAppNotifier(s) + workspace := t.TempDir() + busy := saveTestSchedule(t, ctx, s, pid, "busy", workspace, "1h", time.Now()) + brief := saveTestSchedule(t, ctx, s, pid, "Daily brief", workspace, "1h", time.Now()) + release := make(chan struct{}) + entered := make(chan struct{}, 2) + r.execute = func(ctx context.Context, _ stage.Definition, input stage.Values) (stage.Result, error) { + entered <- struct{}{} + if prompt, _ := input["prompt"].(string); prompt == "busy" { + <-release + } + return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil + } + if err := r.scheduleTick(dueOf(t, busy), false); err != nil { + t.Fatal(err) + } + <-entered + due := dueOf(t, brief) + if err := r.scheduleTick(due, false); err != nil { + t.Fatal(err) + } + diagnostic, _ := waitOccurrence(t, s, brief.ID, due, "delayed") + if !strings.Contains(diagnostic, "busy workspace") || !strings.Contains(diagnostic, "already active") { + t.Fatalf("delay diagnostic %q", diagnostic) + } + notices := scheduleNotices(t, s) + if len(notices) != 1 || notices[0].Priority != 2 || !strings.Contains(notices[0].Title, "delayed") || !strings.Contains(notices[0].Title, "Daily brief") { + t.Fatalf("delay notices %+v", notices) + } + close(release) + diagnostic, run := waitOccurrence(t, s, brief.ID, due, "started") + r.scheduleAdmissions.Wait() + r.wg.Wait() + if run == 0 || !strings.Contains(diagnostic, "started after waiting") { + t.Fatalf("delayed run not admitted: run=%d %q", run, diagnostic) + } + runs, err := s.ListRuns(ctx) + if err != nil || len(runs) != 2 { + t.Fatalf("runs %+v %v", runs, err) + } +} + +// Waiting is bounded: past the limit the occurrence is skipped, saying why, +// and the operator is told. +func TestScheduledRunGivesUpOnABusyWorkspace(t *testing.T) { + seamScheduleBusyRetry(t, 20*time.Millisecond, 150*time.Millisecond) + ctx, s, r, pid := scheduleFixture(t) + r.notes = newAppNotifier(s) + workspace := t.TempDir() + busy := saveTestSchedule(t, ctx, s, pid, "busy", workspace, "1h", time.Now()) + brief := saveTestSchedule(t, ctx, s, pid, "Daily brief", workspace, "1h", time.Now()) + release := make(chan struct{}) + defer close(release) + entered := make(chan struct{}, 2) + r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) { + entered <- struct{}{} + select { + case <-release: + case <-ctx.Done(): + } + return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil + } + if err := r.scheduleTick(dueOf(t, busy), false); err != nil { + t.Fatal(err) + } + <-entered + due := dueOf(t, brief) + if claimed, err := s.ClaimSavedSchedule(ctx, *brief, due, due.Add(time.Hour), "claimed"); err != nil || !claimed { + t.Fatal(claimed, err) + } + r.admitScheduled(*brief, due) + diagnostic, run := waitOccurrence(t, s, brief.ID, due, "skipped") + if run != 0 || !strings.Contains(diagnostic, "gave up after waiting") { + t.Fatalf("skip diagnostic %q run=%d", diagnostic, run) + } + notices := scheduleNotices(t, s) + var titles []string + for _, n := range notices { + titles = append(titles, n.Title) + if n.Priority != 2 { + t.Fatalf("schedule notice is not low priority: %+v", n) + } + } + if len(notices) != 2 || !strings.Contains(strings.Join(titles, "|"), "skipped") { + t.Fatalf("notices %v", titles) + } +} diff --git a/internal/server/scheduler_test.go b/internal/server/scheduler_test.go index 9a7b5703..4fb38602 100644 --- a/internal/server/scheduler_test.go +++ b/internal/server/scheduler_test.go @@ -201,7 +201,17 @@ func TestScheduleDeletionDoesNotCancelAdmittedRun(t *testing.T) { } } +// seamScheduleBusyRetry sets how a scheduled admission waits for a busy +// workspace (limit 0: it is skipped at once, as before delays existed). +func seamScheduleBusyRetry(t *testing.T, every, limit time.Duration) { + t.Helper() + previous := scheduleBusyRetry + scheduleBusyRetry = func() (time.Duration, time.Duration) { return every, limit } + t.Cleanup(func() { scheduleBusyRetry = previous }) +} + func TestSavedScheduleRecoveryAndOverlap(t *testing.T) { + seamScheduleBusyRetry(t, time.Minute, 0) ctx, s, r, pid := scheduleFixture(t) item := saveTestSchedule(t, ctx, s, pid, "task", t.TempDir(), "1m", time.Now()) due := dueOf(t, item) diff --git a/internal/server/session_export_gate.go b/internal/server/session_export_gate.go index 6f09f238..2fc35395 100644 --- a/internal/server/session_export_gate.go +++ b/internal/server/session_export_gate.go @@ -35,7 +35,7 @@ func (r *runner) resumeExportGates(ctx context.Context) error { r.mu.Unlock() return err } - if err := r.checkWorkspaceFreeExcept(d.Workspace, id); err != nil { + if err := r.checkWorkspaceFreeExcept(d.Workspace, id, d.WritePaths...); err != nil { r.mu.Unlock() continue } diff --git a/internal/stage/claude_stage.go b/internal/stage/claude_stage.go index 6d659863..506ee787 100644 --- a/internal/stage/claude_stage.go +++ b/internal/stage/claude_stage.go @@ -8,6 +8,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "os" "os/exec" "path/filepath" @@ -36,6 +37,9 @@ var ( errClaudeMissing = errors.New("Claude Code is not installed on the execution server; run pipelines harness setup claude there") errClaudeSignedOut = errors.New("Claude Code is not signed in on the execution server; run pipelines harness setup claude there") errClaudeNoResult = errors.New("Claude Code ended without a final result") + // errClaudeStoppedUnwatched: the CLI ended while no server was watching + // it (the server was restarting) and left no final result. + errClaudeStoppedUnwatched = errors.New("Claude Code stopped while the server was restarting, before it reported a final result") ) // ClaudeStageClient runs one stage visit with the Claude Code CLI in print @@ -196,6 +200,10 @@ func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort stri } func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, prompt string) (text string, err error) { + // A re-adopted visit was admitted by a previous server process (see + // WithResumeSession): follow its CLI or read what it left, never prompt + // again. + resume := TakeResumeSession(ctx) c.WorkStarted = false c.usd, c.input, c.output, c.reasoning, c.cacheRead, c.cacheW = 0, 0, 0, 0, 0, 0 c.budget = config.Budget @@ -230,34 +238,54 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr if _, statErr := os.Stat(c.Executable); statErr != nil { return "", fmt.Errorf("%w: %w", ErrHarnessUnreachable, errClaudeMissing) } - cache, err := os.UserCacheDir() - if err != nil { - return "", err - } - root := filepath.Join(cache, "pipelines", claudeStageSessions) - if err = os.MkdirAll(root, 0700); err != nil { - return "", err - } - if c.Reference, err = os.MkdirTemp(root, "stage-*"); err != nil { - return "", err - } - if c.SessionID, err = newClaudeSessionID(); err != nil { - return "", err + var adopted *claudeStageOwner + if resume != "" { + owner, ownerErr := claudeStageOwnerAt(c.Reference) + if ownerErr != nil || owner.SessionID != resume || owner.Output == "" { + return "", fmt.Errorf("retained Claude Code stage session %.64s cannot be re-adopted: invalid retained evidence", RedactEvidence(resume)) + } + adopted = &owner + c.SessionID = resume + } else { + cache, cacheErr := os.UserCacheDir() + if cacheErr != nil { + return "", cacheErr + } + root := filepath.Join(cache, "pipelines", claudeStageSessions) + if err = os.MkdirAll(root, 0700); err != nil { + return "", err + } + if c.Reference, err = os.MkdirTemp(root, "stage-*"); err != nil { + return "", err + } + if c.SessionID, err = newClaudeSessionID(); err != nil { + return "", err + } } env := claudeStageEnvironment(c.environment(ctx), c.ArtifactsDir) // User settings are not loaded, so the operator's skills are offered as - // skills-only plugins generated for this visit, never their plugins. - if c.operatorPlugins, err = writeOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills"), OperatorSkills(claudeConfigDir(env))); err != nil { + // skills-only plugins generated for this visit, never their plugins. A + // re-adopted visit keeps the ones its first process generated. + if adopted != nil { + c.operatorPlugins = existingOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills")) + } else if c.operatorPlugins, err = writeOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills"), OperatorSkills(claudeConfigDir(env))); err != nil { return "", err } owned := false defer func() { - // Quiescence is proven per invocation (see run); only then is the + if errors.Is(err, ErrDetached) { + // The server is stopping: the CLI keeps running and its + // ownership stays recorded for the next process to re-adopt. + text = "" + return + } + // Quiescence is proven per invocation (see settle); only then is the // evidence marked settled and ownership released. if errors.Is(err, ErrStageCleanup) { text = "" return } + c.removeRawOutput() _ = os.WriteFile(filepath.Join(c.Reference, "quiescent"), []byte("quiescent"), 0600) if owned { if saveErr := c.OnOwnership(c.SessionID, c.Reference, false); saveErr != nil { @@ -272,13 +300,21 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr } owned = true } - if text, err = c.run(ctx, env, c.args(config, tools, effort, false), config.Model, prompt); err != nil { + if adopted != nil { + // The prompt was admitted by the previous process. The evidence stream + // is rebuilt from the CLI's own output, so nothing is listed twice. + c.WorkStarted = true + if err = os.WriteFile(filepath.Join(c.Reference, "stream.jsonl"), nil, 0600); err != nil { + return "", err + } + } + if text, err = c.invoke(ctx, env, c.args(config, tools, effort, false), 0, config.Model, prompt, adopted); err != nil { return "", err } // One outcome repair follow-up in the same session. repair := outputRepairFrom(ctx) if message, ok := repair.followUp(text); ok { - reply, err := c.run(ctx, env, c.args(config, tools, effort, true), config.Model, message) + reply, err := c.invoke(ctx, env, c.args(config, tools, effort, true), 1, config.Model, message, adopted) if err != nil { return "", err } @@ -384,145 +420,330 @@ type claudeStreamRecord struct { } `json:"message"` } -func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model, prompt string) (text string, err error) { +// claudeInvocation is what one CLI invocation's stream-json output reported. +type claudeInvocation struct { + final *claudeStreamRecord + refusal, limited bool + resetsAt int64 + authFailed, sessionMismatch, modelMismatch bool +} + +func (inv *claudeInvocation) observe(record claudeStreamRecord, session, model string) { + switch record.Type { + case "system": + if record.Subtype == "init" { + inv.sessionMismatch = record.SessionID != session + inv.modelMismatch = record.Model != model + } + case "rate_limit_event": + if record.RateLimit != nil && record.RateLimit.Status == "rejected" { + inv.limited = true + inv.resetsAt = record.RateLimit.ResetsAt + } + case "assistant": + if record.Message != nil { + switch record.Message.Error { + case "billing_error", "rate_limit": + inv.refusal = true + case "authentication_failed": + inv.authFailed = true + } + } + switch record.Error { + case "billing_error", "rate_limit": + inv.refusal = true + case "authentication_failed": + inv.authFailed = true + } + case "result": + copied := record + inv.final = &copied + } +} + +// claudeProcess is one invocation's CLI: a child this process started, or one +// a previous server process left (adopted: it cannot be waited on and its exit +// status is unknown). +type claudeProcess struct { + pid int + adopted bool + done chan struct{} // closed once the CLI has exited + waitErr error // the child's exit error, read after done + stop chan struct{} // ends an adopted process's liveness poll +} + +// exitedClaudeProcess is an invocation whose CLI already exited: its output +// is read to the end, nothing is waited for. +func exitedClaudeProcess(pid int) *claudeProcess { + p := &claudeProcess{pid: pid, adopted: true, done: make(chan struct{}), stop: make(chan struct{})} + close(p.done) + return p +} + +// adoptClaudeProcess follows a CLI left running by a previous server process. +func adoptClaudeProcess(pid int, session string) *claudeProcess { + p := &claudeProcess{pid: pid, adopted: true, done: make(chan struct{}), stop: make(chan struct{})} + go func() { + ticker := time.NewTicker(claudeAdoptPoll) + defer ticker.Stop() + for claudeProcessAlive(pid, session) { + select { + case <-p.stop: + return + case <-ticker.C: + } + } + close(p.done) + }() + return p +} + +func (p *claudeProcess) release() { + select { + case <-p.stop: + default: + close(p.stop) + } +} + +// claudeAdoptPoll is how often an adopted CLI's liveness is checked, and how +// often its output file is read again when no new line has arrived. +var claudeAdoptPoll = 100 * time.Millisecond + +// claudeOutputName is the raw stdout file of invocation n in the evidence +// directory. The CLI writes it directly, so it keeps writing whether or not a +// server is reading; it is removed once the visit settles. +func claudeOutputName(n int) string { return fmt.Sprintf("cli-%d.out", n) } + +func claudePromptName(n int) string { return fmt.Sprintf("cli-%d.prompt", n) } + +// removeRawOutput drops the unredacted CLI output and prompt files of a settled +// visit; the redacted stream.jsonl stays as its evidence. +func (c *ClaudeStageClient) removeRawOutput() { + for n := 0; n < 2; n++ { + _ = os.Remove(filepath.Join(c.Reference, claudeOutputName(n))) + _ = os.Remove(filepath.Join(c.Reference, claudePromptName(n))) + } +} + +// invoke runs invocation n (0 is the prompt, 1 the outcome repair follow-up). +// For a re-adopted visit (adopted != nil), an invocation the previous process +// already started is followed instead: its CLI if it still runs, else the +// output it left. A prompt that ended without a result while no server was +// watching is never sent again; a lost repair follow-up is. +func (c *ClaudeStageClient) invoke(ctx context.Context, env, args []string, n int, model, prompt string, adopted *claudeStageOwner) (string, error) { + if adopted != nil && n <= adopted.Invocation { + var proc *claudeProcess + switch { + case n < adopted.Invocation: + // An earlier invocation settled before the next one started; + // the owner record names only the latest process. + proc = exitedClaudeProcess(0) + case claudeProcessAlive(adopted.PID, c.SessionID): + proc = adoptClaudeProcess(adopted.PID, c.SessionID) + default: + proc = exitedClaudeProcess(adopted.PID) + } + inv, waitErr, err := c.follow(ctx, proc, n, model) + if err != nil { + return "", err + } + if inv.final != nil || n == 0 || n < adopted.Invocation { + return c.settle(ctx, proc, inv, waitErr) + } + // The repair follow-up's CLI ended without a reply while the server + // was down; the follow-up only asks for the outcome, so ask again. + } + proc, err := c.start(env, args, n, prompt) + if err != nil { + return "", err + } + inv, waitErr, err := c.follow(ctx, proc, n, model) + if err != nil { + return "", err + } + return c.settle(ctx, proc, inv, waitErr) +} + +// start launches one CLI invocation detached from the server process: in its +// own session, with the prompt read from a file and stdout written straight to +// a file, so a server restart neither signals it nor cuts its output. The owner +// record names the process and its output for a later server to re-adopt. +func (c *ClaudeStageClient) start(env, args []string, n int, prompt string) (*claudeProcess, error) { + promptPath := filepath.Join(c.Reference, claudePromptName(n)) + if err := os.WriteFile(promptPath, []byte(prompt), 0600); err != nil { + return nil, err + } + stdin, err := os.Open(promptPath) + if err != nil { + return nil, err + } + defer stdin.Close() + stdout, err := os.OpenFile(filepath.Join(c.Reference, claudeOutputName(n)), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600) + if err != nil { + return nil, err + } + defer stdout.Close() + stderr, err := os.OpenFile(filepath.Join(c.Reference, "stderr.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) + if err != nil { + return nil, err + } + defer stderr.Close() cmd := exec.Command(c.Executable, args...) cmd.Dir = c.Directory cmd.Env = env - cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} - cmd.Stdin = strings.NewReader(prompt) - stderr, err := os.OpenFile(filepath.Join(c.Reference, "stderr.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) - if err != nil { - return "", err - } - defer stderr.Close() - cmd.Stderr = stderr - out, err := cmd.StdoutPipe() - if err != nil { - return "", err - } - stream, err := os.OpenFile(filepath.Join(c.Reference, "stream.jsonl"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) - if err != nil { - return "", err - } - defer stream.Close() + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} + cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr if err = cmd.Start(); err != nil { - return "", fmt.Errorf("%w: %w", ErrHarnessUnreachable, errClaudeMissing) + return nil, fmt.Errorf("%w: %w", ErrHarnessUnreachable, errClaudeMissing) } - owner, _ := json.Marshal(map[string]any{"pid": cmd.Process.Pid, "session_id": c.SessionID}) - if err = os.WriteFile(filepath.Join(c.Reference, "owner.json"), owner, 0600); err != nil { - _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) - _ = cmd.Wait() - return "", err + proc := &claudeProcess{pid: cmd.Process.Pid, done: make(chan struct{}), stop: make(chan struct{})} + go func() { + // Reaps the child, also after this server detached from it. + proc.waitErr = cmd.Wait() + close(proc.done) + }() + owner := claudeStageOwner{PID: proc.pid, PGID: proc.pid, SessionID: c.SessionID, Invocation: n, Output: claudeOutputName(n)} + if err = writeClaudeStageOwner(c.Reference, owner); err != nil { + _ = syscall.Kill(-proc.pid, syscall.SIGKILL) + <-proc.done + return nil, err } // The prompt is admitted once the process has it: tool work may follow. c.WorkStarted = true - var final *claudeStreamRecord - var refusal, limited bool - var resetsAt int64 - var authFailed, sessionMismatch, modelMismatch bool - scanned := make(chan error, 1) - go func() { - scanner := bufio.NewScanner(out) - scanner.Buffer(make([]byte, 64<<10), 16<<20) - for scanner.Scan() { - line := scanner.Bytes() - var record claudeStreamRecord - if json.Unmarshal(line, &record) != nil { - continue - } - // One valid JSON record per line: the export parses this stream. - redacted := RedactEvidenceJSON(line) - _, _ = stream.WriteString(redacted + "\n") - if len(c.Transcript) < 32<<10 { - c.Transcript += redacted + "\n" - } - switch record.Type { - case "system": - if record.Subtype == "init" { - sessionMismatch = record.SessionID != c.SessionID - modelMismatch = record.Model != model - } - case "rate_limit_event": - if record.RateLimit != nil && record.RateLimit.Status == "rejected" { - limited = true - resetsAt = record.RateLimit.ResetsAt - } - case "assistant": - if record.Message != nil { - switch record.Message.Error { - case "billing_error", "rate_limit": - refusal = true - case "authentication_failed": - authFailed = true - } - } - switch record.Error { - case "billing_error", "rate_limit": - refusal = true - case "authentication_failed": - authFailed = true - } - case "result": - copied := record - final = &copied - } - } - scanned <- scanner.Err() - }() - waited := make(chan error, 1) - go func() { - scanErr := <-scanned - waitErr := cmd.Wait() - if scanErr != nil && waitErr == nil { - waitErr = scanErr - } - waited <- waitErr - }() - var waitErr error - select { - case waitErr = <-waited: - case <-ctx.Done(): - // Timeout or cancellation: stop the whole process group, then prove it. - _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM) - select { - case <-waited: - case <-time.After(5 * time.Second): - _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) - <-waited - } - waitErr = ctx.Err() + return proc, nil +} + +// follow reads invocation n's output file from its start until the CLI has +// exited and every line it wrote is read, keeping the redacted evidence +// stream. A server shutdown leaves the CLI running (ErrDetached); any other +// cancellation stops its process group first. +func (c *ClaudeStageClient) follow(ctx context.Context, proc *claudeProcess, n int, model string) (inv claudeInvocation, waitErr error, err error) { + defer proc.release() + out, err := os.Open(filepath.Join(c.Reference, claudeOutputName(n))) + if err != nil { + return inv, nil, err } + defer out.Close() + stream, err := os.OpenFile(filepath.Join(c.Reference, "stream.jsonl"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) + if err != nil { + return inv, nil, err + } + defer stream.Close() + consume := func(line []byte) { + var record claudeStreamRecord + if json.Unmarshal(line, &record) != nil { + return + } + // One valid JSON record per line: the export parses this stream. + redacted := RedactEvidenceJSON(line) + _, _ = stream.WriteString(redacted + "\n") + if len(c.Transcript) < 32<<10 { + c.Transcript += redacted + "\n" + } + inv.observe(record, c.SessionID, model) + } + reader := bufio.NewReaderSize(out, 64<<10) + var partial []byte + exited := false + ticker := time.NewTicker(claudeAdoptPoll) + defer ticker.Stop() + for { + chunk, readErr := reader.ReadBytes('\n') + partial = append(partial, chunk...) + if readErr == nil { + consume(partial) + partial = partial[:0] + continue + } + if readErr != io.EOF { + return inv, nil, readErr + } + if exited { + if len(bytes.TrimSpace(partial)) > 0 { + consume(partial) + } + if !proc.adopted { + waitErr = proc.waitErr + } + return inv, waitErr, nil + } + select { + case <-proc.done: + exited = true // Read what it wrote before exiting. + case <-ticker.C: + case <-ctx.Done(): + if Detached(ctx) { + return inv, nil, fmt.Errorf("%w: Claude Code stage session %s left running", ErrDetached, c.SessionID) + } + // Timeout or cancellation: stop the whole process group, then prove it. + if proc.pid > 1 { + _ = syscall.Kill(-proc.pid, syscall.SIGTERM) + } + select { + case <-proc.done: + case <-time.After(5 * time.Second): + _ = syscall.Kill(-proc.pid, syscall.SIGKILL) // done never stays open for pid 0. + select { + case <-proc.done: + case <-time.After(5 * time.Second): + } + } + if !claudeGroupStopped(proc.pid) { + return inv, nil, errors.Join(ctx.Err(), ErrStageCleanup) + } + return inv, nil, ctx.Err() + } + } +} + +// claudeGroupStopped kills what is left of an exited CLI's process group and +// reports whether the group is proven gone. +func claudeGroupStopped(pid int) bool { + if pid <= 1 { + return true // No process of this server's to prove (see exitedClaudeProcess). + } + if claudeGroupGone(pid) { + return true + } + _ = syscall.Kill(-pid, syscall.SIGKILL) + deadline := time.Now().Add(5 * time.Second) + for !claudeGroupGone(pid) && time.Now().Before(deadline) { + time.Sleep(50 * time.Millisecond) + } + return claudeGroupGone(pid) +} + +// settle proves the invocation's process group is gone and turns what its +// output reported into the invocation's result. +func (c *ClaudeStageClient) settle(ctx context.Context, proc *claudeProcess, inv claudeInvocation, waitErr error) (string, error) { // The CLI's exit alone does not prove its shell descendants exited. - if !claudeGroupGone(cmd.Process.Pid) { - _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) - deadline := time.Now().Add(5 * time.Second) - for !claudeGroupGone(cmd.Process.Pid) && time.Now().Before(deadline) { - time.Sleep(50 * time.Millisecond) - } - if !claudeGroupGone(cmd.Process.Pid) { - return "", errors.Join(waitErr, ErrStageCleanup) - } + if !claudeGroupStopped(proc.pid) { + return "", errors.Join(waitErr, ErrStageCleanup) } if ctx.Err() != nil { return "", ctx.Err() } + final := inv.final if final != nil { if usageErr := c.observe(final); usageErr != nil { return "", usageErr } } switch { - case authFailed: + case inv.authFailed: return "", fmt.Errorf("%w: %w", ErrHarnessTransport, errClaudeSignedOut) - case refusal || (limited && (final == nil || final.IsError)): - if resetsAt > 0 { + case inv.refusal || (inv.limited && (final == nil || final.IsError)): + if inv.resetsAt > 0 { // A usage window, not an empty account: say when it reopens (a // time only; no provider text is copied). - return "", fmt.Errorf("%w: %w; the Claude usage limit resets at %s", ErrHarnessTransport, opencode.ErrProviderQuota, time.Unix(resetsAt, 0).Format("15:04 on 2 Jan")) + return "", fmt.Errorf("%w: %w; the Claude usage limit resets at %s", ErrHarnessTransport, opencode.ErrProviderQuota, time.Unix(inv.resetsAt, 0).Format("15:04 on 2 Jan")) } return "", fmt.Errorf("%w: %w", ErrHarnessTransport, opencode.ErrProviderQuota) - case sessionMismatch || modelMismatch: + case inv.sessionMismatch || inv.modelMismatch: return "", fmt.Errorf("%w: Claude Code did not start the requested session and model", ErrHarnessTransport) + case final == nil && proc.adopted: + return "", fmt.Errorf("%w: %w", ErrHarnessTransport, errClaudeStoppedUnwatched) case final == nil: if waitErr != nil { return "", fmt.Errorf("%w: Claude Code exited with an error before a result (see the retained stderr log)", ErrHarnessTransport) @@ -536,6 +757,68 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model, return final.Result, nil } +// claudeProcessAlive reports whether pid is a live (not zombie) process whose +// command line names the session, so a recorded pid the system reused is never +// mistaken for the stage's CLI. +func claudeProcessAlive(pid int, session string) bool { + if pid <= 1 || session == "" { + return false + } + if _, err := os.Stat("/proc/self/stat"); err != nil { + return syscall.Kill(pid, 0) == nil // No procfs: liveness only. + } + stat, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) + if err != nil { + return false + } + if i := bytes.LastIndexByte(stat, ')'); i < 0 || i+2 >= len(stat) || stat[i+2] == 'Z' || stat[i+2] == 'X' { + return false + } + cmdline, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)) + return err == nil && bytes.Contains(cmdline, []byte(session)) +} + +// ClaudeStageReattachable reports whether a Claude Code stage session a +// stopped server left owned can be re-adopted: its CLI still runs, or it ended +// with a final result while no server was watching (or it was in the outcome +// repair follow-up, which follows a complete result). Otherwise the error says +// why. +func ClaudeStageReattachable(reference, sessionID string) error { + owner, err := claudeStageOwnerAt(reference) + if err != nil || owner.SessionID != sessionID { + return errors.New("its retained evidence is missing or invalid") + } + if owner.Output == "" { + return errors.New("it was started by a server version that ran Claude Code as its own child") + } + if claudeProcessAlive(owner.PID, sessionID) || owner.Invocation > 0 { + return nil + } + root, err := claudeStageRoot(reference) + if err != nil { + return errors.New("its retained evidence is missing or invalid") + } + defer root.Close() + f, err := piOpenEvidence(root, owner.Output) + if err != nil { + return errors.New("its Claude Code output is missing") + } + defer f.Close() + reader := bufio.NewReaderSize(f, 64<<10) + for { + line, readErr := reader.ReadBytes('\n') + var record struct { + Type string `json:"type"` + } + if json.Unmarshal(line, &record) == nil && record.Type == "result" { + return nil + } + if readErr != nil { + return errClaudeStoppedUnwatched + } + } +} + func claudeGroupGone(pid int) bool { return errors.Is(syscall.Kill(-pid, 0), syscall.ESRCH) } diff --git a/internal/stage/claude_stage_export.go b/internal/stage/claude_stage_export.go index 530f1409..d0f1155f 100644 --- a/internal/stage/claude_stage_export.go +++ b/internal/stage/claude_stage_export.go @@ -76,9 +76,47 @@ func claudeStageRead(root *os.Root, name string, limit int64) ([]byte, bool, err return data, false, err } +// claudeStageOwner is the retained owner record of a Claude stage visit's +// current CLI invocation. Output names the file the detached CLI writes its +// stream-json to; it is empty for a visit an older server ran as its own child +// (with piped output), which a restart cannot re-adopt. type claudeStageOwner struct { - PID int `json:"pid"` - SessionID string `json:"session_id"` + PID int `json:"pid"` + PGID int `json:"pgid,omitempty"` + SessionID string `json:"session_id"` + Invocation int `json:"invocation,omitempty"` + Output string `json:"output,omitempty"` +} + +// writeClaudeStageOwner replaces the owner record atomically, so a server +// stopped mid-write never leaves a torn record behind. +func writeClaudeStageOwner(reference string, owner claudeStageOwner) error { + data, err := json.Marshal(owner) + if err != nil { + return err + } + temp := filepath.Join(reference, "owner.json.tmp") + if err := os.WriteFile(temp, data, 0600); err != nil { + return err + } + return os.Rename(temp, filepath.Join(reference, "owner.json")) +} + +// claudeStageOwnerAt reads the owner record of a validated evidence directory. +func claudeStageOwnerAt(reference string) (claudeStageOwner, error) { + root, err := claudeStageRoot(reference) + if err != nil { + return claudeStageOwner{}, err + } + defer root.Close() + owner, err := claudeStageOwnerOf(root) + if err != nil { + return owner, err + } + if owner.Output != "" && owner.Output != claudeOutputName(owner.Invocation) { + return owner, fmt.Errorf("invalid retained Claude stage owner") + } + return owner, nil } func claudeStageOwnerOf(root *os.Root) (claudeStageOwner, error) { diff --git a/internal/stage/claude_stage_restart_test.go b/internal/stage/claude_stage_restart_test.go new file mode 100644 index 00000000..e3959325 --- /dev/null +++ b/internal/stage/claude_stage_restart_test.go @@ -0,0 +1,268 @@ +package stage + +import ( + "context" + "errors" + "os" + "path/filepath" + "slices" + "strings" + "syscall" + "testing" + "time" +) + +// detachClaudeMidInvocation runs Generate until invocation n's CLI has started +// working, then stops the "server" (a shutdown-caused cancel). The CLI must be +// left running and owned. +func detachClaudeMidInvocation(t *testing.T, client *ClaudeStageClient, ctx context.Context, config ModelConfig, n int) claudeStageOwner { + t.Helper() + run, stop := context.WithCancelCause(ctx) + defer stop(nil) + done := make(chan error, 1) + go func() { + _, err := client.Generate(run, config, "the task") + done <- err + }() + waitForClaudeOutput(t, n, `"init"`) + stop(ErrServerShutdown) + if err := <-done; !errors.Is(err, ErrDetached) { + t.Fatalf("a server shutdown did not detach the stage: %v", err) + } + if _, err := os.Stat(filepath.Join(client.Reference, "quiescent")); err == nil { + t.Fatal("a detached stage was marked quiescent") + } + owner, err := claudeStageOwnerAt(client.Reference) + if err != nil || owner.Invocation != n || owner.SessionID != client.SessionID { + t.Fatalf("owner %+v %v", owner, err) + } + if !claudeProcessAlive(owner.PID, client.SessionID) { + t.Fatal("the server shutdown stopped the Claude Code CLI") + } + if err := ClaudeStageReattachable(client.Reference, client.SessionID); err != nil { + t.Fatalf("a running stage is not reattachable: %v", err) + } + return owner +} + +// waitForClaudeOutput waits until the (only) stage evidence directory's +// invocation n output contains needle and returns that directory. It reads the +// file system, never the client a running Generate is writing. +func waitForClaudeOutput(t *testing.T, n int, needle string) string { + t.Helper() + cache, err := os.UserCacheDir() + if err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(10 * time.Second) + for { + dirs, _ := filepath.Glob(filepath.Join(cache, "pipelines", claudeStageSessions, "stage-*")) + for _, dir := range dirs { + if data, err := os.ReadFile(filepath.Join(dir, claudeOutputName(n))); err == nil && strings.Contains(string(data), needle) { + return dir + } + } + if time.Now().After(deadline) { + t.Fatalf("invocation %d never started", n) + } + time.Sleep(10 * time.Millisecond) + } +} + +// restartedClaudeClient is the next server process's client for the same visit. +func restartedClaudeClient(first *ClaudeStageClient) (*ClaudeStageClient, *[]bool) { + active := &[]bool{} + return &ClaudeStageClient{Executable: first.Executable, Directory: first.Directory, Tools: first.Tools, Reference: first.Reference, OnOwnership: func(_, _ string, value bool) error { + *active = append(*active, value) + return nil + }}, active +} + +func release(t *testing.T, root string) { + t.Helper() + if err := os.WriteFile(filepath.Join(root, "release"), nil, 0600); err != nil { + t.Fatal(err) + } +} + +func waitGone(t *testing.T, pid int) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !claudeGroupGone(pid) { + if time.Now().After(deadline) { + t.Fatal("the CLI did not exit") + } + time.Sleep(10 * time.Millisecond) + } +} + +// TestClaudeStageSurvivesServerRestart: a server restart mid-stage leaves the +// CLI running; the next process re-adopts it, keeps reading its output, waits +// for its result and settles the visit, without prompting again. +func TestClaudeStageSurvivesServerRestart(t *testing.T) { + first, root, firstActive := fakeClaudeClient(t, "slow") + owner := detachClaudeMidInvocation(t, first, context.Background(), claudeConfig(nil), 0) + if !slices.Equal(*firstActive, []bool{true}) { + t.Fatal("the detaching process released ownership", *firstActive) + } + second, active := restartedClaudeClient(first) + budget := NewBudget(10, 1000) + ctx, cancel := context.WithTimeout(WithResumeSession(context.Background(), first.SessionID), 10*time.Second) + defer cancel() + go func() { time.Sleep(200 * time.Millisecond); release(t, root) }() + text, err := second.Generate(ctx, claudeConfig(budget), "never sent") + if err != nil || text != "done" { + t.Fatal(text, err) + } + if calls := fakeClaudeArgs(t, root); len(calls) != 1 { + t.Fatalf("the restarted server prompted again: %v", calls) + } + if prompt, _ := os.ReadFile(filepath.Join(root, "prompt")); string(prompt) != "the task" { + t.Fatalf("prompt %q", prompt) + } + if !slices.Equal(*active, []bool{true, false}) || !second.WorkStarted || second.SessionID != first.SessionID { + t.Fatal("ownership", *active, second.WorkStarted) + } + if used := budget.Snapshot(); used.UsedUSD != 0.25 || used.UsedTokens != 17 { + t.Fatalf("usage %+v", used) + } + if !claudeGroupGone(owner.PID) { + t.Fatal("the adopted CLI's group is still running") + } + // The evidence lists each record once and the export reads it. + data, err := ClaudeStageEvidence(first.Reference) + if err != nil || strings.Count(data, `"working"`) != 1 || strings.Count(data, `"type":"result"`) != 1 { + t.Fatalf("evidence %q %v", data, err) + } + if _, err := os.Stat(filepath.Join(first.Reference, claudeOutputName(0))); !os.IsNotExist(err) { + t.Fatal("the raw CLI output outlived the settled visit") + } + session, err := exportClaudeStageSession(ctx, SessionExportRequest{Backend: ClaudeBackend, SessionID: first.SessionID, Reference: first.Reference}) + if err != nil || len(session.Messages) == 0 { + t.Fatalf("export %+v %v", session, err) + } +} + +// TestClaudeStageFinishedWhileServerWasDown: the CLI completed while no server +// ran; the next process reads the result it left. +func TestClaudeStageFinishedWhileServerWasDown(t *testing.T) { + first, root, _ := fakeClaudeClient(t, "slow") + owner := detachClaudeMidInvocation(t, first, context.Background(), claudeConfig(nil), 0) + release(t, root) + waitGone(t, owner.PID) + if err := ClaudeStageReattachable(first.Reference, first.SessionID); err != nil { + t.Fatalf("a completed stage is not reattachable: %v", err) + } + second, active := restartedClaudeClient(first) + text, err := second.Generate(WithResumeSession(context.Background(), first.SessionID), claudeConfig(nil), "never sent") + if err != nil || text != "done" || !slices.Equal(*active, []bool{true, false}) { + t.Fatal(text, err, *active) + } + if calls := fakeClaudeArgs(t, root); len(calls) != 1 { + t.Fatalf("the restarted server prompted again: %v", calls) + } +} + +// TestClaudeStageDiedWithoutResultWhileServerWasDown: a CLI that ended +// without a result while no server watched is never prompted again; recovery +// says why. +func TestClaudeStageDiedWithoutResultWhileServerWasDown(t *testing.T) { + first, root, _ := fakeClaudeClient(t, "slow") + owner := detachClaudeMidInvocation(t, first, context.Background(), claudeConfig(nil), 0) + _ = syscall.Kill(-owner.PID, syscall.SIGKILL) + waitGone(t, owner.PID) + err := ClaudeStageReattachable(first.Reference, first.SessionID) + if !errors.Is(err, errClaudeStoppedUnwatched) { + t.Fatalf("a dead stage without a result was reattachable: %v", err) + } + // Adopting anyway (a death between the plan and the adoption) fails + // closed with the same diagnostic and settles ownership. + second, active := restartedClaudeClient(first) + _, err = second.Generate(WithResumeSession(context.Background(), first.SessionID), claudeConfig(nil), "never sent") + if !errors.Is(err, ErrHarnessTransport) || !errors.Is(err, errClaudeStoppedUnwatched) || !slices.Equal(*active, []bool{true, false}) { + t.Fatal(err, *active) + } + if calls := fakeClaudeArgs(t, root); len(calls) != 1 { + t.Fatalf("a lost prompt was sent again: %v", calls) + } +} + +// TestClaudeStageRestartDuringOutcomeRepair: a restart during the outcome +// repair follow-up re-adopts that follow-up; the prompt's report is read back +// from its retained output and merged with the reply, and both invocations' +// usage counts. +func TestClaudeStageRestartDuringOutcomeRepair(t *testing.T) { + first, root, _ := fakeClaudeClient(t, "slowrepair") + repair := withOutputRepair(context.Background(), []string{"error", "success"}) + detachClaudeMidInvocation(t, first, repair, claudeConfig(nil), 1) + second, active := restartedClaudeClient(first) + budget := NewBudget(0, 1000) + go func() { time.Sleep(200 * time.Millisecond); release(t, root) }() + text, err := second.Generate(WithResumeSession(repair, first.SessionID), claudeConfig(budget), "never sent") + if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") || !strings.Contains(text, "Report kept.") { + t.Fatalf("%q %v", text, err) + } + if calls := fakeClaudeArgs(t, root); len(calls) != 2 { + t.Fatalf("invocations %v", calls) + } + if budget.Snapshot().UsedTokens != 34 || !slices.Equal(*active, []bool{true, false}) { + t.Fatalf("usage %+v ownership %v", budget.Snapshot(), *active) + } +} + +// TestClaudeStageLostRepairFollowUpIsSentAgain: the follow-up's CLI died +// without a reply while the server was down; it only asks for the outcome, +// so the next process asks again instead of failing the visit. +func TestClaudeStageLostRepairFollowUpIsSentAgain(t *testing.T) { + first, root, _ := fakeClaudeClient(t, "slowrepair") + repair := withOutputRepair(context.Background(), []string{"error", "success"}) + owner := detachClaudeMidInvocation(t, first, repair, claudeConfig(nil), 1) + _ = syscall.Kill(-owner.PID, syscall.SIGKILL) + waitGone(t, owner.PID) + if err := ClaudeStageReattachable(first.Reference, first.SessionID); err != nil { + t.Fatalf("a visit with a complete prompt result is not reattachable: %v", err) + } + release(t, root) + second, _ := restartedClaudeClient(first) + text, err := second.Generate(WithResumeSession(repair, first.SessionID), claudeConfig(nil), "never sent") + if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") { + t.Fatalf("%q %v", text, err) + } + calls := fakeClaudeArgs(t, root) + if len(calls) != 3 || !slices.Contains(calls[2], "--resume") { + t.Fatalf("invocations %v", calls) + } +} + +// TestClaudeStageOperatorCancelStillStopsTheCLI: only a server shutdown +// detaches; an ordinary cancel stops the detached process group. +func TestClaudeStageOperatorCancelStillStopsTheCLI(t *testing.T) { + client, _, active := fakeClaudeClient(t, "slow") + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + _, err := client.Generate(ctx, claudeConfig(nil), "task") + done <- err + }() + owner, _ := claudeStageOwnerAt(waitForClaudeOutput(t, 0, "working")) + cancel() + if err := <-done; !errors.Is(err, context.Canceled) || errors.Is(err, ErrDetached) { + t.Fatal(err) + } + if !claudeGroupGone(owner.PID) || !slices.Equal(*active, []bool{true, false}) { + t.Fatal("cancel left the CLI running", *active) + } +} + +func TestClaudeStageLegacyOwnerIsNotReattachable(t *testing.T) { + client, _, _ := fakeClaudeClient(t, "success") + if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(client.Reference, "owner.json"), []byte(`{"pid":99999999,"session_id":"`+client.SessionID+`"}`), 0600); err != nil { + t.Fatal(err) + } + if err := ClaudeStageReattachable(client.Reference, client.SessionID); err == nil || !strings.Contains(err.Error(), "server version") { + t.Fatal(err) + } +} diff --git a/internal/stage/claude_stage_test.go b/internal/stage/claude_stage_test.go index c7f247bf..01c779b7 100644 --- a/internal/stage/claude_stage_test.go +++ b/internal/stage/claude_stage_test.go @@ -48,6 +48,24 @@ case "$FAKE_CLAUDE_CASE" in if [ "$resumed" = 1 ]; then text='# outcome\nsuccess\n'; else text='Report kept.'; fi printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"'"$text"'","session_id":"'"$session"'",'"$usage"'}' ;; + slow) + # Works until the test releases it (a server restart happens meanwhile). + init "$session" "$model" + echo '{"type":"assistant","session_id":"'"$session"'","message":{"role":"assistant","content":[{"type":"text","text":"working"}]}}' + while [ ! -e "$FAKE_CLAUDE_OUT/release" ]; do sleep 0.02; done + echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'",'"$usage"'}' + ;; + slowrepair) + # The prompt's report lacks an outcome; the follow-up waits for release. + init "$session" "$model" + if [ "$resumed" = 1 ]; then + while [ ! -e "$FAKE_CLAUDE_OUT/release" ]; do sleep 0.02; done + text='# outcome\nsuccess\n' + else + text='Report kept.' + fi + printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"'"$text"'","session_id":"'"$session"'",'"$usage"'}' + ;; nousage) init "$session" "$model" echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'"}' diff --git a/internal/stage/operator_skills.go b/internal/stage/operator_skills.go index bfd79ce3..bb8687c5 100644 --- a/internal/stage/operator_skills.go +++ b/internal/stage/operator_skills.go @@ -249,3 +249,20 @@ func writeOperatorSkillPlugins(dir string, groups []OperatorSkillGroup) ([]strin } return roots, nil } + +// existingOperatorSkillPlugins lists the skills-only plugin roots an earlier +// process generated in dir (see writeOperatorSkillPlugins), for a re-adopted +// visit whose follow-up must offer the same skills. +func existingOperatorSkillPlugins(dir string) []string { + entries, err := os.ReadDir(dir) + if err != nil { + return nil + } + var roots []string + for _, entry := range entries { + if entry.IsDir() { + roots = append(roots, filepath.Join(dir, entry.Name())) + } + } + return roots +}