Add a human decision stage that pauses a run for an operator's choice
A new registered stage type `human` (internal/stage/human.go) has no model,
agent, tools or configs: its required `prompt` block carries the operator
instructions and its non-error edges are the selectable options. It parses,
validates, renders, exports and imports like every other type (no parser
special-case, no config keys).
At runtime the runner parks the run instead of executing: the step and the run
persist `waiting` with self-contained {prompt, options} evidence, and the run
returns without starting later stages, capturing file diffs, scanning artifacts,
holding a goroutine/timer or applying a stage timeout. The wait is durable: a
restart leaves the waiting rows untouched (RecoverRuns excludes them) and a
rebuilt runtime over the same database still accepts the decision.
`pipelines decide <run-id> [stage] --option KEY [--feedback TEXT] [--json]` and
the TUI `c` picker resolve the decision from the pinned graph in one store
transaction, record the choice and feedback as the step's evidence and resume
along edges[KEY]. An unknown option is refused with the valid list, a stage that
is not waiting is refused, and a repeated decision for an already-decided visit
does not double-apply. Cancel and retry keep working while waiting and after a
decision; a human stage is never killed by a stage timeout or max_visits, and a
`notify` policy can fire an `on=waiting` event.
Docs: the authoring skill references (format.md, operations.md), docs/cli.md and
README describe the stage, the command and the TUI picker. Tests cover stage
validation, the parsing round-trip, the store transitions, a websocket wait/decide
integration, cancel/retry, waiting notifications and a persistence-layer rebuild
(second Open + newRunner over one database, no process restart).
This commit is contained in:
+212
-70
@@ -234,15 +234,9 @@ func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.Ru
|
||||
return nil, err
|
||||
}
|
||||
if created {
|
||||
ctx, cancel := context.WithCancel(r.ctx)
|
||||
r.active[id] = activeRun{cancel: cancel, workspace: workspace}
|
||||
r.wg.Add(1)
|
||||
go func() {
|
||||
defer r.wg.Done()
|
||||
defer cancel()
|
||||
defer func() { r.mu.Lock(); delete(r.active, id); r.mu.Unlock() }()
|
||||
r.launch(id, workspace, func(ctx context.Context) {
|
||||
r.run(ctx, id, d, workspace, request)
|
||||
}()
|
||||
})
|
||||
}
|
||||
detail, err := r.store.GetRun(r.ctx, id)
|
||||
if detail != nil {
|
||||
@@ -251,6 +245,22 @@ func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.Ru
|
||||
return detail, err
|
||||
}
|
||||
|
||||
// launch registers an active run's cancellation seam and workspace, adds it to
|
||||
// the wait group and starts fn on a derived cancellable context that cleans up
|
||||
// the registration when it returns. A fresh run and a resumed decision both go
|
||||
// through it, so registration and teardown live once. Callers must hold r.mu.
|
||||
func (r *runner) launch(id int64, workspace string, fn func(context.Context)) {
|
||||
ctx, cancel := context.WithCancel(r.ctx)
|
||||
r.active[id] = activeRun{cancel: cancel, workspace: workspace}
|
||||
r.wg.Add(1)
|
||||
go func() {
|
||||
defer r.wg.Done()
|
||||
defer cancel()
|
||||
defer func() { r.mu.Lock(); delete(r.active, id); r.mu.Unlock() }()
|
||||
fn(ctx)
|
||||
}()
|
||||
}
|
||||
|
||||
// checkWorkspaceFree refuses a run when an active run is already changing the
|
||||
// same resolved workspace. The workspace is the only scope a run reserves, and
|
||||
// one active run per workspace keeps this scan finding at most one match, so the
|
||||
@@ -319,65 +329,174 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
|
||||
func (r *runner) cancel(id int64) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
entry, ok := r.active[id]
|
||||
if !ok {
|
||||
return fmt.Errorf("run is not active")
|
||||
r.mu.Unlock()
|
||||
if ok {
|
||||
entry.cancel()
|
||||
return nil
|
||||
}
|
||||
entry.cancel()
|
||||
return nil
|
||||
// A run that is waiting on a person has no live goroutine, so cancel it at
|
||||
// the persistence layer instead. This keeps cancel working across a restart.
|
||||
return r.store.CancelWaiting(r.ctx, id)
|
||||
}
|
||||
|
||||
// setTitle renames a run: it replaces the stored operator-facing title without
|
||||
// touching the run's input, steps or execution, then returns the updated detail.
|
||||
func (r *runner) setTitle(id int64, title string) (*protocol.RunDetail, error) {
|
||||
explicit, ok := summarise.ExplicitTitle(title)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("a title with usable text is required")
|
||||
// decide records an operator's choice for a waiting human stage and resumes the
|
||||
// run along the chosen edge. ResolveDecision owns validation and idempotency, so
|
||||
// decide does no option parsing of its own. A resumed run is registered and
|
||||
// launched exactly like a fresh one but starts from the persisted state.
|
||||
func (r *runner) decide(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
if request.RunID <= 0 {
|
||||
return nil, fmt.Errorf("decide requires a positive run ID")
|
||||
}
|
||||
if err := r.store.SetRunTitle(r.ctx, id, explicit); err != nil {
|
||||
r.mu.Lock()
|
||||
detail, err := r.store.GetRun(r.ctx, request.RunID)
|
||||
if err != nil {
|
||||
r.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
return r.getRun(id)
|
||||
if _, busy := r.active[detail.ID]; busy {
|
||||
r.mu.Unlock()
|
||||
return nil, fmt.Errorf("run %d is already active; wait for it to pause before deciding", detail.ID)
|
||||
}
|
||||
if detail.Status == protocol.RunStatusWaiting {
|
||||
if err := r.checkWorkspaceFree(detail.Workspace); err != nil {
|
||||
r.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
step, applied, err := r.store.ResolveDecision(r.ctx, detail.ID, request.Stage, request.Option, request.Feedback)
|
||||
if err != nil {
|
||||
r.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
if applied {
|
||||
for i := range detail.Steps {
|
||||
if detail.Steps[i].Sequence == step.Sequence && detail.Steps[i].Stage == step.Stage {
|
||||
detail.Steps[i] = step
|
||||
break
|
||||
}
|
||||
}
|
||||
r.launch(detail.ID, detail.Workspace, func(ctx context.Context) {
|
||||
r.resume(ctx, detail.ID, detail, detail.Workspace, step)
|
||||
})
|
||||
}
|
||||
r.mu.Unlock()
|
||||
return r.getRun(request.RunID)
|
||||
}
|
||||
|
||||
func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail, workspace string, request protocol.Message) {
|
||||
input := stage.Values(request.Input)
|
||||
key := d.Graph.Stages[0].Key
|
||||
visits := map[string]int{}
|
||||
budgets := map[string]*stage.Budget{}
|
||||
finish := func(status, outcome, diagnostic string) {
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := r.store.FinishRun(c, id, status, outcome, diagnostic, input); err != nil {
|
||||
log.Printf("finish run %d: %v", id, err)
|
||||
}
|
||||
}
|
||||
original, copyErr := copyValues(stage.Values(request.Input))
|
||||
if copyErr != nil {
|
||||
finish("failed", "error", copyErr.Error())
|
||||
r.finishRunState(id, "failed", "error", copyErr.Error(), stage.Values(request.Input))
|
||||
return
|
||||
}
|
||||
memory := map[string]memoryValue{"input": {output: original}}
|
||||
input := stage.Values(request.Input)
|
||||
state := newRunState(d.Graph.Stages[0].Key, input)
|
||||
state.memory["input"] = memoryValue{output: original}
|
||||
r.runLoop(ctx, id, d.Graph, d.Name, workspace, request, state)
|
||||
}
|
||||
|
||||
// terminalFinish classifies a stage's resolved target. A terminal key yields the
|
||||
// run's final status, outcome and diagnostic; an empty target means the stage
|
||||
// named an undeclared outcome; any other value is a stage key and is not
|
||||
// terminal. resume and the loop tail share it, so terminal routing lives once.
|
||||
func terminalFinish(target, stageKey, outcome, diagnostic string) (status, finalOutcome, finalDiagnostic string, terminal bool) {
|
||||
switch target {
|
||||
case protocol.SuccessEnd:
|
||||
return "succeeded", "success", "", true
|
||||
case protocol.FailureEnd:
|
||||
if diagnostic == "" {
|
||||
diagnostic = fmt.Sprintf("stage %s returned outcome %q", stageKey, outcome)
|
||||
}
|
||||
return "failed", "error", diagnostic, true
|
||||
case "":
|
||||
return "failed", "error", "stage returned an undeclared outcome", true
|
||||
}
|
||||
return "", "", "", false
|
||||
}
|
||||
|
||||
// resume continues a decided run from the state already persisted for its run
|
||||
// detail: memory from the run input and the completed steps, visits counted per
|
||||
// stage, and the next sequence above the highest recorded one. It then runs the
|
||||
// shared loop from the decision's target; no full-table scan and no extra
|
||||
// per-step query are introduced.
|
||||
func (r *runner) resume(ctx context.Context, id int64, d *protocol.RunDetail, workspace string, step protocol.RunStep) {
|
||||
// The decision may route straight to a terminal, which has no stage to run.
|
||||
if status, outcome, diagnostic, terminal := terminalFinish(step.Target, step.Stage, step.Outcome, step.Diagnostic); terminal {
|
||||
r.finishRunState(id, status, outcome, diagnostic, stage.Values(step.Output))
|
||||
return
|
||||
}
|
||||
state := rebuildRunState(d, step)
|
||||
r.runLoop(ctx, id, d.Graph, d.Name, workspace, protocol.Message{WritePaths: d.WritePaths, AllowTools: d.AllowTools}, state)
|
||||
}
|
||||
|
||||
// runState is the loop's whole mutable state, extracted so a fresh run and a
|
||||
// resumed run share one implementation. nextSequence is set before each visit so
|
||||
// a wait that returns to the caller records where the run will continue.
|
||||
type runState struct {
|
||||
key string
|
||||
nextSequence int
|
||||
visits map[string]int
|
||||
memory map[string]memoryValue
|
||||
input stage.Values
|
||||
}
|
||||
|
||||
func newRunState(key string, input stage.Values) *runState {
|
||||
return &runState{key: key, nextSequence: 1, visits: map[string]int{}, memory: map[string]memoryValue{}, input: input}
|
||||
}
|
||||
|
||||
func rebuildRunState(detail *protocol.RunDetail, decided protocol.RunStep) *runState {
|
||||
state := newRunState(decided.Target, stage.Values(decided.Output))
|
||||
if original, err := copyValues(stage.Values(detail.Input)); err == nil {
|
||||
state.memory["input"] = memoryValue{output: original}
|
||||
}
|
||||
for _, step := range detail.Steps {
|
||||
state.visits[step.Stage]++
|
||||
if step.Sequence >= state.nextSequence {
|
||||
state.nextSequence = step.Sequence + 1
|
||||
}
|
||||
if step.Status == "completed" {
|
||||
if values, err := copyValues(stage.Values(step.Output)); err == nil {
|
||||
state.memory[step.Stage] = memoryValue{output: values, sequence: step.Sequence}
|
||||
}
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
func (r *runner) finishRunState(id int64, status, outcome, diagnostic string, input stage.Values) {
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := r.store.FinishRun(c, id, status, outcome, diagnostic, input); err != nil {
|
||||
log.Printf("finish run %d: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, name, workspace string, request protocol.Message, state *runState) {
|
||||
finish := func(status, outcome, diagnostic string) {
|
||||
r.finishRunState(id, status, outcome, diagnostic, state.input)
|
||||
}
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
finish("failed", "error", "stage execution panicked")
|
||||
}
|
||||
}()
|
||||
for sequence := 1; sequence <= 30; sequence++ {
|
||||
budgets := map[string]*stage.Budget{}
|
||||
if state.key == "" {
|
||||
finish("failed", "error", "stage returned an undeclared outcome")
|
||||
return
|
||||
}
|
||||
for sequence := state.nextSequence; sequence <= 30; sequence++ {
|
||||
state.nextSequence = sequence + 1
|
||||
if ctx.Err() != nil {
|
||||
finish("canceled", "", ctx.Err().Error())
|
||||
return
|
||||
}
|
||||
visits[key]++
|
||||
if visits[key] > 5 {
|
||||
finish("failed", "error", "stage visit budget exceeded")
|
||||
return
|
||||
}
|
||||
key := state.key
|
||||
var def stage.Definition
|
||||
var selected protocol.Stage
|
||||
found := false
|
||||
for _, s := range d.Graph.Stages {
|
||||
for _, s := range graph.Stages {
|
||||
if s.Key == key {
|
||||
selected = s
|
||||
def = pipeline.StageDefinition(s)
|
||||
@@ -389,16 +508,27 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
finish("failed", "error", "missing stage")
|
||||
return
|
||||
}
|
||||
isHuman := stage.EffectiveType(def.Type) == stage.HumanType
|
||||
state.visits[key]++
|
||||
maxVisits := 5
|
||||
if selected.Limits != nil {
|
||||
maxVisits = selected.Limits.MaxVisits
|
||||
}
|
||||
if visits[key] > maxVisits {
|
||||
finish("failed", "error", fmt.Sprintf("stage %s visit limit reached (%d)", key, maxVisits))
|
||||
return
|
||||
// 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.
|
||||
if !isHuman {
|
||||
if state.visits[key] > 5 {
|
||||
finish("failed", "error", "stage visit budget exceeded")
|
||||
return
|
||||
}
|
||||
if state.visits[key] > maxVisits {
|
||||
finish("failed", "error", fmt.Sprintf("stage %s visit limit reached (%d)", key, maxVisits))
|
||||
return
|
||||
}
|
||||
}
|
||||
var reads map[string]protocol.MemoryRead
|
||||
input, reads, copyErr = memoryInput(input, selected.Memory, memory)
|
||||
input, reads, copyErr := memoryInput(state.input, selected.Memory, state.memory)
|
||||
if copyErr != nil {
|
||||
finish("failed", "error", copyErr.Error())
|
||||
return
|
||||
@@ -411,6 +541,22 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
finish("failed", "error", err.Error())
|
||||
return
|
||||
}
|
||||
if isHuman {
|
||||
// A human step is O(1): one BeginStep plus one MarkWaiting, no
|
||||
// filediff capture, no artifacts directory and no workspace mutation.
|
||||
evidence := protocol.NewWaitingEvidence(def.Blocks["prompt"], stage.HumanOptions(def.Edges))
|
||||
if err := r.store.MarkWaiting(ctx, id, sequence, key, evidence); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
finish("canceled", "", ctx.Err().Error())
|
||||
return
|
||||
}
|
||||
finish("failed", "error", err.Error())
|
||||
return
|
||||
}
|
||||
waitStep := protocol.RunStep{Sequence: sequence, Stage: key, Status: protocol.StepStatusWaiting, Output: evidence}
|
||||
r.notifyStep(id, name, workspace, selected.Notify, waitStep)
|
||||
return
|
||||
}
|
||||
var tools []string
|
||||
explicitTools := false
|
||||
var toolErr error
|
||||
@@ -541,8 +687,8 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
step.Transcript = stage.RetainSession(step.Transcript, stageSession)
|
||||
}
|
||||
step.Target = def.Edges[step.Outcome]
|
||||
step.Control = &protocol.ControlEvidence{Visit: visits[key], MaxVisits: maxVisits, Memory: reads}
|
||||
if err == nil && selected.Limits != nil && visits[key] >= maxVisits {
|
||||
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads}
|
||||
if err == nil && selected.Limits != nil && state.visits[key] >= maxVisits {
|
||||
for _, outcome := range selected.Limits.On {
|
||||
if outcome == step.Outcome {
|
||||
step.Control.LimitReached = true
|
||||
@@ -579,15 +725,10 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
finish("failed", "error", err.Error())
|
||||
return
|
||||
}
|
||||
memory[key] = memoryValue{output: values, sequence: sequence}
|
||||
state.memory[key] = memoryValue{output: values, sequence: sequence}
|
||||
}
|
||||
for _, s := range d.Graph.Stages {
|
||||
if s.Key == key {
|
||||
r.notifyStep(id, d, workspace, s.Notify, step)
|
||||
break
|
||||
}
|
||||
}
|
||||
input = stage.Values(step.Output)
|
||||
r.notifyStep(id, name, workspace, selected.Notify, step)
|
||||
state.input = stage.Values(step.Output)
|
||||
if useAgent || errors.Is(err, stage.ErrStageCleanup) {
|
||||
sessions, checkErr := r.store.ActiveAgentSessionsForRun(context.Background(), id)
|
||||
if checkErr != nil || len(sessions) > 0 {
|
||||
@@ -599,23 +740,24 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
finish("canceled", "", ctx.Err().Error())
|
||||
return
|
||||
}
|
||||
if step.Target == protocol.SuccessEnd {
|
||||
finish("succeeded", "success", "")
|
||||
if status, outcome, diagnostic, terminal := terminalFinish(step.Target, step.Stage, step.Outcome, step.Diagnostic); terminal {
|
||||
finish(status, outcome, diagnostic)
|
||||
return
|
||||
}
|
||||
if step.Target == protocol.FailureEnd {
|
||||
diagnostic := step.Diagnostic
|
||||
if diagnostic == "" {
|
||||
diagnostic = fmt.Sprintf("stage %s returned outcome %q", step.Stage, step.Outcome)
|
||||
}
|
||||
finish("failed", "error", diagnostic)
|
||||
return
|
||||
}
|
||||
if step.Target == "" {
|
||||
finish("failed", "error", "stage returned an undeclared outcome")
|
||||
return
|
||||
}
|
||||
key = step.Target
|
||||
state.key = step.Target
|
||||
}
|
||||
finish("failed", "error", "total stage budget exceeded")
|
||||
}
|
||||
|
||||
// setTitle renames a run: it replaces the stored operator-facing title without
|
||||
// touching the run's input, steps or execution, then returns the updated detail.
|
||||
func (r *runner) setTitle(id int64, title string) (*protocol.RunDetail, error) {
|
||||
explicit, ok := summarise.ExplicitTitle(title)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("a title with usable text is required")
|
||||
}
|
||||
if err := r.store.SetRunTitle(r.ctx, id, explicit); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.getRun(id)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user