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:
2026-10-16 16:47:28 +01:00
parent 1b4674d22c
commit a6aff47117
32 changed files with 1782 additions and 87 deletions
+9
View File
@@ -348,6 +348,15 @@ Every run also records a short, single-line title: `pipelines run ... --title "
sets one explicitly, otherwise it is generated from the prompt. `pipelines runs`
and `pipelines inspect` show it beside the pipeline name and version, and
`pipelines title <run-id> "…"` renames it afterwards.
A pipeline may include a `type=human` decision stage: the run pauses as
**waiting** with the stage's instructions and options visible in `inspect` and the
run inspector. Answer it with `pipelines decide <run-id> [stage] --option KEY
[--feedback "…"]` or by pressing **c** in the run inspector to pick an option and
type feedback. The choice and feedback are recorded as the step's evidence and the
run resumes along that edge. The wait is persisted, so it survives a server
restart; an unknown option is refused with the valid list, a stage that is not
waiting is refused, and a repeated decision does not double-apply. **cancel** and
**retry** keep working while waiting and after a decision.
On Home, **r** opens global run history; **/** fuzzy-searches it. Inside a pipeline,
**r** / **:runs** opens only that pipeline's history.
Quit the TUI with **:quit**; **q** does not exit. **Ctrl+C** remains an interrupt.
+17 -1
View File
@@ -201,6 +201,7 @@ Submitting activates included schedules, so review them before publishing.
| Start a run | `run NAME PROMPT [--title TITLE] --yes --json` |
| Run history/inspection | `runs --json`, `inspect ID --json` |
| Rename a run | `title ID "TITLE" --json` |
| Decide a waiting human stage | `decide ID [STAGE] --option KEY [--feedback TEXT] --json` |
| Cancel | `cancel ID --json` |
| Connection and phone settings | `connection --json`, `ping --json` |
| Server/ntfy status popup | `status --json` |
@@ -218,7 +219,7 @@ printf '%s' '{"type":"get_pipeline","pipeline_id":1,"version":1}' | pipelines rp
Existing protocol commands: `ping`, `list_pipelines`, `get_pipeline`,
`list_templates`, `validate`, `submit`, `run_pipeline`, `list_runs`, `get_run`,
`cancel_run`, `retry_run`, `get_status`. `list_runs` also returns all-history `usage`
`cancel_run`, `retry_run`, `decide_run`, `set_run_title`, `get_run_evidence`, `get_status`. `list_runs` also returns all-history `usage`
aggregates. See `internal/protocol/message.go` for JSON envelopes. Mutating RPCs
have real effects; they are not previews. TUI-only animation, scrolling, and
transient client logs are presentation, not separate server capabilities.
@@ -257,6 +258,21 @@ Retry is hidden and rejected while a run is executing or agent cleanup remains
active, even if a terminal status was already persisted. Run RPCs report
`executing` alongside status so clients can distinguish cleanup from completion.
A pipeline may contain a `type=human` decision stage (see the authoring skill's
`references/format.md`). Its step becomes `waiting`, the run reports that it is
waiting on a person, and no later stage runs. `runs`/`inspect --json` show the
`waiting` status, the stage and its recorded instructions and options. Answer it
with `pipelines decide <run-id> [stage] --option KEY [--feedback TEXT] [--json]`
or, in the run inspector, press `c` to open the option picker, choose with
`↑/↓`, type optional feedback with `Tab`, and confirm with Enter. The choice and
feedback are recorded as the step's evidence and the run resumes along
`edges[KEY]`. An unknown option is refused with the valid list, a decision to a
stage that is not waiting is refused, and a repeated decision for an
already-decided visit does not double-apply. The wait is persisted in the run
rows, so it survives a server restart and `decide` still works afterwards;
`cancel` and `retry` keep working while waiting and after a decision, and a
human stage is never killed by a stage timeout or `max_visits`.
The run inspector's upper half shows the entire graph from the run's immutable
pinned version using the shared renderer and viewport. Executed stages and taken
routes retain their colors; unexecuted stages, unchosen routes and unreached
+42 -1
View File
@@ -105,6 +105,46 @@ Use this block for intentional file/command restrictions; prose is not a runtime
permission policy. Keep ordinary workflows language-neutral and unrestricted
within their run directory unless the user asks for a narrower scope.
## Human (decision) stages
A `type=human` stage pauses its run until a person chooses one of its outgoing
options. It has no model, agent, tools or configs: it needs a nonempty `prompt`
block (the operator instructions) and at least one non-`error` `edges` outcome.
Its outcomes are exactly its non-error edges, so a draft can express choices such
as `deploy`, `revise` or `abort`; the mandatory error edge is a failure route,
not a choice. It validates, renders, exports and imports like every other type.
````markdown
# stage gate
```output
The operator's decision evidence.
```
```prompt
Review the screenshots and artifacts above, then choose where the run goes.
```
```edges
deploy -> publish
revise -> worker
abort -> #failure
error -> #failure
```
````
When a run reaches a human stage its step becomes `waiting`, the run reports it is
waiting on a person, and nothing later runs. Decide from the TUI (open the run,
press `c`, pick an option, optionally type feedback, Enter) or the CLI:
`pipelines decide <run-id> [stage] --option KEY [--feedback TEXT]`. The decision
and feedback are recorded as the step's evidence (the feedback stays in the step
output, never an error diagnostic) and the run resumes along that
edge. The wait is persisted, so it survives a server restart. An unknown option is
refused with the valid list; a decision to a stage that is not waiting is refused;
a repeated decision for an already-decided visit does not double-apply. Cancel and
retry keep working while waiting and after a decision, and a human stage is never
killed by a stage timeout or `max_visits` (the shared run budget still applies).
Malformed final JSON has bounded recovery even with `retries=0`; it never changes
verdict/evidence. Recovery tries a deterministic local pass first (append missing
closing delimiters, drop one trailing comma, or insert the single comma/colon the
@@ -139,7 +179,8 @@ are not approved. Warn explicitly before adding/changing schedules.
## Notifications
Stage hooks use the global phone connection, never store credentials. Optional
fenced `notify` block: `on=success,failure`, `artifacts=markdown`.
fenced `notify` block: `on=success,failure` (add `waiting` to fire when a human
stage parks the run), `artifacts=markdown`.
Read this skill's `references/notifications.md` for the minimal terminal-path
recipe and optional native publisher format. Prefer hooks for ordinary success/error
alerts; a request to notify is not a request for a new delivery stage. Do not scan
+16 -4
View File
@@ -30,10 +30,10 @@ parallel/distributed task engine or a guarantee that model reports are correct.
fails another's concurrent run. An active session left over by a restart with no
owning active run is an orphan and still refuses new work until interrupted.
Reusing that active run's request key reattaches idempotently.
There are no parallel branches or built-in human approval stages. Optional
worktrees, full backup/restore, automatic database sync and independent
verifier stage types are future ideas, not existing capabilities. Do not
invent them in definitions.
`type=human` decision stages exist and pause the run (see `references/format.md`);
there are no parallel branches. Optional worktrees, full backup/restore,
automatic database sync and independent verifier stage types are future ideas,
not existing capabilities. Do not invent them in definitions.
- Services are native or Docker-based. With an existing Docker installation do not
start a competing native server. Server APIs are unauthenticated: trusted networks
only; never recommend public exposure. Tool scope is not a universal OS sandbox.
@@ -86,6 +86,18 @@ Use the authoritative `CLI_PREFIX` from the prompt:
bound is a valid, credential-redacted preview envelope (with preserved stage
limits, failure/format diagnostics and the retained session pointer), not the
complete tool history.
- `CLI_PREFIX decide RUN_ID [STAGE] --option KEY [--feedback TEXT] [--json]`: answer
a run that is `waiting` on a `type=human` stage. The status and the stage's
instructions/options are visible in `runs` and `inspect --json` (and the TUI
picker); the stage is inferred from the run's current stage unless named. The
choice and feedback are recorded as the step's evidence (its output and derived
verdict; the feedback is never an error diagnostic) and the run resumes along
`edges[KEY]`. An unknown option is
refused with the valid list; a stage that is not waiting is refused; a repeated
decision for an already-decided visit does not double-apply. The wait is persisted,
so `decide` still works after a server restart. `cancel` and `retry` keep working
while waiting and after a decision; a human stage is never killed by a stage
timeout or `max_visits` (the shared 30-step run budget still applies).
- `CLI_PREFIX run ... --json --wait --wait-timeout DURATION`: `--wait` polls until
terminal and `--wait-timeout` bounds only the client wait after admission,
independent of per-request `--timeout`. A reached wait limit leaves the admitted run
+36
View File
@@ -35,6 +35,7 @@ type App struct {
type options struct {
harness string
url, name, prompt, title, template, workspace, paths, key, opencode, model string
option, feedback string
output string
conflict string
all bool
@@ -107,6 +108,9 @@ func (a App) flags(command string) (*flag.FlagSet, *options) {
f.DurationVar(&o.waitTimeout, "wait-timeout", 0, "Client limit for --wait (0 waits until the run ends); independent of --timeout")
case "cancel", "draft-delete":
f.BoolVar(&o.yes, "yes", false, "Confirm this action without an interactive prompt")
case "decide":
f.StringVar(&o.option, "option", "", "Option key to choose among the waiting stage's edges (required)")
f.StringVar(&o.feedback, "feedback", "", "Optional free-text feedback recorded with the decision")
case "debug":
f.StringVar(&o.harness, "harness", "", "Debugging harness: configured opencode/pi, or nvim")
f.BoolVar(&o.yes, "yes", false, "Approve opening a debugging session without prompting")
@@ -778,6 +782,38 @@ func (a App) Run(ctx context.Context, args []string) error {
return a.finishRun(ctx, r, o, call)
}
return a.output(r.RunDetail)
case "decide":
if len(pos) < 1 || len(pos) > 2 {
return fmt.Errorf("decide requires a run ID and an optional stage key")
}
id, err := strconv.ParseInt(pos[0], 10, 64)
if err != nil || id <= 0 {
return fmt.Errorf("run ID must be positive")
}
option := strings.TrimSpace(o.option)
if option == "" {
return fmt.Errorf("decide requires --option KEY")
}
stageKey := ""
if len(pos) == 2 {
stageKey = pos[1]
}
r, err := call(protocol.Message{Type: protocol.DecideRun, RunID: id, Stage: stageKey, Option: option, Feedback: o.feedback})
if err != nil {
return err
}
if r.RunDetail == nil {
return fmt.Errorf("server did not return run detail")
}
if o.json {
return a.output(r.RunDetail)
}
line := fmt.Sprintf("Decided run #%d: %s · %s", r.RunDetail.ID, option, r.RunDetail.Status)
if feedback := strings.TrimSpace(o.feedback); feedback != "" {
line += " · feedback: " + feedback
}
_, err = fmt.Fprintln(a.Out, line)
return err
case "title":
if len(pos) != 2 {
return fmt.Errorf("title requires a run ID and a title")
+2
View File
@@ -20,6 +20,7 @@ var usage = map[string]string{
"runs": "runs [--pipeline NAME] [--json]",
"inspect": "inspect <run-id> [--json]",
"cancel": "cancel <run-id> [--json]",
"decide": "decide <run-id> [stage] --option KEY [--feedback TEXT] [--json]",
"retry": "retry <run-id> [--json [--wait [--wait-timeout DURATION]]]",
"title": "title <run-id> \"<title>\" [--json]",
"debug": "debug <run-id> [--json | --no-open]",
@@ -44,6 +45,7 @@ var notes = map[string]string{
"run": "Runs in your current directory after action confirmation (--yes skips it). Select a pipeline and compose a multiline task with Ctrl+S. Stage tools are enabled automatically; no file list or typed RUN confirmation. Cancellation does not undo edits. --title sets an explicit run title; without it the title is derived from the prompt. In JSON mode --wait polls until terminal; --wait-timeout bounds only the client wait after admission and is independent of per-request --timeout. A reached wait limit leaves the run active: inspect read-only with `inspect <run-id> --json`, or reattach with --wait reusing the original --request-key (never an automatic replay or cancel).",
"retry": "Start a new attempt of a failed run with the same initial input, directory, pipeline version, and edit scope. Original history is retained. Already-completed side effects are not undone. --wait/--wait-timeout behave as for run: a reached wait limit leaves the new run active; inspect read-only with `inspect <run-id> --json`, or reattach with --wait and the original --request-key instead of starting a duplicate retry.",
"title": "Rename a run's operator-facing title after the fact without touching its input, steps or execution. The title is collapsed to a single bounded line and recorded as explicitly set. `pipelines runs` and `pipelines inspect` then show it.",
"decide": "Choose an option for a run waiting on a human stage. The run must be `waiting`; the option must be one of that stage's non-error edges. The stage is inferred from the run's current stage unless named. The choice and optional --feedback are recorded as the step's evidence (visible in inspect and the TUI) and the run resumes along the chosen edge. An unknown option is refused with the valid list; a repeated decision for an already-decided visit does not double-apply. Works across a server restart because the wait is persisted.",
"debug": "Open a fresh configured harness conversation to investigate a run using inspect/show/runs CLI queries. --harness opencode|pi|nvim chooses another configured harness or read-only nvim packet. Does not resume implementation or retry. --json returns the prompt without launching anything.",
"rpc": "Accepts a JSON protocol envelope; '-' reads stdin. Every TUI server operation is available here too. Mutating commands are not dry runs.",
}
+85
View File
@@ -0,0 +1,85 @@
package cli_test
import (
"context"
"encoding/json"
"strconv"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
const cliHumanSource = "# stage gate\n\n```output\nDecision evidence.\n```\n\n```prompt\nApprove the release.\n```\n\n```edges\ngo -> #success\nhalt -> #failure\nerror -> #failure\n```\n\n```configs\ntype=human\n```\n\n"
func TestCLIDecideWaitingHumanRun(t *testing.T) {
run, store, _ := setup(t)
ctx := context.Background()
if _, err := store.Submit(ctx, "human-ws", cliHumanSource); err != nil {
t.Fatal(err)
}
output, err := run("run", "human-ws", "ship it", "--json", "--yes")
if err != nil {
t.Fatal(err)
}
var started protocol.Message
if err := json.Unmarshal([]byte(output), &started); err != nil || started.RunDetail == nil {
t.Fatalf("run did not return detail: %v %s", err, output)
}
runID := started.RunDetail.ID
waitFor := func(status string) protocol.RunDetail {
t.Helper()
for i := 0; i < 100; i++ {
text, err := run("inspect", strconv.FormatInt(runID, 10), "--json")
if err != nil {
t.Fatal(err)
}
var detail protocol.RunDetail
if err := json.Unmarshal([]byte(text), &detail); err != nil {
t.Fatal(err)
}
if detail.Status == status {
return detail
}
}
t.Fatalf("run never reached %s", status)
return protocol.RunDetail{}
}
waiting := waitFor(protocol.RunStatusWaiting)
if len(waiting.Steps) != 1 || waiting.Steps[0].Status != protocol.StepStatusWaiting {
t.Fatalf("waiting step not visible: %+v", waiting.Steps)
}
if prompt := protocol.WaitingPrompt(waiting.Steps[0].Output); !strings.Contains(prompt, "Approve the release") {
t.Fatalf("waiting prompt not visible: %+v", waiting.Steps[0].Output)
}
if _, err := run("decide", strconv.FormatInt(runID, 10)); err == nil || !strings.Contains(err.Error(), "--option") {
t.Fatalf("missing --option was accepted: %v", err)
}
if _, err := run("decide", strconv.FormatInt(runID, 10), "--option", "launch"); err == nil || !strings.Contains(err.Error(), "valid options") {
t.Fatalf("unknown option was accepted: %v", err)
}
output, err = run("decide", strconv.FormatInt(runID, 10), "gate", "--option", "go", "--feedback", "approved", "--json")
if err != nil {
t.Fatal(err)
}
var decided protocol.RunDetail
if err := json.Unmarshal([]byte(output), &decided); err != nil {
t.Fatal(err)
}
final := waitFor("succeeded")
gate := final.Steps[0]
if gate.Outcome != "go" || gate.Target != protocol.SuccessEnd || gate.Output["feedback"] != "approved" || gate.Diagnostic != "" {
t.Fatalf("decision evidence not recorded: %+v", gate)
}
if gate.Verdict == nil || gate.Verdict.Option != "go → success" || gate.Verdict.Reason != "approved" {
t.Fatalf("derived verdict missing the decision: %+v", gate.Verdict)
}
if _, err := run("help", "decide"); err != nil {
t.Fatal(err)
}
}
+1
View File
@@ -26,6 +26,7 @@ EXECUTE
runs List audited runs; --pipeline filters results
inspect <run-id> Inspect stages, outputs, errors and status
cancel <run-id> Cancel a run; changes are NOT rolled back
decide <run-id> [stage] Choose an option for a run waiting on a person
retry <run-id> Restart a failed run with its original input and directory
title <run-id> "<title>" Rename a run after the fact; input/steps unchanged
debug <run-id> Investigate a run with a configured harness or nvim
+207
View File
@@ -0,0 +1,207 @@
package pipeline
import (
"context"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
const humanSource = "# stage gate\n\n```output\nDecision evidence.\n```\n\n```prompt\nReview the screenshots and choose.\n```\n\n```edges\ndeploy -> worker\nrevise -> worker\nerror -> #failure\n```\n\n```configs\ntype=human\n```\n\n# stage worker\n\n```output\nWork result.\n```\n\n```prompt\nDo the work.\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=2\ntimeout=1h\n```\n\n"
func TestHumanStageAuthoringRoundTrip(t *testing.T) {
graph, err := Parse(humanSource)
if err != nil {
t.Fatal(err)
}
if len(graph.Stages) != 2 || graph.Stages[0].Type != "human" {
t.Fatalf("human type not parsed: %+v", graph.Stages)
}
gate := graph.Stages[0]
if strings.TrimSpace(gate.Prompt) == "" || gate.Edges["deploy"] != "worker" {
t.Fatalf("human stage fields lost: %+v", gate)
}
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "human.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "human", humanSource); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
definition, err := store.Get(ctx, items[0].ID, 1)
if err != nil {
t.Fatal(err)
}
if definition.Source != humanSource {
t.Fatal("immutable source was rewritten")
}
if definition.Graph.Stages[0].Type != "human" {
t.Fatalf("human type lost in stored graph: %+v", definition.Graph.Stages[0])
}
}
func humanRun(t *testing.T, ctx context.Context, store *Store) (int64, string) {
t.Helper()
if _, err := store.Submit(ctx, "humangate", humanSource); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
definition, err := store.Get(ctx, items[0].ID, 1)
if err != nil {
t.Fatal(err)
}
id, _, err := store.CreateRun(ctx, definition, "humangate-run", "workspace", false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if err := store.BeginStep(ctx, id, 1, "gate", map[string]any{"prompt": "task"}); err != nil {
t.Fatal(err)
}
evidence := protocol.NewWaitingEvidence("Review the screenshots and choose.", []string{"deploy", "revise"})
if err := store.MarkWaiting(ctx, id, 1, "gate", evidence); err != nil {
t.Fatal(err)
}
return id, "gate"
}
func TestMarkWaitingPersistsDurableWait(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "wait.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
id, _ := humanRun(t, ctx, store)
detail, err := store.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
if detail.Status != protocol.RunStatusWaiting || detail.CurrentStage != "gate" || detail.FinishedAt != "" {
t.Fatalf("run did not report waiting: %+v", detail.RunSummary)
}
if len(detail.Steps) != 1 || detail.Steps[0].Status != protocol.StepStatusWaiting || detail.Steps[0].FinishedAt != "" {
t.Fatalf("step did not persist waiting: %+v", detail.Steps)
}
if prompt := protocol.WaitingPrompt(detail.Steps[0].Output); prompt == "" {
t.Fatalf("waiting evidence lost its prompt: %+v", detail.Steps[0].Output)
}
if options := protocol.WaitingOptions(detail.Steps[0].Output); len(options) != 2 {
t.Fatalf("waiting evidence lost its options: %+v", options)
}
// Recovery from persisted rows must leave a waiting run and step untouched.
if err := store.RecoverRuns(ctx); err != nil {
t.Fatal(err)
}
recovered, err := store.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
if recovered.Status != protocol.RunStatusWaiting || recovered.Steps[0].Status != protocol.StepStatusWaiting {
t.Fatalf("RecoverRuns disturbed a waiting run: %+v", recovered.RunSummary)
}
}
func TestResolveDecisionValidUnknownRepeatAndNotWaiting(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "decide.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
id, _ := humanRun(t, ctx, store)
if _, _, err := store.ResolveDecision(ctx, id, "", "launch", ""); err == nil || !strings.Contains(err.Error(), "valid options") || !strings.Contains(err.Error(), "deploy") {
t.Fatalf("unknown option not refused with the valid list: %v", err)
}
step, applied, err := store.ResolveDecision(ctx, id, "", "deploy", "looks good, ship it")
if err != nil || !applied {
t.Fatalf("valid decision failed: %+v %v %v", step, applied, err)
}
if step.Outcome != "deploy" || step.Target != "worker" {
t.Fatalf("decision did not route along the edge: %+v", step)
}
detail, err := store.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
if detail.Status != "running" || detail.Steps[0].Status != "completed" || detail.Steps[0].Outcome != "deploy" {
t.Fatalf("decision not persisted: %+v", detail)
}
if detail.Steps[0].Diagnostic != "" {
t.Fatalf("a deliberate decision must not be recorded as a stop: %+v", detail.Steps[0])
}
if detail.Steps[0].Output["option"] != "deploy" || detail.Steps[0].Output["feedback"] != "looks good, ship it" {
t.Fatalf("feedback not recorded in the output: %+v", detail.Steps[0])
}
verdict := detail.Steps[0].Verdict
if verdict == nil || verdict.Option != "deploy → worker" || verdict.Reason != "looks good, ship it" {
t.Fatalf("derived verdict missing the choice or feedback: %+v", verdict)
}
// A repeated decision for the already-decided visit must not double-apply.
repeat, applied, err := store.ResolveDecision(ctx, id, "", "deploy", "second try")
if err != nil || applied {
t.Fatalf("repeat decision double-applied: applied=%v err=%v", applied, err)
}
if repeat.Sequence != step.Sequence {
t.Fatalf("repeat decision pointed at another visit: %+v", repeat)
}
// A different option for the same decided visit is refused.
if _, _, err := store.ResolveDecision(ctx, id, "", "revise", ""); err == nil || !strings.Contains(err.Error(), "not waiting") {
t.Fatalf("deciding a decided visit with another option was accepted: %v", err)
}
// A run whose graph has no human stage cannot be decided.
if _, err := store.Submit(ctx, "plain", Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
plainItems, _ := store.List(ctx)
var plain protocol.PipelineSummary
for _, p := range plainItems {
if p.Name == "plain" {
plain = p
}
}
plainDef, err := store.Get(ctx, plain.ID, 1)
if err != nil {
t.Fatal(err)
}
plainRun, _, err := store.CreateRun(ctx, plainDef, "plain-run", "workspace", false, nil, map[string]any{"prompt": "task"})
if err != nil {
t.Fatal(err)
}
if _, _, err := store.ResolveDecision(ctx, plainRun, "", "success", ""); err == nil {
t.Fatal("decision on a run with no human stage was accepted")
}
}
func TestCancelWaitingRun(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "cancel.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
id, _ := humanRun(t, ctx, store)
if err := store.CancelWaiting(ctx, id); err != nil {
t.Fatal(err)
}
detail, err := store.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
if detail.Status != "canceled" || detail.Steps[0].Status != "canceled" {
t.Fatalf("waiting run not canceled: %+v %+v", detail.RunSummary, detail.Steps)
}
if err := store.CancelWaiting(ctx, id); err == nil {
t.Fatal("canceling an already-canceled run succeeded")
}
}
+1 -1
View File
@@ -49,7 +49,7 @@ func parseNotify(text string) (*protocol.NotificationPolicy, error) {
return result, nil
}
var err error
p.On, err = parse(values["on"], map[string]bool{"success": true, "failure": true})
p.On, err = parse(values["on"], map[string]bool{"success": true, "failure": true, protocol.NotifyWaiting: true})
if err != nil {
return nil, err
}
+154 -2
View File
@@ -582,6 +582,158 @@ WHERE run_id=? AND sequence=? AND status='running'`, step.Status, step.Outcome,
return tx.Commit()
}
// MarkWaiting persists a human stage's pending state in one transaction: the
// step becomes waiting with self-contained evidence (its operator instructions
// and ordered options) and the run reports the same key it is waiting on. It
// leaves finished_at NULL for both and adds no goroutine, timer or new column.
func (s *Store) MarkWaiting(ctx context.Context, id int64, sequence int, key string, evidence map[string]any) error {
data, err := json.Marshal(evidence)
if err != nil {
return err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if err := affected(tx.ExecContext(ctx, `UPDATE run_steps SET status=?,output_json=? WHERE run_id=? AND sequence=? AND status='running'`,
protocol.StepStatusWaiting, string(data), id, sequence)); err != nil {
return err
}
if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status=?,current_stage=? WHERE id=? AND status IN ('queued','running')`,
protocol.RunStatusWaiting, key, id)); err != nil {
return err
}
return tx.Commit()
}
// ResolveDecision records an operator's choice for a waiting human stage and
// routes the run along that option's edge, all in one short transaction. It
// reads the pinned graph and the pending step from persisted rows, so it is
// correct after a restart and needs no live goroutine. Validation is idempotent:
// a repeated decision for an already-decided visit with the same option returns
// applied=false and no error, an unknown option is refused with the valid list,
// and a stage that is not waiting is refused with its current state.
func (s *Store) ResolveDecision(ctx context.Context, id int64, stageKey, option, feedback string) (protocol.RunStep, bool, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return protocol.RunStep{}, false, err
}
defer tx.Rollback()
var status, currentStage, graphJSON string
if err := tx.QueryRowContext(ctx, `SELECT r.status,r.current_stage,v.graph_json FROM pipeline_runs r
JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version WHERE r.id=?`, id).Scan(&status, &currentStage, &graphJSON); err != nil {
if err == sql.ErrNoRows {
return protocol.RunStep{}, false, fmt.Errorf("run not found")
}
return protocol.RunStep{}, false, err
}
if stageKey == "" {
stageKey = currentStage
// Prefer the actual waiting step's stage; current_stage is normally the
// waiting stage, but this keeps the decision correct if it ever drifts.
var waitingKey string
if err := tx.QueryRowContext(ctx, `SELECT stage_key FROM run_steps WHERE run_id=? AND status=? ORDER BY sequence DESC LIMIT 1`, id, protocol.StepStatusWaiting).Scan(&waitingKey); err == nil {
stageKey = waitingKey
} else if err != sql.ErrNoRows {
return protocol.RunStep{}, false, err
}
}
var graph protocol.Graph
if err := json.Unmarshal([]byte(graphJSON), &graph); err != nil {
return protocol.RunStep{}, false, err
}
var edges map[string]string
found := false
for _, declared := range graph.Stages {
if declared.Key == stageKey {
edges = declared.Edges
found = true
break
}
}
if !found {
return protocol.RunStep{}, false, fmt.Errorf("stage %q is not part of this run", stageKey)
}
options := stage.HumanOptions(edges)
valid := false
for _, candidate := range options {
if candidate == option {
valid = true
break
}
}
if !valid {
return protocol.RunStep{}, false, fmt.Errorf("unknown option %q for stage %s; valid options: %s", option, stageKey, strings.Join(options, ", "))
}
var sequence int
var stepStatus, stepOutcome string
err = tx.QueryRowContext(ctx, `SELECT sequence,status,outcome FROM run_steps WHERE run_id=? AND stage_key=? ORDER BY sequence DESC LIMIT 1`, id, stageKey).Scan(&sequence, &stepStatus, &stepOutcome)
if err == sql.ErrNoRows {
return protocol.RunStep{}, false, fmt.Errorf("stage %s is not waiting", stageKey)
}
if err != nil {
return protocol.RunStep{}, false, err
}
if stepStatus != protocol.StepStatusWaiting {
if stepStatus == "completed" && stepOutcome == option {
return protocol.RunStep{Sequence: sequence, Stage: stageKey, Status: "completed", Outcome: stepOutcome, Target: edges[stepOutcome]}, false, nil
}
return protocol.RunStep{}, false, fmt.Errorf("stage %s is not waiting (state %s)", stageKey, stepStatus)
}
if status != protocol.RunStatusWaiting && status != protocol.RunStatusRunning {
return protocol.RunStep{}, false, fmt.Errorf("run %d is not waiting (state %s)", id, status)
}
target := edges[option]
// The operator's choice and feedback are the step's evidence. The feedback
// stays in the output only - never the step diagnostic - so a deliberate,
// successful decision is not presented as a stop or error; the derived
// verdict reads the feedback as the step's reason.
output := map[string]any{"option": option, "feedback": feedback}
encoded, err := json.Marshal(output)
if err != nil {
return protocol.RunStep{}, false, err
}
if err := affected(tx.ExecContext(ctx, `UPDATE run_steps SET status='completed',outcome=?,target=?,output_json=?,finished_at=CURRENT_TIMESTAMP
WHERE run_id=? AND sequence=? AND status=?`, option, target, string(encoded), id, sequence, protocol.StepStatusWaiting)); err != nil {
return protocol.RunStep{}, false, err
}
if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status='running' WHERE id=? AND status IN (?,?)`, id, protocol.RunStatusWaiting, protocol.RunStatusRunning)); err != nil {
return protocol.RunStep{}, false, err
}
if err := tx.Commit(); err != nil {
return protocol.RunStep{}, false, err
}
return protocol.RunStep{Sequence: sequence, Stage: stageKey, Status: "completed", Outcome: option, Target: target, Output: output}, true, nil
}
// CancelWaiting cancels a run that is waiting on a person without a live
// goroutine. It is a single transaction that marks the run canceled and its
// waiting step canceled; a run that is not waiting is reported, not silently
// ignored.
func (s *Store) CancelWaiting(ctx context.Context, id int64) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
res, err := tx.ExecContext(ctx, `UPDATE pipeline_runs SET status='canceled',finished_at=CURRENT_TIMESTAMP WHERE id=? AND status=?`, id, protocol.RunStatusWaiting)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("run is not active or waiting")
}
if _, err := tx.ExecContext(ctx, `UPDATE run_steps SET status='canceled',diagnostic='Canceled while waiting for a decision',finished_at=CURRENT_TIMESTAMP WHERE run_id=? AND status=?`, id, protocol.StepStatusWaiting); err != nil {
return err
}
return tx.Commit()
}
func (s *Store) FinishRun(ctx context.Context, id int64, status, outcome, diagnostic string, output map[string]any) error {
data, err := json.Marshal(output)
if err != nil {
@@ -617,10 +769,10 @@ func (s *Store) RecoverRuns(ctx context.Context) error {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, "UPDATE run_steps SET status='interrupted',agent_active=0,diagnostic='Server stopped; stage was not resumed',finished_at=CURRENT_TIMESTAMP WHERE status='running' OR agent_active=1"); err != nil {
if _, err := tx.ExecContext(ctx, "UPDATE run_steps SET status='interrupted',agent_active=0,diagnostic='Server stopped; stage was not resumed',finished_at=CURRENT_TIMESTAMP WHERE (status='running' OR agent_active=1) AND status<>?", protocol.StepStatusWaiting); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic='Server stopped; run was not resumed',finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running')"); err != nil {
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic='Server stopped; run was not resumed',finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>?", protocol.RunStatusWaiting); err != nil {
return err
}
return tx.Commit()
+3
View File
@@ -129,6 +129,9 @@ type Message struct {
RunID int64 `json:"run_id,omitempty"`
RunDetail *RunDetail `json:"run_detail,omitempty"`
Runs []RunSummary `json:"runs,omitempty"`
Stage string `json:"stage,omitempty"`
Option string `json:"option,omitempty"`
Feedback string `json:"feedback,omitempty"`
Input map[string]any `json:"input,omitempty"`
AllowTools bool `json:"allow_tools,omitempty"`
WritePaths []string `json:"write_paths,omitempty"`
+56
View File
@@ -11,11 +11,67 @@ const (
Run = "run"
CancelRun = "cancel_run"
RetryRun = "retry_run"
DecideRun = "decide_run"
SetRunTitle = "set_run_title"
GetRunEvidence = "get_run_evidence"
RunEvidence = "run_evidence"
)
// Waiting statuses. A human stage pauses its run without a live goroutine, so
// the run and its step persist these statuses and the decision path resumes
// them. Store, server, CLI and TUI read the one pair below, never a literal.
const (
RunStatusWaiting = "waiting"
RunStatusRunning = "running"
StepStatusWaiting = "waiting"
// NotifyWaiting is the notification event a human stage emits when it parks
// the run. It is the same value the `on=` policy accepts.
NotifyWaiting = "waiting"
)
// Waiting evidence keys. A human stage records its operator instructions and
// its ordered selectable options in the step output, so inspect and the TUI are
// self-contained without re-reading the pinned graph.
const (
WaitingPromptKey = "prompt"
WaitingOptionsKey = "options"
)
// NewWaitingEvidence builds the self-contained evidence a human stage persists
// at wait time: the operator instructions and the ordered options to choose.
func NewWaitingEvidence(prompt string, options []string) map[string]any {
ordered := make([]any, len(options))
for i, option := range options {
ordered[i] = option
}
return map[string]any{WaitingPromptKey: prompt, WaitingOptionsKey: ordered}
}
// WaitingPrompt reads the recorded operator instructions from a waiting step's
// output, or "" when none were recorded.
func WaitingPrompt(output map[string]any) string {
prompt, _ := output[WaitingPromptKey].(string)
return prompt
}
// WaitingOptions reads the recorded selectable options from a waiting step's
// output, accepting the string and generic forms JSON decoding produces.
func WaitingOptions(output map[string]any) []string {
switch options := output[WaitingOptionsKey].(type) {
case []string:
return options
case []any:
result := make([]string, 0, len(options))
for _, option := range options {
if text, ok := option.(string); ok {
result = append(result, text)
}
}
return result
}
return nil
}
type SessionEvidence struct {
Sequence int `json:"sequence"`
SessionID string `json:"session_id"`
+3 -1
View File
@@ -9,7 +9,9 @@ import (
// VerdictReasonKeys is the single ordered definition of the output keys a stage
// may use to state why it chose its outcome. The first key carrying usable text
// wins. Store, server and TUI all read this one list, so the order never drifts.
var VerdictReasonKeys = []string{"verdict", "reason", "decision", "summary", "implementation_summary"}
// "feedback" is last so it only states the reason when no model-authored key
// does: an operator's decision feedback is exactly the human stage's reason.
var VerdictReasonKeys = []string{"verdict", "reason", "decision", "summary", "implementation_summary", "feedback"}
// VerdictReasonCap bounds a verdict reason to this many runes, whether it was
// generated by the model or derived at read time. It is the same cap the
+2
View File
@@ -70,6 +70,8 @@ func TestDeriveVerdictReasonKeyOrder(t *testing.T) {
{"implementation_summary alone", map[string]any{"implementation_summary": "i"}, "i"},
{"non-string is encoded", map[string]any{"summary": 42}, "42"},
{"empty values skipped to a later key", map[string]any{"reason": " ", "summary": "s"}, "s"},
{"feedback states the reason when nothing else does", map[string]any{"option": "go", "feedback": "looks good"}, "looks good"},
{"summary still wins over feedback", map[string]any{"summary": "s", "feedback": "f"}, "s"},
{"none yields nothing", map[string]any{"other": "x", "screenshots": []any{"a.png"}}, ""},
{"nil output yields nothing", nil, ""},
}
+438
View File
@@ -0,0 +1,438 @@
package server
import (
"context"
"encoding/json"
"fmt"
"mime"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync/atomic"
"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"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
)
const humanPipelineSource = "# stage gate\n\n```output\nDecision evidence.\n```\n\n```prompt\nReview the screenshots and choose where the run goes.\n```\n\n```edges\ngo -> worker\nhalt -> #success\nerror -> #failure\n```\n\n```configs\ntype=human\n```\n\n# stage worker\n\n```output\nWork result.\n```\n\n```prompt\nDo the work.\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=2\ntimeout=1h\n```\n\n"
func successExecute(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
// startHumanRun submits the human pipeline (once) and starts one run, returning
// once the run goroutine has parked the run in the waiting state.
func startHumanRun(t *testing.T, ctx context.Context, r *runner, store *pipeline.Store, key string) *protocol.RunDetail {
t.Helper()
items, _ := store.List(ctx)
var pipelineID int64
for _, p := range items {
if p.Name == "human" {
pipelineID = p.ID
}
}
if pipelineID == 0 {
if _, err := store.Submit(ctx, "human", humanPipelineSource); err != nil {
t.Fatal(err)
}
items, _ = store.List(ctx)
for _, p := range items {
if p.Name == "human" {
pipelineID = p.ID
}
}
}
run, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: key, Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
return run
}
func TestHumanStageWaitsAndDecisionResumes(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "human.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
defer r.wg.Wait()
r.execute = successExecute
run := startHumanRun(t, ctx, r, store, "human-go")
detail, err := r.getRun(run.ID)
if err != nil {
t.Fatal(err)
}
if detail.Status != protocol.RunStatusWaiting || detail.CurrentStage != "gate" {
t.Fatalf("run did not wait: %+v", detail.RunSummary)
}
if len(detail.Steps) != 1 || detail.Steps[0].Status != protocol.StepStatusWaiting {
t.Fatalf("waiting step not persisted: %+v", detail.Steps)
}
if prompt := protocol.WaitingPrompt(detail.Steps[0].Output); !strings.Contains(prompt, "Review the screenshots") {
t.Fatalf("waiting step omitted its prompt: %+v", detail.Steps[0].Output)
}
if options := protocol.WaitingOptions(detail.Steps[0].Output); strings.Join(options, ",") != "go,halt" {
t.Fatalf("waiting step omitted its options: %+v", options)
}
if detail.Steps[0].FinishedAt != "" {
t.Fatalf("waiting step must not be finished: %+v", detail.Steps[0])
}
// No later step is created while waiting.
if len(detail.Steps) != 1 {
t.Fatalf("a later step ran while waiting: %+v", detail.Steps)
}
// Unknown option is refused with the valid list.
if _, err := r.decide(protocol.Message{RunID: run.ID, Option: "launch"}); err == nil || !strings.Contains(err.Error(), "valid options") || !strings.Contains(err.Error(), "go") {
t.Fatalf("unknown option not refused with the list: %v", err)
}
decided, err := r.decide(protocol.Message{RunID: run.ID, Option: "go", Feedback: "looks good"})
if err != nil {
t.Fatal(err)
}
if decided.Status != "running" {
t.Fatalf("decided run did not resume: %+v", decided.RunSummary)
}
r.wg.Wait()
detail, err = store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
if detail.Status != "succeeded" || len(detail.Steps) != 2 {
t.Fatalf("run did not resume to completion: %+v", detail.RunSummary)
}
gate := detail.Steps[0]
if gate.Status != "completed" || gate.Outcome != "go" || gate.Target != "worker" || gate.Diagnostic != "" {
t.Fatalf("decision evidence not recorded: %+v", gate)
}
if gate.Output["option"] != "go" || gate.Output["feedback"] != "looks good" {
t.Fatalf("decision output missing option/feedback: %+v", gate.Output)
}
if gate.Verdict == nil || gate.Verdict.Option != "go → worker" || gate.Verdict.Reason != "looks good" {
t.Fatalf("derived verdict missing the decision: %+v", gate.Verdict)
}
// A repeated decision for the already-decided visit must be an idempotent
// no-op (applied=false, no error) and must not create another step. Naming
// the stage explicitly keeps this on the decided visit instead of relying on
// current_stage having advanced past it.
repeat, err := r.decide(protocol.Message{RunID: run.ID, Stage: "gate", Option: "go"})
if err != nil {
t.Fatalf("repeat decision for a decided visit was refused: %v", err)
}
if repeat == nil || repeat.Status != "succeeded" {
t.Fatalf("repeat decision changed the run: %+v", repeat)
}
after, err := store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
if len(after.Steps) != 2 {
t.Fatalf("repeat decision created another step: %+v", after.Steps)
}
}
func TestHumanDecisionToTerminalFinalizesRun(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "terminal.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
defer r.wg.Wait()
r.execute = successExecute
run := startHumanRun(t, ctx, r, store, "human-halt")
if _, err := r.decide(protocol.Message{RunID: run.ID, Option: "halt", Feedback: "approved"}); err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
if detail.Status != "succeeded" || len(detail.Steps) != 1 || detail.Steps[0].Target != protocol.SuccessEnd {
t.Fatalf("decision to success did not finalize the run: %+v", detail.RunSummary)
}
}
func TestHumanStageCancelRetryAndRebuild(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
path := filepath.Join(t.TempDir(), "rebuild.db")
store, err := pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
r.execute = successExecute
run := startHumanRun(t, ctx, r, store, "human-rebuild")
// Cancel works while waiting.
if err := r.cancel(run.ID); err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
if detail.Status != "canceled" || detail.Steps[0].Status != "canceled" {
t.Fatalf("waiting run not canceled: %+v %+v", detail.RunSummary, detail.Steps)
}
if err := r.cancel(run.ID); err == nil {
t.Fatal("canceling a canceled run succeeded")
}
if err := store.Close(); err != nil {
t.Fatal(err)
}
// Rebuild runtime state from persisted rows: a second Open + newRunner over
// the same database, with no process restart. RecoverRuns must leave a
// waiting run waiting.
store, err = pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
defer store.Close()
r2, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
defer r2.wg.Wait()
r2.execute = successExecute
waiting := startHumanRun(t, ctx, r2, store, "human-rebuild-2")
if err := store.Close(); err != nil {
t.Fatal(err)
}
store, err = pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
r3, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
defer r3.wg.Wait()
r3.execute = successExecute
recovered, err := r3.getRun(waiting.ID)
if err != nil {
t.Fatal(err)
}
if recovered.Status != protocol.RunStatusWaiting || recovered.Steps[0].Status != protocol.StepStatusWaiting {
t.Fatalf("rebuilt runtime lost the wait: %+v %+v", recovered.RunSummary, recovered.Steps)
}
if _, err := r3.decide(protocol.Message{RunID: waiting.ID, Option: "go", Feedback: "after restart"}); err != nil {
t.Fatal(err)
}
r3.wg.Wait()
final, err := store.GetRun(ctx, waiting.ID)
if err != nil {
t.Fatal(err)
}
if final.Status != "succeeded" || final.Steps[0].Outcome != "go" || final.Steps[0].Output["feedback"] != "after restart" {
t.Fatalf("rebuilt runtime refused or mis-recorded the decision: %+v", final)
}
// Retry works after a decision that later fails.
failing := startHumanRun(t, ctx, r3, store, "human-retry")
r3.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{}, fmt.Errorf("provider failed")
}
if _, err := r3.decide(protocol.Message{RunID: failing.ID, Option: "go"}); err != nil {
t.Fatal(err)
}
r3.wg.Wait()
failed, err := store.GetRun(ctx, failing.ID)
if err != nil {
t.Fatal(err)
}
if failed.Status != "failed" {
t.Fatalf("post-decision failure did not fail the run: %+v", failed.RunSummary)
}
r3.execute = successExecute
retried, err := r3.retry(protocol.Message{RunID: failing.ID, RequestKey: "retry-human"})
if err != nil {
t.Fatal(err)
}
r3.wg.Wait()
retriedDetail, err := store.GetRun(ctx, retried.ID)
if err != nil {
t.Fatal(err)
}
if retried.ID == failing.ID || retriedDetail.Status != protocol.RunStatusWaiting {
t.Fatalf("retry after a decision did not start a fresh waiting run: %+v", retriedDetail.RunSummary)
}
}
const humanOnlySource = "# stage gate\n\n```output\nDecision evidence.\n```\n\n```prompt\nApprove the release.\n```\n\n```edges\ngo -> #success\nhalt -> #failure\nerror -> #failure\n```\n\n```configs\ntype=human\n```\n\n"
func TestHumanRunWebSocketWaitAndDecide(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "ws.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "human-ws", humanOnlySource); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
handler := Handler(ctx, store).(*runHandler)
defer func() { cancel(); WaitRuns(handler) }()
srv := httptest.NewServer(handler)
defer srv.Close()
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
if err != nil {
t.Fatal(err)
}
defer conn.CloseNow()
var snapshot protocol.Message
if err := wsjson.Read(ctx, conn, &snapshot); err != nil {
t.Fatal(err)
}
request := func(message protocol.Message) protocol.Message {
t.Helper()
if err := wsjson.Write(ctx, conn, message); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
return response
}
started := request(protocol.Message{Type: protocol.RunPipeline, ID: "start", PipelineID: items[0].ID, Version: 1, RequestKey: "ws-human", Input: map[string]any{"prompt": "ship it"}})
if started.Type != protocol.RunStarted || started.RunDetail == nil {
t.Fatalf("run not started: %+v", started)
}
runID := started.RunDetail.ID
var waiting protocol.Message
for i := 0; i < 50; i++ {
waiting = request(protocol.Message{Type: protocol.GetRun, ID: "poll", RunID: runID})
if waiting.RunDetail != nil && waiting.RunDetail.Status == protocol.RunStatusWaiting {
break
}
if waiting.Type == protocol.Error {
t.Fatal(waiting.Error)
}
time.Sleep(20 * time.Millisecond)
}
if waiting.RunDetail == nil || waiting.RunDetail.Status != protocol.RunStatusWaiting || waiting.RunDetail.CurrentStage != "gate" {
t.Fatalf("run never reached waiting: %+v", waiting.RunDetail)
}
if len(waiting.RunDetail.Steps) != 1 || waiting.RunDetail.Steps[0].Status != protocol.StepStatusWaiting {
t.Fatalf("waiting step not visible over websocket: %+v", waiting.RunDetail.Steps)
}
if prompt := protocol.WaitingPrompt(waiting.RunDetail.Steps[0].Output); !strings.Contains(prompt, "Approve the release") {
t.Fatalf("prompt not visible over websocket: %+v", waiting.RunDetail.Steps[0].Output)
}
if options := protocol.WaitingOptions(waiting.RunDetail.Steps[0].Output); strings.Join(options, ",") != "go,halt" {
t.Fatalf("options not visible over websocket: %+v", options)
}
// Unknown option is refused verbatim over the wire.
bad := request(protocol.Message{Type: protocol.DecideRun, ID: "bad", RunID: runID, Option: "launch"})
if bad.Type != protocol.Error || !strings.Contains(bad.Error, "valid options") {
t.Fatalf("unknown option not refused over websocket: %+v", bad)
}
decided := request(protocol.Message{Type: protocol.DecideRun, ID: "decide", RunID: runID, Option: "go", Feedback: "approved"})
if decided.Type != protocol.Run || decided.RunDetail == nil {
t.Fatalf("decision not accepted over websocket: %+v", decided)
}
var final protocol.Message
for i := 0; i < 50; i++ {
final = request(protocol.Message{Type: protocol.GetRun, ID: "final", RunID: runID})
if final.RunDetail != nil && final.RunDetail.Status != protocol.RunStatusWaiting && final.RunDetail.Status != "running" {
break
}
time.Sleep(20 * time.Millisecond)
}
if final.RunDetail == nil || final.RunDetail.Status != "succeeded" {
t.Fatalf("decided run did not complete over websocket: %+v", final.RunDetail)
}
if final.RunDetail.Steps[0].Outcome != "go" || final.RunDetail.Steps[0].Output["feedback"] != "approved" {
t.Fatalf("decision evidence not persisted over websocket: %+v", final.RunDetail.Steps[0])
}
}
func TestHumanStageWaitingNotification(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "notify.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
filename, _ := new(mime.WordDecoder).DecodeHeader(r.Header.Get("Filename"))
ack := map[string]any{"id": "msg1", "event": "message"}
if filename != "" {
ack["attachment"] = map[string]string{"name": filename, "url": "https://ntfy.example.com/file/" + filename}
}
_ = json.NewEncoder(w).Encode(ack)
}))
defer srv.Close()
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
source := strings.Replace(humanPipelineSource, "```configs\ntype=human\n```", "```notify\non=waiting\n```\n\n```configs\ntype=human\n```", 1)
if _, err := store.Submit(ctx, "human-notify", source); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
var pipelineID int64
for _, p := range items {
if p.Name == "human-notify" {
pipelineID = p.ID
}
}
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
defer r.wg.Wait()
run, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "human-notify", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if calls.Load() != 1 {
t.Fatalf("waiting notification fired %d times", calls.Load())
}
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
if len(detail.Steps[0].Notifications) != 1 || detail.Steps[0].Notifications[0].Status != "sent" {
t.Fatalf("waiting notification receipt missing: %+v", detail.Steps[0].Notifications)
}
}
+5 -3
View File
@@ -15,12 +15,14 @@ import (
"unicode/utf8"
)
func (r *runner) notifyStep(id int64, d *protocol.PipelineDetail, workspace string, policy *protocol.NotificationPolicy, step protocol.RunStep) {
func (r *runner) notifyStep(id int64, name, workspace string, policy *protocol.NotificationPolicy, step protocol.RunStep) {
if policy == nil {
return
}
event := "success"
if step.Status != "completed" || step.Outcome == "error" || step.Target == protocol.FailureEnd {
if step.Status == protocol.StepStatusWaiting || step.Outcome == protocol.StepStatusWaiting {
event = protocol.NotifyWaiting
} else if step.Status != "completed" || step.Outcome == "error" || step.Target == protocol.FailureEnd {
event = "failure"
}
enabled := false
@@ -34,7 +36,7 @@ func (r *runner) notifyStep(id int64, d *protocol.PipelineDetail, workspace stri
}
ctx, cancel := context.WithTimeout(r.ctx, 30*time.Second)
defer cancel()
summary := fmt.Sprintf("%s · run #%d · stage %s · %s (%s)", d.Name, id, step.Stage, event, step.Outcome)
summary := fmt.Sprintf("%s · run #%d · stage %s · %s (%s)", name, id, step.Stage, event, step.Outcome)
if len(summary) > 1800 {
summary = summary[:1800]
for !utf8.ValidString(summary) {
+1 -1
View File
@@ -85,7 +85,7 @@ func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
t.Fatal(err)
}
before := calls.Load()
r.notifyStep(id, d, workspace, policy, step)
r.notifyStep(id, d.Name, workspace, policy, step)
detail, err := store.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
+212 -70
View File
@@ -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)
}
+4 -1
View File
@@ -208,7 +208,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
} else {
response.Pipelines = items
}
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence) {
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence) {
var err error
switch request.Type {
case protocol.GetRunEvidence:
@@ -220,6 +220,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
case protocol.RetryRun:
response.Type = protocol.RunStarted
response.RunDetail, err = runs.retry(request)
case protocol.DecideRun:
response.Type = protocol.Run
response.RunDetail, err = runs.decide(request)
case protocol.SetRunTitle:
response.Type = protocol.Run
response.RunDetail, err = runs.setTitle(request.RunID, request.Title)
+60
View File
@@ -0,0 +1,60 @@
package stage
import (
"context"
"fmt"
"sort"
"strings"
)
const HumanType = "human"
// HumanStage pauses its run until a person chooses one of the stage's outgoing
// options. It has no model, agent, tools or configs: its outcomes are exactly
// its non-error edges (the selectable options) and its required prompt block
// carries the operator instructions. It parses, validates, renders, exports and
// imports like every other registered type. The runner owns the wait and the
// decision path; Run is defensive only and never executes synchronously.
type HumanStage struct{}
func (HumanStage) Validate(def Definition) error {
if EffectiveType(def.Type) != HumanType {
return fmt.Errorf("expected human stage")
}
for name := range def.Blocks {
switch name {
case "configs", "edges", "output", "prompt":
default:
return fmt.Errorf("unexpected block %q for human stage", name)
}
}
for key := range def.Configs {
return fmt.Errorf("unknown human config %q", key)
}
if strings.TrimSpace(def.Blocks["prompt"]) == "" {
return fmt.Errorf("human stage requires a nonempty prompt block with the operator instructions")
}
if len(HumanOptions(def.Edges)) == 0 {
return fmt.Errorf("human stage requires at least one non-error option edge")
}
return nil
}
func (HumanStage) Run(context.Context, Definition, Values) (Result, error) {
return Result{}, fmt.Errorf("human stage is resolved by the runner's decision path, not executed")
}
// HumanOptions is the single definition of a human stage's selectable outcomes:
// its non-error edges in a deterministic order. The mandatory error edge is a
// failure route, not an operator choice, so it is never returned. Store, runner
// and TUI all read this one helper, so the option set cannot drift.
func HumanOptions(edges map[string]string) []string {
options := make([]string, 0, len(edges))
for outcome := range edges {
if outcome != "error" {
options = append(options, outcome)
}
}
sort.Strings(options)
return options
}
+54
View File
@@ -0,0 +1,54 @@
package stage
import (
"context"
"reflect"
"strings"
"testing"
)
func humanDefinition() Definition {
return Definition{
Key: "gate",
Type: HumanType,
Blocks: map[string]string{"prompt": "Review the screenshots and decide."},
Configs: map[string]string{},
Edges: map[string]string{"deploy": "#success", "revise": "worker", "error": "#failure"},
}
}
func TestHumanStageValidateAndRun(t *testing.T) {
if err := (HumanStage{}).Validate(humanDefinition()); err != nil {
t.Fatalf("valid human stage rejected: %v", err)
}
for name, mutate := range map[string]func(*Definition){
"missing prompt": func(def *Definition) { def.Blocks["prompt"] = " " },
"unexpected block": func(def *Definition) { def.Blocks["tools"] = "shell" },
"config key": func(def *Definition) { def.Configs["provider"] = "opencode-go" },
"no non-error edge": func(def *Definition) { def.Edges = map[string]string{"error": "#failure"} },
} {
t.Run(name, func(t *testing.T) {
def := humanDefinition()
mutate(&def)
if err := (HumanStage{}).Validate(def); err == nil {
t.Fatal("accepted an invalid human stage")
}
})
}
if _, err := (HumanStage{}).Run(context.Background(), humanDefinition(), nil); err == nil || !strings.Contains(err.Error(), "decision path") {
t.Fatalf("Run must never execute synchronously, got %v", err)
}
if _, err := DefaultRegistry().Resolve(HumanType); err != nil {
t.Fatalf("human type must be registered: %v", err)
}
}
func TestHumanOptionsAreSortedNonErrorEdges(t *testing.T) {
options := HumanOptions(map[string]string{"revise": "worker", "deploy": "#success", "abort": "#failure", "error": "#failure"})
if !reflect.DeepEqual(options, []string{"abort", "deploy", "revise"}) {
t.Fatalf("HumanOptions = %v", options)
}
if len(HumanOptions(map[string]string{"error": "#failure"})) != 0 {
t.Fatal("an error-only edge set must yield no options")
}
}
+1 -1
View File
@@ -52,7 +52,7 @@ func NewRegistry(types map[string]Stage) *Registry {
}
func DefaultRegistry() *Registry {
return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}})
return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}})
}
func EffectiveType(name string) string {
+4
View File
@@ -13,6 +13,8 @@ func (m Model) activeFooter() string {
switch {
case m.editorChecking:
text = "Refreshing published state · draft retained"
case m.decisionOpen:
text = "↑/↓ choose · Tab feedback · Enter decide · Esc cancel"
case m.actionConfirm != nil || m.mutationCommand != nil:
text = "y confirm · n/Esc cancel · j/k read"
case m.draftDeletingPath != "":
@@ -59,6 +61,8 @@ func (m Model) activeFooter() string {
switch {
case m.editorChecking:
text = "Refreshing · draft retained"
case m.decisionOpen:
text = "Esc cancel · Enter decide · ↑↓ select"
case m.actionConfirm != nil || m.mutationCommand != nil:
text = "Esc cancel · y confirm · j/k read"
case m.draftDeletingPath != "":
+3
View File
@@ -104,6 +104,9 @@ func (m Model) homeLines() []string {
if r.CurrentStage != "" && (r.Status == "running" || r.Status == "queued") {
runs = append(runs, "Working on "+r.CurrentStage)
}
if r.Status == protocol.RunStatusWaiting {
runs = append(runs, "Waiting on a person · stage "+r.CurrentStage)
}
runs = append(runs, "")
}
if len(m.runs) > limit {
+164
View File
@@ -0,0 +1,164 @@
package tui
import (
"fmt"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
)
// lastWaitingStep returns the most recent step a run is waiting on (the last
// waiting step by sequence), or false when no step is waiting. The decision
// overlay and the run summary both read it, so the scan lives once.
func lastWaitingStep(r *protocol.RunDetail) (protocol.RunStep, bool) {
for i := len(r.Steps) - 1; i >= 0; i-- {
if r.Steps[i].Status == protocol.StepStatusWaiting {
return r.Steps[i], true
}
}
return protocol.RunStep{}, false
}
// waitingStage returns the stage the open run is waiting on plus its recorded
// prompt and selectable options. It prefers the self-contained evidence on the
// waiting step and falls back to the pinned graph's edges when a step recorded
// no options.
func (m Model) waitingStage() (string, []string, string) {
if m.runDetail == nil {
return "", nil, ""
}
if step, ok := lastWaitingStep(m.runDetail); ok {
return step.Stage, protocol.WaitingOptions(step.Output), protocol.WaitingPrompt(step.Output)
}
key := m.runDetail.CurrentStage
for _, declared := range m.runDetail.Graph.Stages {
if declared.Key == key {
return key, stage.HumanOptions(declared.Edges), declared.Prompt
}
}
return key, nil, ""
}
func (m Model) openDecision() (tea.Model, tea.Cmd) {
if m.runDetail == nil || m.runDetail.Status != protocol.RunStatusWaiting {
m.runError = "This run is not waiting for a decision."
return m, nil
}
key, options, _ := m.waitingStage()
if len(options) == 0 {
m.runError = "No selectable options recorded for the waiting stage."
return m, nil
}
m.decisionOpen = true
m.decisionRunID = m.runDetail.ID
m.decisionStage = key
m.decisionOptions = options
m.decisionIndex = 0
m.decisionFeedback = newInput()
m.decisionFeedback.Placeholder = "Optional feedback"
m.decisionFeedback.Width = max(1, min(60, m.width-12))
m.decisionFeedbackFocus = false
return m, nil
}
func (m *Model) closeDecision() {
m.decisionOpen = false
m.decisionRunID = 0
m.decisionStage = ""
m.decisionOptions = nil
m.decisionIndex = 0
m.decisionFeedback = newInput()
m.decisionFeedbackFocus = false
}
func (m Model) updateDecision(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "esc":
m.closeDecision()
return m, nil
case "tab":
m.decisionFeedbackFocus = !m.decisionFeedbackFocus
if m.decisionFeedbackFocus {
return m, m.decisionFeedback.Focus()
}
m.decisionFeedback.Blur()
return m, nil
case "f":
if !m.decisionFeedbackFocus {
m.decisionFeedbackFocus = true
return m, m.decisionFeedback.Focus()
}
case "up", "k":
if !m.decisionFeedbackFocus {
m.decisionIndex = max(0, m.decisionIndex-1)
return m, nil
}
case "down", "j":
if !m.decisionFeedbackFocus {
m.decisionIndex = min(m.decisionIndex+1, max(0, len(m.decisionOptions)-1))
return m, nil
}
case "enter":
if len(m.decisionOptions) == 0 {
return m, nil
}
option := m.decisionOptions[min(m.decisionIndex, len(m.decisionOptions)-1)]
feedback := strings.TrimSpace(m.decisionFeedback.Value())
request := protocol.Message{Type: protocol.DecideRun, RunID: m.decisionRunID, Stage: m.decisionStage, Option: option, Feedback: feedback}
m.closeDecision()
return m.runRequest(request)
}
if m.decisionFeedbackFocus {
var cmd tea.Cmd
m.decisionFeedback, cmd = m.decisionFeedback.Update(msg)
return m, cmd
}
return m, nil
}
func (m Model) decisionView(height int) string {
title := fmt.Sprintf("Decide %s · run #%d", m.decisionStage, m.decisionRunID)
intro := "Choose where the run goes next. The choice and feedback are recorded as the stage's evidence."
if m.width < 65 {
intro = "Choose where the run goes next."
}
// Size the option window to the panel body so every shown paragraph fits and
// the selected option is never clipped: each option costs a line plus a
// separator, and the feedback line always fits. The count of shown options
// goes in the controls, so a windowed list still says more exist.
dialogWidth := min(m.width, 76)
inner := max(1, dialogWidth-4)
introLines := len(strings.Split(ansi.Wrap(intro, inner, ""), "\n"))
capacity := max(1, (height-4-introLines)/2-1)
count := len(m.decisionOptions)
start, end := selectionWindow(count, m.decisionIndex, capacity)
paragraphs := []string{intro}
for i := start; i < end; i++ {
marker := " "
if i == m.decisionIndex {
marker = " › "
}
paragraphs = append(paragraphs, marker+m.decisionOptions[i])
}
paragraphs = append(paragraphs, "Feedback: "+m.decisionFeedback.View())
controls := "↑/↓ choose · Tab feedback · Enter decide · Esc cancel"
if end-start < count {
controls += fmt.Sprintf(" · %d/%d", end-start, count)
}
if m.width < 65 {
controls = "↑↓ select · Enter decide · Esc"
if end-start < count {
controls += fmt.Sprintf(" · %d/%d", end-start, count)
}
}
if m.decisionFeedbackFocus {
controls = "type feedback · Tab options · Enter decide · Esc cancel"
if m.width < 65 {
controls = "type feedback · Enter decide · Esc"
}
}
return wrappedDialog(m.width, height, 72, title, paragraphs, controls, 0)
}
+137
View File
@@ -0,0 +1,137 @@
package tui
import (
"context"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
)
func decisionModel() Model {
m := New(context.Background(), "")
m.width = 100
m.height = 30
m.runOpen = true
m.keys.runs = true
m.requestedRunID = 8
m.runDetail = &protocol.RunDetail{
RunSummary: protocol.RunSummary{ID: 8, Name: "release", Version: 1, Status: protocol.RunStatusWaiting, CurrentStage: "gate"},
Steps: []protocol.RunStep{{
Sequence: 1, Stage: "gate", Status: protocol.StepStatusWaiting,
Output: protocol.NewWaitingEvidence("Approve the release?", []string{"go", "halt"}),
}},
}
return m
}
func TestWaitingRunRendersPromptAndOptions(t *testing.T) {
m := decisionModel()
text := ansi.Strip(strings.Join(m.runSectionLines(m.runDetailWidth()), "\n"))
for _, want := range []string{"Waiting for a person · stage gate", "Approve the release?", "Options: go, halt"} {
if !strings.Contains(text, want) {
t.Fatalf("waiting run view missing %q:\n%s", want, text)
}
}
detail := ansi.Strip(m.runsDetailsView(24))
if !strings.Contains(detail, "Waiting for a person") {
t.Fatalf("run detail omitted the waiting banner:\n%s", detail)
}
}
func TestDecisionOverlaySelectsAndEmits(t *testing.T) {
m := decisionModel()
updated, _ := m.openDecision()
m = updated.(Model)
if !m.decisionOpen || m.decisionStage != "gate" || strings.Join(m.decisionOptions, ",") != "go,halt" {
t.Fatalf("overlay did not open with the recorded options: %+v", m.decisionOptions)
}
if view := ansi.Strip(m.decisionView(24)); !strings.Contains(view, "Decide gate") || !strings.Contains(view, "halt") {
t.Fatalf("overlay view missing the choice:\n%s", view)
}
updated, _ = m.updateDecision(tea.KeyMsg{Type: tea.KeyDown})
m = updated.(Model)
if m.decisionIndex != 1 {
t.Fatalf("down did not move the selection: %d", m.decisionIndex)
}
updated, _ = m.updateDecision(tea.KeyMsg{Type: tea.KeyTab})
m = updated.(Model)
if !m.decisionFeedbackFocus {
t.Fatal("Tab did not focus the feedback field")
}
updated, _ = m.updateDecision(tea.KeyMsg{Type: tea.KeyEsc})
m = updated.(Model)
if m.decisionOpen {
t.Fatal("Esc did not close the overlay")
}
// Enter emits a DecideRun request; with no connection the send path records
// the attempt and the overlay closes.
updated, _ = m.openDecision()
m = updated.(Model)
m.decisionFeedback.SetValue("looks good")
before := len(m.lines)
updated, _ = m.updateDecision(tea.KeyMsg{Type: tea.KeyEnter})
m = updated.(Model)
if m.decisionOpen {
t.Fatal("Enter did not close the overlay")
}
if len(m.lines) == before {
t.Fatal("Enter did not attempt to send the decision")
}
if !strings.Contains(strings.Join(m.lines, "\n"), "not connected") {
t.Fatalf("decision path did not run: %v", m.lines)
}
}
// TestDecisionOverlayKeepsSelectionVisibleAtNarrowViewport proves the overlay
// windows its option list like the palette: at the smallest reviewed viewport
// the selected option stays visible with its marker and a count says more exist.
func TestDecisionOverlayKeepsSelectionVisibleAtNarrowViewport(t *testing.T) {
m := decisionModel()
m.width = 40
m.height = 16
m.runDetail.Steps[0].Output = protocol.NewWaitingEvidence("Approve the release?", []string{"abort", "deploy", "revise"})
updated, _ := m.openDecision()
m = updated.(Model)
// Move onto the option a fixed, unwindowed list would clip at this viewport.
updated, _ = m.updateDecision(tea.KeyMsg{Type: tea.KeyDown})
m = updated.(Model)
updated, _ = m.updateDecision(tea.KeyMsg{Type: tea.KeyDown})
m = updated.(Model)
view := ansi.Strip(m.View())
if !strings.Contains(view, "› revise") {
t.Fatalf("selected option is not visible with a marker at 40x16:\n%s", view)
}
if !strings.Contains(view, "2/3") {
t.Fatalf("option count affordance missing at 40x16:\n%s", view)
}
if strings.Contains(view, "Enter d…") {
t.Fatalf("controls are still truncated at 40x16:\n%s", view)
}
}
// TestDecidedHumanStepRendersNeutralFeedback locks the fix for the review
// finding: a completed decision shows its feedback as a normal output field,
// never as the error-style "Stopped:" line reserved for real stops.
func TestDecidedHumanStepRendersNeutralFeedback(t *testing.T) {
m := decisionModel()
m.runDetail.Status = "succeeded"
output := map[string]any{"option": "go", "feedback": "looks good"}
m.runDetail.Steps[0] = protocol.RunStep{
Sequence: 1, Stage: "gate", Status: "completed", Outcome: "go", Target: "worker",
Output: output,
Verdict: protocol.NewStageVerdict("go", "worker", output, nil, "", ""),
}
m.runStepIndex = 1
view := ansi.Strip(strings.Join(m.runSectionLines(m.runDetailWidth()), "\n"))
if strings.Contains(view, "Stopped:") {
t.Fatalf("a deliberate decision must not render as a stop:\n%s", view)
}
if !strings.Contains(view, "looks good") {
t.Fatalf("decision feedback is not visible:\n%s", view)
}
}
+13
View File
@@ -185,6 +185,13 @@ type Model struct {
runGraphFocus bool
runGraphTop int
runGraphPan int
decisionOpen bool
decisionRunID int64
decisionStage string
decisionOptions []string
decisionIndex int
decisionFeedback textinput.Model
decisionFeedbackFocus bool
editorOpen bool
editorInput textinput.Model
editorIndex int
@@ -582,6 +589,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if m.runForm != 0 {
return m.updateRunForm(msg)
}
if m.decisionOpen {
return m.updateDecision(msg)
}
if m.runOpen && (msg.String() != ":" || m.runSearchOpen) {
return m.updateRuns(msg)
}
@@ -784,6 +794,9 @@ func (m Model) View() string {
if m.actionConfirm != nil {
content = m.actionConfirmView(bodyHeight)
}
if m.decisionOpen {
content = m.decisionView(bodyHeight)
}
if m.mutationCommand != nil {
paragraphs := []string{"This opens a new session/editor and may modify a retained draft.", "Published definitions and previous run history are unchanged."}
if strings.Contains(m.mutationTitle, "debugging") {
+31
View File
@@ -3,6 +3,7 @@ package tui
import (
"fmt"
"maps"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/charmbracelet/lipgloss"
@@ -23,6 +24,12 @@ func resultLabel(r protocol.RunSummary) string {
if preview != "" {
return "Latest output: " + preview
}
if r.Status == protocol.RunStatusWaiting {
if r.CurrentStage != "" {
return "Waiting for a person · stage " + r.CurrentStage
}
return "Waiting for a person"
}
if r.Status == "running" || r.Status == "queued" {
return "In progress · awaiting stage output"
}
@@ -60,6 +67,7 @@ func runResultLines(r *protocol.RunDetail) []string {
if r.Diagnostic != "" {
lines = append(lines, "Stopped: "+ansi.Strip(r.Diagnostic))
}
lines = append(lines, waitingLines(r)...)
if r.Status == "succeeded" {
if preview := protocol.OutputPreview(r.Output); preview != "" {
lines = append(lines, "Result: "+ansi.Strip(preview))
@@ -96,6 +104,26 @@ func runResultLines(r *protocol.RunDetail) []string {
return lines
}
// waitingLines renders a run waiting on a human stage: the banner, the operator
// instructions recorded with the wait, and the selectable options, so the choice
// is visible without opening the stage view.
func waitingLines(r *protocol.RunDetail) []string {
if r.Status != protocol.RunStatusWaiting {
return nil
}
lines := []string{"⏸ Waiting for a person · stage " + r.CurrentStage}
if step, ok := lastWaitingStep(r); ok {
if prompt := strings.TrimSpace(protocol.WaitingPrompt(step.Output)); prompt != "" {
lines = append(lines, strings.Split(ansi.Strip(prompt), "\n")...)
}
if options := protocol.WaitingOptions(step.Output); len(options) > 0 {
lines = append(lines, "Options: "+strings.Join(options, ", "))
}
lines = append(lines, fmt.Sprintf("Decide: pipelines decide %d --option KEY [--feedback TEXT]", r.ID))
}
return lines
}
func completedWorkLines(r *protocol.RunDetail) []string {
var lines []string
for _, s := range r.Steps {
@@ -117,6 +145,9 @@ func completedWorkLines(r *protocol.RunDetail) []string {
}
func runOutputDocument(r *protocol.RunDetail, width int) []string {
if r.Status == protocol.RunStatusWaiting {
return waitingLines(r)
}
var notice []string
if r.Diagnostic != "" {
notice = append(notice, lipgloss.NewStyle().Foreground(themeError).Render("Stopped: "+ansi.Strip(r.Diagnostic)), "")
+11 -1
View File
@@ -101,6 +101,7 @@ func (m *Model) closeRuns() {
m.runGraphFocus = false
m.runGraphTop = 0
m.runGraphPan = 0
m.closeDecision()
}
func (m Model) visibleRuns() []protocol.RunSummary {
@@ -265,6 +266,8 @@ func runStatus(status string) string {
color = themeError
case "running", "queued":
color = themeAccent
case protocol.RunStatusWaiting:
color = themeAccent
}
return lipgloss.NewStyle().Foreground(color).Render(status)
}
@@ -640,6 +643,9 @@ func (m Model) runActions() string {
if m.runDetail != nil {
text += " · a evidence"
}
if m.runDetail != nil && m.runDetail.Status == protocol.RunStatusWaiting {
text += " · c decide"
}
if m.selectedFailedRun() > 0 {
text += " · r retry failed"
}
@@ -718,7 +724,11 @@ func (m Model) runsDetailsView(height int) string {
lines := m.runSectionLines(m.runDetailWidth())
page := max(0, innerHeight-5)
top := max(0, min(m.runTop, max(0, len(lines)-page)))
footer := bar("o result · d diff · s progress · i input · t evidence · m details", fmt.Sprintf("%d–%d / %d", min(top+1, len(lines)), min(top+page, len(lines)), len(lines)), max(1, m.width-4), false)
footerHint := "o result · d diff · s progress · i input · t evidence · m details"
if r.Status == protocol.RunStatusWaiting {
footerHint += " · c decide"
}
footer := bar(footerHint, fmt.Sprintf("%d–%d / %d", min(top+1, len(lines)), min(top+page, len(lines)), len(lines)), max(1, m.width-4), false)
label := m.runSelectionLabel()
if m.runStepIndex > 0 && m.runStepIndex <= len(r.Steps) {
step := r.Steps[m.runStepIndex-1]
+3
View File
@@ -27,6 +27,9 @@ func (m Model) progress(status string) string {
color = themeError
case "canceled":
marker = "−"
case protocol.RunStatusWaiting:
marker = "⏸"
color = themeAccent
}
return lipgloss.NewStyle().Foreground(color).Render(marker + " " + status)
}
+7
View File
@@ -282,6 +282,9 @@ func (m Model) updateRuns(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
if m.runGraphFocus {
switch msg.String() {
case "c":
if m.runDetail != nil && m.runDetail.Status == protocol.RunStatusWaiting {
return m.openDecision()
}
m.runGraphTop, m.runGraphPan = m.runGraphFollow()
return m, nil
case "j", "down":
@@ -418,6 +421,10 @@ func (m Model) updateRuns(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
if m.runDetail != nil {
return m.runRequest(protocol.Message{Type: protocol.CancelRun, RunID: m.runDetail.ID})
}
case "c":
if m.runDetail != nil && m.runDetail.Status == protocol.RunStatusWaiting {
return m.openDecision()
}
}
if m.runDetail != nil {
m.runTop = max(0, min(m.runTop, max(0, len(m.runSectionLines(m.runDetailWidth()))-m.runPageSize())))