Claude stages survive server restarts; non-repo folders don't falsely overlap; busy scheduled runs wait

- Claude stage CLIs now run in their own session (setsid) with the prompt from
  a file and stream-json written straight to cli-<n>.out in the evidence
  directory; owner.json records pid/pgid, session, invocation and output. A
  server shutdown leaves the CLI running and owned (ErrDetached). Start-up
  recovery re-adopts it (stage.ClaudeStageReattachable): the next process
  re-reads the output, follows the live CLI until it exits, or reads the
  result it left while the server was down; one that ended without a result
  marks the run interrupted with a clear reason. The outcome repair follow-up
  is re-adopted too (or asked again if its CLI died without a reply).
- Workspace overlap: two folders outside any repository overlap only when
  they are the same folder or the inner one lies within the outer run's
  declared write paths; nested-repository rules are unchanged.
- Scheduled admissions refused for a busy workspace are recorded as
  "delayed" and retried every 5 min for up to 2 h (env-configurable), then
  started or skipped with the reason; the operator gets a low-priority app
  notice (and ntfy when enabled) when a scheduled run is delayed or skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 12:55:12 +00:00
parent c4de1de27b
commit f061675fc1
20 changed files with 1344 additions and 180 deletions
+414 -131
View File
@@ -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)
}
+40 -2
View File
@@ -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) {
+268
View File
@@ -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)
}
}
+18
View File
@@ -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"'"}'
+17
View File
@@ -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
}