Add stage-exclusive resource waiting

Add durable FIFO capacity-one resource leases for executable stages, including cleanup-confirmed release, conservative restart quarantine, queue state events, and CLI/TUI/Android waiting presentation. Add scheduler, cleanup, protocol, client, and Android coverage plus a proposed Android v3 resource draft.

Checked packaged templates and authoring skill references: neither needs updating in this item. The per-item docs note records the shared documentation that docs-fold must update; no shared README or packaged reference was edited.
This commit is contained in:
2026-10-18 12:30:30 +01:00
parent 88595ebd55
commit 9130ae8c7a
39 changed files with 2657 additions and 79 deletions
+87 -22
View File
@@ -78,12 +78,19 @@ func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
if owner.Backend == "pi" {
err = stage.InterruptPi(stop, owner.Reference)
} else {
err = (stage.OpenCodeClient{Backend: owner.Backend, Directory: owner.Directory, Reference: owner.Reference}).Interrupt(stop, owner.ID)
err = (stage.OpenCodeClient{Backend: owner.Backend, Directory: owner.Directory, Reference: owner.Reference}).InterruptAndConfirm(stop, owner.ID)
}
cancel()
if err != nil {
if resource, checkErr := s.HasResourceOwner(ctx, owner.RunID); checkErr == nil && resource {
log.Printf("resource owner run=%d remains quarantined: cleanup not confirmed", owner.RunID)
continue
}
return nil, fmt.Errorf("cannot interrupt previously active agent %s: %w", owner.ID, err)
}
if err := s.ConfirmRecoveredSession(ctx, owner); err != nil {
return nil, err
}
}
if err := s.RecoverRuns(ctx); err != nil {
return nil, err
@@ -213,6 +220,9 @@ func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.Ru
// workspace) must not block new work.
for _, owner := range owners {
if _, ok := r.active[owner.RunID]; !ok {
if resource, checkErr := r.store.HasResourceOwner(r.ctx, owner.RunID); checkErr == nil && resource && owner.Directory != workspace {
continue
}
r.mu.Unlock()
return nil, fmt.Errorf("an agent may still be active; restart recovery must interrupt it before new work")
}
@@ -775,13 +785,14 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag
// Push the terminal delta before the attention notification, so a slow ntfy
// never delays the live update the app folds.
r.emitRun(protocol.RunEventFrame{
RunID: id,
Workspace: workspace,
Status: status,
Outcome: outcome,
CurrentStage: currentStage,
CompletedSteps: completed,
FinishedAt: time.Now().UTC().Format(time.RFC3339),
RunID: id,
Workspace: workspace,
Status: status,
ResourceWaitSet: true,
Outcome: outcome,
CurrentStage: currentStage,
CompletedSteps: completed,
FinishedAt: time.Now().UTC().Format(time.RFC3339),
}, true)
r.notifyRun(id, name, status, sequence, currentStage, diagnostic)
// The run is terminal: nothing more can notify for it.
@@ -849,6 +860,21 @@ func (r *runner) finishStage(id int64, name, workspace string, selected protocol
}
func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, name, workspace string, request protocol.Message, state *runState) {
var held *pipeline.ResourceLease
resourceQuiet := true
release := func() error {
if held != nil {
err := r.releaseResource(*held, resourceQuiet)
held = nil
return err
}
return nil
}
defer func() {
if err := release(); err != nil {
log.Printf("resource cleanup run=%d: %v", id, err)
}
}()
finish := func(status, outcome, diagnostic string) {
r.finishRunState(id, name, workspace, status, outcome, diagnostic, state.completed, state.nextSequence-1, state.key, state.input)
}
@@ -877,7 +903,6 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
effectiveModels = resolved
}
for sequence := state.nextSequence; sequence <= 30; sequence++ {
state.nextSequence = sequence + 1
if ctx.Err() != nil {
finish("canceled", "", ctx.Err().Error())
return
@@ -909,24 +934,42 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
}
}
isHuman := stage.EffectiveType(def.Type) == stage.HumanType
state.visits[key]++
maxVisits := 5
if selected.Limits != nil {
maxVisits = selected.Limits.MaxVisits
}
// A human stage pauses for a person; neither the global visit budget nor
// the per-stage max_visits may kill it. The shared 30-step run budget
// still bounds every run.
// Validate the next visit without consuming it. An already-exhausted
// stage must not queue for a resource it can never execute.
if !isHuman {
if state.visits[key] > 5 {
if state.visits[key]+1 > 5 {
finish("failed", "error", "stage visit budget exceeded")
return
}
if state.visits[key] > maxVisits {
if state.visits[key]+1 > maxVisits {
finish("failed", "error", fmt.Sprintf("stage %s visit limit reached (%d)", key, maxVisits))
return
}
}
_, declaresSkip := def.Edges["skipped"]
skip := !isHuman && declaresSkip && !state.uiSurface
if selected.Resources != nil && !skip {
if isHuman || !pipeline.ValidResourceKey(selected.Resources.Exclusive) {
finish("failed", "error", "invalid persisted resource declaration")
return
}
lease, err := r.acquireResource(ctx, pipeline.ResourceVisit{Resource: selected.Resources.Exclusive, RunID: id, Stage: key, Sequence: sequence}, workspace, state.completed)
if err != nil {
if ctx.Err() != nil {
finish("canceled", "", err.Error())
} else {
finish("failed", "error", err.Error())
}
return
}
held, resourceQuiet = &lease, true
}
state.nextSequence = sequence + 1
state.visits[key]++
// Publish the run's server-captured changed paths into the input memory
// value before resolving bindings, so a stage selecting
// input.server_changed_files always resolves (an empty list when nothing
@@ -948,12 +991,13 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
}
// queued -> running: report the new current stage and the step start.
r.emitRun(protocol.RunEventFrame{
RunID: id,
Workspace: workspace,
Status: protocol.RunStatusRunning,
CurrentStage: key,
CompletedSteps: state.completed,
Step: &protocol.RunStepDelta{Sequence: sequence, Stage: key, Status: protocol.StepStatusRunning},
RunID: id,
Workspace: workspace,
Status: protocol.RunStatusRunning,
CurrentStage: key,
ResourceWaitSet: true,
CompletedSteps: state.completed,
Step: &protocol.RunStepDelta{Sequence: sequence, Stage: key, Status: protocol.StepStatusRunning},
}, false)
if isHuman {
// A human step is O(1): one BeginStep plus one MarkWaiting, no
@@ -987,7 +1031,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
// the model call and its capture work, record the step as completed and
// route along the declared edge. Only a declared route is honoured, and no
// other stage or outcome routing changes.
if _, declaresSkip := def.Edges["skipped"]; declaresSkip && !state.uiSurface {
if skip {
reason := skipReasonLine(state)
step := protocol.RunStep{
Sequence: sequence,
@@ -1068,6 +1112,9 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
snapshotCancel()
var stageSession string
panicked := false
if held != nil {
resourceQuiet = false
}
func() {
defer func() {
if recover() != nil {
@@ -1075,6 +1122,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
err = fmt.Errorf("stage execution panicked")
}
}()
if ctx.Err() != nil {
err = ctx.Err()
return
}
if r.execute != nil {
timeout, _ := stage.StageTimeout(def)
executeCtx, cancel := context.WithTimeout(stageCtx, timeout)
@@ -1119,6 +1170,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
result, err = stage.DefaultRegistry().Run(ctx, def, input)
}
}()
if held != nil {
resourceQuiet = r.resourceQuiescent(id, err, panicked)
if confirmed, reported := result.Output[protocol.ResourceCleanupConfirmedKey]; reported && confirmed != true {
resourceQuiet = false
}
}
// Capture after cleanup, even when the stage's context was canceled.
snapshotCtx, snapshotCancel = context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
after := filediff.Capture(snapshotCtx, workspace, before)
@@ -1236,6 +1293,14 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
return
}
}
if held != nil && !resourceQuiet {
finish("failed", "error", "resource cleanup/restoration not confirmed; ownership quarantined pending inspection")
return
}
if err := release(); err != nil {
finish("failed", "error", "resource release failed; retained ownership needs reconciliation: "+err.Error())
return
}
if ctx.Err() != nil {
finish("canceled", "", ctx.Err().Error())
return