Merge main into the engine loop improvements
Keep both intents: check stages, allow_workspace_changes, outcome repair counts and Claude stage re-adoption from main beside the findings gate, resume_session, applyLimitOn and exhaustion decisions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+115
-27
@@ -320,7 +320,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
|
||||
}
|
||||
@@ -344,7 +344,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
|
||||
}
|
||||
@@ -381,7 +381,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()
|
||||
@@ -544,9 +544,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
|
||||
}
|
||||
}
|
||||
@@ -558,14 +558,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)
|
||||
@@ -575,35 +591,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 {
|
||||
@@ -1080,7 +1137,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
|
||||
}
|
||||
@@ -2308,6 +2365,8 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
budgetBefore = budgets[key].Snapshot()
|
||||
stageCtx = stage.WithBudget(stageCtx, budgets[key])
|
||||
}
|
||||
repairs := &stage.RepairCounter{}
|
||||
stageCtx = stage.WithRepairCounter(stageCtx, repairs)
|
||||
snapshotCtx, snapshotCancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
before := filediff.Capture(snapshotCtx, workspace)
|
||||
snapshotCancel()
|
||||
@@ -2324,7 +2383,11 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
err = ctx.Err()
|
||||
return
|
||||
}
|
||||
if r.execute != nil {
|
||||
if stage.EffectiveType(def.Type) == stage.CheckType {
|
||||
// The server runs a check stage's commands itself, in the run
|
||||
// workspace or, for delivery, in a fresh candidate worktree.
|
||||
result, err = r.runCheckStage(stageCtx, def, workspace, delivery, landing, id)
|
||||
} else if r.execute != nil {
|
||||
timeout, _ := stage.StageTimeout(def)
|
||||
executeCtx, cancel := context.WithTimeout(stageCtx, timeout)
|
||||
defer cancel()
|
||||
@@ -2352,7 +2415,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 def.Configs["resume_session"] == "true" && adopted == nil && state.visits[key] > 1 {
|
||||
if adopted != nil {
|
||||
// Follow the CLI the previous process left (see run_reattach.go).
|
||||
claudeClient.Reference = adopted.owner.Reference
|
||||
} else if def.Configs["resume_session"] == "true" && state.visits[key] > 1 {
|
||||
// A loop visit continues the stage's previous session.
|
||||
claudeClient.ResumeSessionID = state.sessions[key]
|
||||
}
|
||||
@@ -2502,7 +2568,26 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
step.Output = stage.Values{"error": err.Error(), "stage": key, "input": input}
|
||||
}
|
||||
}
|
||||
if err == nil && delivery && result.Outcome == "success" {
|
||||
if err == nil {
|
||||
// A stage without edit must leave the run directory as it found it;
|
||||
// a shell is not a licence to write (allow_workspace_changes opts out).
|
||||
ignored := append([]string{artifactsDir, visitTurn.PublicDir}, stage.HarnessStateDirs(workspaceEnv(stageCtx, workspace))...)
|
||||
if violation := readOnlyViolation(def, tools, explicitTools, changes, workspace, ignored); violation != "" {
|
||||
err = errors.New(violation)
|
||||
log.Printf("run %d stage %s #%d: %s", id, key, sequence, violation)
|
||||
step.Status = "failed"
|
||||
step.Diagnostic = violation
|
||||
step.Outcome = "error"
|
||||
step.Output = stage.Values{"error": violation, "stage": key, "input": input}
|
||||
if len(result.Output) > 0 {
|
||||
step.Output["salvage"] = result.Output
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil && stage.EffectiveType(def.Type) == stage.CheckType {
|
||||
step.Verdict = checkVerdict(result.Output)
|
||||
}
|
||||
if err == nil && delivery && stage.EffectiveType(def.Type) == stage.ModelType && result.Outcome == "success" {
|
||||
checks, checksErr := stage.DeliveryChecks(def)
|
||||
if checksErr != nil {
|
||||
err = checksErr
|
||||
@@ -2546,7 +2631,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CleanupUnconfirmed: true}, false)
|
||||
return
|
||||
}
|
||||
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads}
|
||||
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads, OutcomeRepairs: repairs.Count()}
|
||||
if step.Control.OutcomeRepairs > 0 {
|
||||
log.Printf("run %d stage %s #%d: outcome repair follow-up sent %d time(s)", id, key, sequence, step.Control.OutcomeRepairs)
|
||||
}
|
||||
parkExhausted := false
|
||||
if err == nil {
|
||||
parkExhausted = applyLimitOn(&step, selected, state.visits[key], maxVisits)
|
||||
@@ -2588,7 +2676,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
// markdown body, which the field-map summariser reads as untrusted data and
|
||||
// answers with an invented rationale; those steps get the honest read-time
|
||||
// fallback instead.
|
||||
if r.verdict != nil && !turnOutputOnly(step.Output) {
|
||||
if r.verdict != nil && !turnOutputOnly(step.Output) && step.Verdict == nil {
|
||||
reasonCtx, reasonCancel := context.WithTimeout(context.Background(), summarise.DefaultTimeout)
|
||||
if line := r.verdict(reasonCtx, step.Output); line != "" && line != summarise.NoSummary {
|
||||
step.Verdict = &protocol.StageVerdict{Reason: line, ReasonSource: protocol.VerdictReasonModel}
|
||||
|
||||
Reference in New Issue
Block a user