diff --git a/api/openapi.yaml b/api/openapi.yaml index dc1024948..3e50a028e 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -51,6 +51,23 @@ components: - token - options type: object + ApprovalsStepView: + additionalProperties: false + properties: + action: + type: string + decision_id: + type: string + level: + type: string + target: + type: string + required: + - decision_id + - action + - target + - level + type: object ApprovalsView: additionalProperties: false properties: @@ -89,6 +106,12 @@ components: step_deadline: format: date-time type: string + steps: + items: + $ref: "#/components/schemas/ApprovalsStepView" + type: + - array + - "null" summary: type: string target: @@ -3994,6 +4017,8 @@ components: $ref: "#/components/schemas/RunsEffect" rejudged: $ref: "#/components/schemas/JudgementDecision" + stop: + type: string required: - decision type: object diff --git a/internal/platform/pg/migrations/00017_approvals_actions.sql b/internal/platform/pg/migrations/00017_approvals_actions.sql new file mode 100644 index 000000000..5cfd19fdd --- /dev/null +++ b/internal/platform/pg/migrations/00017_approvals_actions.sql @@ -0,0 +1,9 @@ +-- +goose Up +-- One approval can cover a sequence of actions, approved in one act. The +-- request's own action columns describe the first action; actions lists all of +-- them in the order they run, each with the decision and digest that bind its +-- approval. +ALTER TABLE approvals.requests ADD COLUMN actions jsonb NOT NULL DEFAULT '[]'; + +-- +goose Down +ALTER TABLE approvals.requests DROP COLUMN actions; diff --git a/modules/approvals/approvals.go b/modules/approvals/approvals.go index 13072c8b1..20329e384 100644 --- a/modules/approvals/approvals.go +++ b/modules/approvals/approvals.go @@ -65,15 +65,25 @@ const ( KindAutonomy = "autonomy" ) -// Request tracks approval of an action or a proposed increase in autonomy. +// Step is one action a request covers, as the approver is shown it: the +// binding that names it, and what it does. +type Step = store.Step + +// Request tracks approval of an action, a sequence of actions, or a proposed +// increase in autonomy. type Request struct { ID uuid.UUID Kind string RunID uuid.UUID // Key identifies the run wait that receives the response. - Key string - Decision judgement.Decision - DecisionID uuid.UUID + Key string + Decision judgement.Decision + DecisionID uuid.UUID + // Digest is the digest of the action the request was raised for. + Digest string + // Actions are the actions the request covers, in the order they run. A + // request for one action lists one; an autonomy proposal lists none. + Actions []Step ActionTypeID uuid.UUID RequestedAt time.Time Connector string @@ -120,10 +130,35 @@ type Answer struct { At time.Time `json:"at"` } -// Approval binds the approver's identity and response time to the decision ID -// and action digest. +// Approval binds the approver's identity and response time to the decision IDs +// and action digests the request covers. func (a Answer) Approval(d judgement.Decision) judgement.Approval { - return judgement.Approval{DecisionID: d.ID, Digest: d.Action.Digest, By: a.By, ByID: a.ByID, At: a.At} + return judgement.Approval{Bindings: []judgement.Binding{judgement.Bind(d)}, By: a.By, ByID: a.ByID, At: a.At} +} + +// Approval is the approval a's answer gives for the actions the request +// covers, in the order the approver saw them. +func (r Request) Approval(a Answer) judgement.Approval { + bindings := make([]judgement.Binding, len(r.Actions)) + for i, s := range r.Actions { + bindings[i] = judgement.Binding{DecisionID: s.DecisionID, Digest: s.Digest} + } + return judgement.Approval{Bindings: bindings, By: a.By, ByID: a.ByID, At: a.At} +} + +// Covers reports whether the request was raised for d's action. +func (r Request) Covers(d judgement.Decision) bool { + if len(r.Actions) == 0 { + // A request recorded before requests listed their actions names on its + // own the action it was raised for. + return r.DecisionID == d.ID && r.Digest == d.Action.Digest + } + for _, s := range r.Actions { + if s.DecisionID == d.ID && s.Digest == d.Action.Digest { + return true + } + } + return false } // View is the API representation of an approval request. @@ -143,6 +178,9 @@ type View struct { // DecisionID identifies the judgement decision or, for an autonomy request, the autonomy proposal. DecisionID uuid.UUID `json:"decision_id"` RequestedAt time.Time `json:"requested_at"` + // Steps are the actions the request covers, in the order they run. A + // request for one action lists one. + Steps []StepView `json:"steps,omitzero"` // AnsweredBy is the answering account's display name. AnsweredBy string `json:"answered_by,omitzero"` // AnsweredByID is the answering account's identity ID. @@ -151,13 +189,25 @@ type View struct { AnsweredAt time.Time `json:"answered_at,omitzero"` } +// StepView is one action of an approval request, as the API shows it. +type StepView struct { + DecisionID uuid.UUID `json:"decision_id"` + Action string `json:"action"` + Target string `json:"target"` + Level string `json:"level"` +} + // View converts a request to its API representation. func (r Request) View() View { + steps := make([]StepView, len(r.Actions)) + for i, s := range r.Actions { + steps[i] = StepView{DecisionID: s.DecisionID, Action: s.Action, Target: s.Target, Level: s.Level} + } return View{ ID: r.ID, Kind: r.Kind, RunID: r.RunID, Action: r.Connector + " " + r.Action, Target: r.TargetKind + ":" + r.TargetID, Level: r.Level, Summary: r.Summary, State: r.State, Deadline: r.Deadline, Step: r.Step, StepDeadline: r.StepDeadline, - DecisionID: r.DecisionID, RequestedAt: r.RequestedAt, + DecisionID: r.DecisionID, RequestedAt: r.RequestedAt, Steps: steps, AnsweredBy: r.AnsweredBy, AnsweredByID: r.AnsweredByID, AnsweredVia: r.AnsweredVia, AnsweredAt: r.AnsweredAt, } } @@ -223,17 +273,36 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake } // Ask reuses the request for the same run and key so retries do not create -// duplicate requests. It uses a change-request connector when judgement -// requires a change request and a connector is configured. Otherwise, it -// sends the request to the approval channels with the first step's deadline. -func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgement.Decision, path []governance.PathStep) (Request, error) { +// duplicate requests. It covers every action in ds, which one person approves +// in one act. It uses a change-request connector when judgement requires a +// change request and a connector is configured. Otherwise, it sends the request +// to the approval channels with the first step's deadline. +func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, ds []judgement.Decision, path []governance.PathStep) (Request, error) { if len(path) == 0 { return Request{}, ErrNoPath } - if d.ActionTypeID == uuid.Nil { + if len(ds) == 0 { + return Request{}, errors.New("approval request needs an action") + } + first := ds[0] + if first.ActionTypeID == uuid.Nil { return Request{}, errors.New("approval request needs an action type id") } - changeRequest := d.ChangeRequest && m.changes != nil + actions := make([]Step, len(ds)) + // The request needs the authority of the strictest action it covers, and a + // passkey for any action that can't be undone. + level := first.Level + var changeRequest, passkey bool + for i, d := range ds { + level = max(level, d.Level) + actions[i] = Step{ + DecisionID: d.ID, Digest: d.Action.Digest, Level: d.Level.String(), + Action: d.Action.Connector + " " + d.Action.Name, Target: d.Action.Target.Kind + ":" + d.Action.Target.ID, + } + changeRequest = changeRequest || d.ChangeRequest + passkey = passkey || irreversible(d.Action) + } + changeRequest = changeRequest && m.changes != nil now := m.now().UTC() var total time.Duration for _, st := range path { @@ -241,18 +310,18 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgeme } row, err := m.store.Put(ctx, store.Request{ ID: uuid.New(), OrgID: m.orgID, RunID: runID, Key: key, - DecisionID: d.ID, ActionTypeID: d.ActionTypeID, Kind: KindAction, Digest: d.Action.Digest, Level: d.Level.String(), - Connector: d.Action.Connector, Action: d.Action.Name, - InstallationID: d.Action.Installation.ID, InstallationScope: d.Action.Installation.Scope, - TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID, Irreversible: irreversible(d.Action), - Summary: Summary(d), State: StatePending, Deadline: now.Add(total), + DecisionID: first.ID, ActionTypeID: first.ActionTypeID, Kind: KindAction, Digest: first.Action.Digest, Level: level.String(), + Connector: first.Action.Connector, Action: first.Action.Name, + InstallationID: first.Action.Installation.ID, InstallationScope: first.Action.Installation.Scope, + TargetKind: first.Action.Target.Kind, TargetID: first.Action.Target.ID, Actions: actions, Irreversible: passkey, + Summary: SummaryOf(ds), State: StatePending, Deadline: now.Add(total), StepDeadline: sql.NullTime{Time: now.Add(path[0].Deadline()), Valid: true}, ChangeRequest: changeRequest, }) if err != nil { return Request{}, err } - r := requestOf(row, d) + r := requestOf(row, first) if row.State != StatePending { return r, nil } @@ -264,7 +333,7 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgeme } if err := m.tell.Ask(ctx, deliveries.ApprovalRequest{ RunID: r.RunID, RequestID: r.ID, Key: r.Key + ":ask", - Title: "Approval needed: " + d.Action.Connector + " " + d.Action.Name, + Title: approvalTitle(ds), Body: r.Summary, ExpiresAt: r.StepDeadline, }); err != nil { return Request{}, fmt.Errorf("send approval request: %w", err) @@ -272,6 +341,25 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgeme return r, nil } +// named is how a request's actions are named in a message: the action, or how +// many were approved together. +func named(r store.Request) string { + if len(r.Actions) > 1 { + return fmt.Sprintf("%d actions", len(r.Actions)) + } + return r.Connector + " " + r.Action +} + +// approvalTitle names what a request asks about: the action, or how many are +// approved together. +func approvalTitle(ds []judgement.Decision) string { + d := ds[0] + if len(ds) > 1 { + return fmt.Sprintf("Approval needed: %d actions", len(ds)) + } + return "Approval needed: " + d.Action.Connector + " " + d.Action.Name +} + func (m *Module) answerAs(ctx context.Context, id uuid.UUID, who Answerer, via string, approved bool) (Request, error) { now := m.now().UTC() if _, err := m.pending(ctx, id, now); err != nil { @@ -510,8 +598,8 @@ func (m *Module) Expire(ctx context.Context, id uuid.UUID) error { // Use a stable key so retrying the expiry does not duplicate the notification. return m.tell.Notify(ctx, deliveries.Notification{ RunID: row.RunID, Key: row.Key + ":expired", - Title: "Approval timed out: " + row.Connector + " " + row.Action, - Body: "No one responded before the final escalation deadline, so " + row.Connector + " " + row.Action + + Title: "Approval timed out: " + named(row), + Body: "No one responded before the final escalation deadline, so " + named(row) + " did not run." + withdrawn + " " + row.Summary, }) } @@ -608,6 +696,24 @@ func answerText(a Answer) string { return fmt.Sprintf("%s by %s via %s.", verb, a.By, a.Via) } +// SummaryOf shows the approver every action a request covers, in the order +// they run, and why each one requires approval. +func SummaryOf(ds []judgement.Decision) string { + if len(ds) == 1 { + return Summary(ds[0]) + } + var s strings.Builder + fmt.Fprintf(&s, "%d actions, approved together, in this order:", len(ds)) + for i, d := range ds { + lines := strings.Split(Summary(d), "\n") + fmt.Fprintf(&s, "\n%d. %s", i+1, lines[0]) + for _, line := range lines[1:] { + s.WriteString("\n " + line) + } + } + return s.String() +} + // Summary shows the approver the action, its target and why it requires approval. func Summary(d judgement.Decision) string { s := fmt.Sprintf("%s: %s on %s %q.", d.Action.Connector, d.Action.Name, d.Action.Target.Kind, d.Action.Target.ID) @@ -657,9 +763,9 @@ func inputLine(input jsontext.Value) string { func requestOf(row store.Request, d judgement.Decision) Request { r := Request{ - ID: row.ID, Kind: row.Kind, RunID: row.RunID, Key: row.Key, Decision: d, DecisionID: row.DecisionID, ActionTypeID: row.ActionTypeID, RequestedAt: row.CreatedAt, + ID: row.ID, Kind: row.Kind, RunID: row.RunID, Key: row.Key, Decision: d, DecisionID: row.DecisionID, Digest: row.Digest, ActionTypeID: row.ActionTypeID, RequestedAt: row.CreatedAt, Connector: row.Connector, Action: row.Action, TargetKind: row.TargetKind, TargetID: row.TargetID, - Level: row.Level, Irreversible: row.Irreversible, Summary: row.Summary, State: row.State, Deadline: row.Deadline, + Level: row.Level, Actions: row.Actions, Irreversible: row.Irreversible, Summary: row.Summary, State: row.State, Deadline: row.Deadline, Step: row.Step, ChangeRequest: row.ChangeRequest, } if row.StepDeadline.Valid { diff --git a/modules/approvals/approvals_test.go b/modules/approvals/approvals_test.go index 700161ada..509bdc35e 100644 --- a/modules/approvals/approvals_test.go +++ b/modules/approvals/approvals_test.go @@ -197,3 +197,31 @@ func TestAnswerersWithTheSameNameRecordDifferentIDs(t *testing.T) { }) } } + +// TestCoversStillBindsARequestRecordedBeforeItListedItsActions guards a request +// made before requests carried the actions they cover: the decision and digest +// it records on its own still bind it to that action and no other, so an +// existing run keeps its approval. +func TestCoversStillBindsARequestRecordedBeforeItListedItsActions(t *testing.T) { + decision := func(id uuid.UUID, digest string) judgement.Decision { + return judgement.Decision{ID: id, Action: judgement.Action{Digest: digest}} + } + approved := decision(uuid.New(), "abc") + request := Request{DecisionID: approved.ID, Digest: "abc"} + tests := []struct { + name string + d judgement.Decision + want bool + }{ + {name: "the action it approved is covered", d: approved, want: true}, + {name: "the same action with a new digest is not covered", d: decision(approved.ID, "def")}, + {name: "another action is not covered", d: decision(uuid.New(), "abc")}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := request.Covers(tt.d); got != tt.want { + t.Fatalf("Covers = %t, want %t", got, tt.want) + } + }) + } +} diff --git a/modules/approvals/escalation.go b/modules/approvals/escalation.go index 2a3e766e6..b9e4e4b2c 100644 --- a/modules/approvals/escalation.go +++ b/modules/approvals/escalation.go @@ -43,7 +43,7 @@ func (m *Module) Escalate(ctx context.Context, id uuid.UUID, n int, to governanc // retrying with the same key won't duplicate the notice. if err := m.tell.Notify(ctx, deliveries.Notification{ RunID: row.RunID, Key: row.Key + ":escalated:" + strconv.Itoa(n), - Title: "Approval escalated: " + row.Connector + " " + row.Action, + Title: "Approval escalated: " + named(row), Body: "No one responded before the previous deadline. Next approver: " + who + ". Response deadline: " + until.Format("2006-01-02 15:04 UTC") + ". " + row.Summary, }); err != nil { return err diff --git a/modules/approvals/internal/store/store.go b/modules/approvals/internal/store/store.go index 563ab7528..307bb5dab 100644 --- a/modules/approvals/internal/store/store.go +++ b/modules/approvals/internal/store/store.go @@ -4,6 +4,7 @@ package store import ( "context" "database/sql" + json "encoding/json/v2" "errors" "fmt" "time" @@ -12,6 +13,37 @@ import ( "github.com/jmoiron/sqlx" ) +// Step is one action a request covers: the decision and digest that bind it, +// and what the action does, so the approver can be shown the sequence without +// loading the decisions. +type Step struct { + DecisionID uuid.UUID `json:"decision_id"` + Digest string `json:"digest"` + Action string `json:"action"` + Target string `json:"target"` + Level string `json:"level"` +} + +// Steps is the list of actions a request covers, stored as JSON. +type Steps []Step + +// Scan reads the stored list. +func (s *Steps) Scan(src any) error { + var raw []byte + switch v := src.(type) { + case nil: + *s = nil + return nil + case []byte: + raw = v + case string: + raw = []byte(v) + default: + return fmt.Errorf("read request actions: %T", src) + } + return json.Unmarshal(raw, s) +} + // Request is the stored record of an action or autonomy proposal approval request. type Request struct { ID uuid.UUID `db:"id"` @@ -36,6 +68,9 @@ type Request struct { TargetKind string `db:"target_kind"` TargetID string `db:"target_id"` Level string `db:"level"` + // Actions are the actions the request covers, in the order they run. A + // request for one action lists one. + Actions Steps `db:"actions"` // Irreversible is whether approving needs a fresh passkey assertion. Irreversible bool `db:"irreversible"` Summary string `db:"summary"` @@ -66,21 +101,25 @@ type Store struct { func New(db *sqlx.DB) *Store { return &Store{db: db} } const requestColumns = `id, org_id, run_id, key, decision_id, action_type_id, kind, digest, connector, installation_id, installation_scope, action, target_kind, - target_id, level, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_by_id, answered_via, + target_id, level, actions, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_by_id, answered_via, step, step_deadline, change_request, counted, discarded_because` // Put inserts r or returns the existing request for the same organisation, // run and key. func (s *Store) Put(ctx context.Context, r Request) (Request, error) { var out Request - err := s.db.GetContext(ctx, &out, ` + actions, err := json.Marshal(r.Actions) + if err != nil { + return Request{}, fmt.Errorf("encode request actions: %w", err) + } + err = s.db.GetContext(ctx, &out, ` INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, action_type_id, kind, digest, connector, installation_id, - installation_scope, action, target_kind, target_id, level, irreversible, summary, state, deadline, step_deadline, change_request) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21) + installation_scope, action, target_kind, target_id, level, actions, irreversible, summary, state, deadline, step_deadline, change_request) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16::jsonb, $17, $18, $19, $20, $21, $22) ON CONFLICT (org_id, run_id, key) DO NOTHING RETURNING `+requestColumns, r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.ActionTypeID, r.Kind, r.Digest, r.Connector, r.InstallationID, r.InstallationScope, r.Action, r.TargetKind, - r.TargetID, r.Level, r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.ChangeRequest) + r.TargetID, r.Level, string(actions), r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.ChangeRequest) if errors.Is(err, sql.ErrNoRows) { return s.Get(ctx, r.OrgID, r.RunID, r.Key) } diff --git a/modules/chat/chat.go b/modules/chat/chat.go index 9d208d055..0238cf339 100644 --- a/modules/chat/chat.go +++ b/modules/chat/chat.go @@ -53,7 +53,7 @@ type Judge interface { // Approver puts actions judgement held to people, escalates them along the // path and expires them after its last deadline. type Approver interface { - Ask(ctx context.Context, runID uuid.UUID, key string, d judgement.Decision, path []governance.PathStep) (approvals.Request, error) + Ask(ctx context.Context, runID uuid.UUID, key string, ds []judgement.Decision, path []governance.PathStep) (approvals.Request, error) Escalate(ctx context.Context, id uuid.UUID, step int, to governance.PathStep) error Expire(ctx context.Context, id uuid.UUID) error Accept(ctx context.Context, id uuid.UUID) error diff --git a/modules/chat/taint_test.go b/modules/chat/taint_test.go index d89b41bc3..6e87a47c4 100644 --- a/modules/chat/taint_test.go +++ b/modules/chat/taint_test.go @@ -58,7 +58,7 @@ func (j *taintJudge) Execute(_ context.Context, d judgement.Decision, _ jsontext // fakeApprover records the asks and answers them with a ready request. type fakeApprover struct{ Approver } -func (fakeApprover) Ask(_ context.Context, _ uuid.UUID, key string, _ judgement.Decision, _ []governance.PathStep) (approvals.Request, error) { +func (fakeApprover) Ask(_ context.Context, _ uuid.UUID, key string, _ []judgement.Decision, _ []governance.PathStep) (approvals.Request, error) { return approvals.Request{ID: uuid.New(), Key: key, Summary: "approve this", StepDeadline: time.Now().Add(time.Hour), Deadline: time.Now().Add(time.Hour)}, nil } diff --git a/modules/chat/tools.go b/modules/chat/tools.go index aed8117ba..12f137567 100644 --- a/modules/chat/tools.go +++ b/modules/chat/tools.go @@ -297,7 +297,7 @@ func (m *Module) hold(ctx context.Context, d Deps, t store.Turn, decision judgem return "", fmt.Errorf("hold %s %s: %w", decision.Action.Connector, decision.Action.Name, err) } key := waitKey(decision.Key) - request, err := d.Approver.Ask(ctx, t.ID, key, decision, path) + request, err := d.Approver.Ask(ctx, t.ID, key, []judgement.Decision{decision}, path) if err != nil { return "", fmt.Errorf("ask for approval: %w", err) } diff --git a/modules/judgement/chat_test.go b/modules/judgement/chat_test.go index 2879fca79..ac71ce65a 100644 --- a/modules/judgement/chat_test.go +++ b/modules/judgement/chat_test.go @@ -69,7 +69,7 @@ func TestChatProhibitsPrivilegedActions(t *testing.T) { exec := &Module{tools: oneTool{countingTool{&invoked}}} for _, level := range []Level{ActQuietly, ProposeAndWait} { held := Decision{ID: uuid.New(), Level: level, Workflow: tt.workflow, Action: a} - approval := Approval{DecisionID: held.ID, Digest: a.Digest, By: "owner", At: time.Now().UTC()} + approval := Approval{Bindings: []Binding{{DecisionID: held.ID, Digest: a.Digest}}, By: "owner", At: time.Now().UTC()} _, errRun := exec.Execute(t.Context(), held, a.Input, "k") _, errApproved := exec.ExecuteApproved(t.Context(), held, approval, a.Input, "k") if tt.wantRefusal && (!errors.Is(errRun, ErrRefused) || !errors.Is(errApproved, ErrRefused)) { diff --git a/modules/judgement/judgement.go b/modules/judgement/judgement.go index 51fb64453..265b69a4d 100644 --- a/modules/judgement/judgement.go +++ b/modules/judgement/judgement.go @@ -455,13 +455,26 @@ func (m *Module) keepCalls(ctx context.Context, id uuid.UUID, calls []connectors } } -// Approval is a person's permission to run one decision's exact action. It -// names the decision and the action's digest, so it covers that action and -// nothing else, and it says who gave it and when. -type Approval struct { +// Binding names one judged action: the decision, and the digest of the action +// it judged. +type Binding struct { DecisionID uuid.UUID `json:"decision_id"` Digest string `json:"digest"` - By string `json:"by"` +} + +// Bind is the binding of d's action. +func Bind(d Decision) Binding { + return Binding{DecisionID: d.ID, Digest: d.Action.Digest} +} + +// Approval is a person's permission to run judged actions given in one act: an +// action, or a sequence approved together. It names each decision and its +// action's digest, so it covers those actions and nothing else, and it says +// who gave it and when. +type Approval struct { + // Bindings are the actions the person approved, in the order they run. + Bindings []Binding `json:"bindings"` + By string `json:"by"` // ByID is the approver's immutable identity ID; By holds their display name. ByID string `json:"by_id,omitzero"` At time.Time `json:"at"` @@ -469,7 +482,7 @@ type Approval struct { // Covers reports whether the approval was given for d's action. func (a Approval) Covers(d Decision) bool { - return a.DecisionID == d.ID && a.Digest == d.Action.Digest + return slices.Contains(a.Bindings, Bind(d)) } // ExecuteApproved runs an action a person approved. A refusal still refuses, diff --git a/modules/judgement/judgement_test.go b/modules/judgement/judgement_test.go index 33c404112..0ff3b990f 100644 --- a/modules/judgement/judgement_test.go +++ b/modules/judgement/judgement_test.go @@ -215,7 +215,7 @@ func TestExecuteApprovedRunsOnlyWhatThePersonSaw(t *testing.T) { } } approval := func(d Decision) Approval { - return Approval{DecisionID: d.ID, Digest: d.Action.Digest, By: "admin", At: time.Now().UTC()} + return Approval{Bindings: []Binding{Bind(d)}, By: "admin", At: time.Now().UTC()} } tests := []struct { name string @@ -230,7 +230,7 @@ func TestExecuteApprovedRunsOnlyWhatThePersonSaw(t *testing.T) { d: decided, input: judged, a: func(d Decision) Approval { other := approval(d) - other.DecisionID = uuid.MustParse("22222222-2222-2222-2222-222222222222") + other.Bindings[0].DecisionID = uuid.MustParse("22222222-2222-2222-2222-222222222222") return other }, wantErr: ErrUnapproved, @@ -240,7 +240,7 @@ func TestExecuteApprovedRunsOnlyWhatThePersonSaw(t *testing.T) { d: decided, input: judged, a: func(d Decision) Approval { other := approval(d) - other.Digest = connectors.Digest("delete", jsontext.Value(`{"path":"/"}`)) + other.Bindings[0].Digest = connectors.Digest("delete", jsontext.Value(`{"path":"/"}`)) return other }, wantErr: ErrUnapproved, diff --git a/modules/proposals/binding.go b/modules/proposals/binding.go index 0f6788475..5a265c269 100644 --- a/modules/proposals/binding.go +++ b/modules/proposals/binding.go @@ -42,7 +42,7 @@ func bind(p store.Proposal, actions []store.Action, decisions []judgement.Decisi out = append(out, runs.ApprovedAction{ Seq: a.Seq, Decision: d, Approval: judgement.Approval{ - DecisionID: d.ID, Digest: a.Digest, By: p.AnsweredByID.String, ByID: p.AnsweredByID.String, At: p.AnsweredAt.Time, + Bindings: []judgement.Binding{{DecisionID: d.ID, Digest: a.Digest}}, By: p.AnsweredByID.String, ByID: p.AnsweredByID.String, At: p.AnsweredAt.Time, }, }) } diff --git a/modules/proposals/binding_test.go b/modules/proposals/binding_test.go index 7aef668ef..882a22cf0 100644 --- a/modules/proposals/binding_test.go +++ b/modules/proposals/binding_test.go @@ -87,7 +87,7 @@ func TestBindApprovesExactlyTheJudgedActions(t *testing.T) { if err != nil { t.Fatal(err) } - if len(got) != 1 || got[0].Approval.DecisionID != good.ID || got[0].Approval.Digest != digest || got[0].Approval.ByID != "person-1" { + if len(got) != 1 || got[0].Approval.Bindings[0].DecisionID != good.ID || got[0].Approval.Bindings[0].Digest != digest || got[0].Approval.ByID != "person-1" { t.Fatalf("approval = %+v, want one covering decision %s with digest %s by person-1", got, good.ID, digest) } if !got[0].Approval.Covers(got[0].Decision) { diff --git a/modules/runs/cancel_test.go b/modules/runs/cancel_test.go new file mode 100644 index 000000000..726f159b5 --- /dev/null +++ b/modules/runs/cancel_test.go @@ -0,0 +1,44 @@ +package runs + +import ( + "context" + "log/slog" + "testing" + + "github.com/google/uuid" + + "github.com/samcharles93/archie-core/modules/governance" + "github.com/samcharles93/archie-core/modules/runs/internal/store" +) + +// cancelFake records what a cancel asked storage for. +type cancelFake struct { + orgID string + id uuid.UUID + by string +} + +func (f *cancelFake) Cancel(_ context.Context, orgID string, id uuid.UUID, by string) error { + f.orgID, f.id, f.by = orgID, id, by + return nil +} + +// TestCancelRecordsWhoAsked guards #2100: cancelling a run left no entry in the +// run's trail, so the trail could not say when a run stopped, or who stopped +// it. The principal making the request is what the entry must name. +func TestCancelRecordsWhoAsked(t *testing.T) { + db := &cancelFake{} + e := newEngine(store.New(nil), nil, slog.New(slog.DiscardHandler), Options{}) + e.cancel = db + id := uuid.New() + ctx := governance.WithPrincipal(t.Context(), governance.Principal{IdentityID: "sam", Org: "org-sys"}) + if err := e.Cancel(ctx, "org-sys", id); err != nil { + t.Fatal(err) + } + if db.by != "sam" { + t.Fatalf("cancel recorded by %q, want the principal that asked", db.by) + } + if db.id != id || db.orgID != "org-sys" { + t.Fatalf("cancel asked storage for %s in %s, want %s in org-sys", db.id, db.orgID, id) + } +} diff --git a/modules/runs/checks.go b/modules/runs/checks.go index b3e1d8fe2..705e0485d 100644 --- a/modules/runs/checks.go +++ b/modules/runs/checks.go @@ -23,9 +23,65 @@ func (d Document) validate() []Problem { for i, s := range d.Steps { c.step(fmt.Sprintf("steps[%d]", i), s, d.mode(), earlier) } + c.covers(d.Steps) return c.problems } +// covers checks that an approval covers steps that come after it, so they can +// be judged when it asks, and that judgement can judge them: connector.action +// steps, each covered by one approval only and none of them reading another +// step the same approval covers. +func (c *checker) covers(steps []Step) { + covered := make(map[string]int, len(steps)) + for i, s := range steps { + if s.Type != typeApproval { + continue + } + var settings approvalSettings + if decodeSettings(s.Settings, &settings) != nil { + continue + } + together := make(map[string]bool, len(settings.Covers)) + for _, id := range settings.Covers { + together[id] = true + } + for j, id := range settings.Covers { + at := fmt.Sprintf("steps[%d].settings.covers[%d]", i, j) + target, k := stepAfter(steps, i, id) + switch { + case k < 0: + c.add(at, "no step after this one has id %q", id) + continue + case target.Type != typeAction: + c.add(at, "step %q is %s, and an approval covers connector.action steps only", id, target.Type) + continue + } + if other, twice := covered[id]; twice { + c.add(at, "step %q is already covered by the approval at steps[%d]", id, other) + } + covered[id] = i + // The approval judges every step it covers when it asks, so one that + // reads another of them has no value to judge yet. + for _, ref := range stepRefs(target.Settings) { + if together[ref] { + c.add(fmt.Sprintf("steps[%d].settings", k), "step %q reads step %q, which the same approval covers and which hasn't run yet when it asks", id, ref) + } + } + } + } +} + +// stepAfter returns the step after the approval at from that has this id, and +// its index in steps, or -1. +func stepAfter(steps []Step, from int, id string) (Step, int) { + for i := from + 1; i < len(steps); i++ { + if id != "" && steps[i].ID == id { + return steps[i], i + } + } + return Step{}, -1 +} + // step validates one step against the vocabulary and the steps before it, and // adds the id it declares to earlier. func (c *checker) step(at string, s Step, mode RepositoryMode, earlier *refScope) { diff --git a/modules/runs/escalation_test.go b/modules/runs/escalation_test.go index 65c4e06a4..1a22ad3b8 100644 --- a/modules/runs/escalation_test.go +++ b/modules/runs/escalation_test.go @@ -83,7 +83,7 @@ type escalations struct { expired int } -func (e *escalations) Ask(context.Context, uuid.UUID, string, judgement.Decision, []governance.PathStep) (approvals.Request, error) { +func (e *escalations) Ask(context.Context, uuid.UUID, string, []judgement.Decision, []governance.PathStep) (approvals.Request, error) { return approvals.Request{}, nil } diff --git a/modules/runs/internal/store/store.go b/modules/runs/internal/store/store.go index d7ca56a8d..21f9adc8f 100644 --- a/modules/runs/internal/store/store.go +++ b/modules/runs/internal/store/store.go @@ -6,6 +6,7 @@ import ( "context" "database/sql" "encoding/json/jsontext" + json "encoding/json/v2" "errors" "fmt" "slices" @@ -446,7 +447,7 @@ const cancelDepth = 5 // is nothing left to cancel. Already-ended descendants are left alone. Only // the named run tells its own caller: the descendants' callers are being // cancelled in the same transaction. -func (s *Store) Cancel(ctx context.Context, orgID string, id uuid.UUID) error { +func (s *Store) Cancel(ctx context.Context, orgID string, id uuid.UUID, by string) error { tx, err := s.db.BeginTxx(ctx, nil) if err != nil { return fmt.Errorf("cancel run: %w", err) @@ -462,7 +463,35 @@ func (s *Store) Cancel(ctx context.Context, orgID string, id uuid.UUID) error { case state == StateSucceeded || state == StateFailed || state == StateCancelled || state == StateDeclined: return ErrEnded } - if _, err := tx.ExecContext(ctx, ` + stopped, err := stopTree(ctx, tx, id) + if err != nil { + return err + } + if err := recordCancel(ctx, tx, stopped, by); err != nil { + return err + } + if err := signalParent(ctx, tx, id); err != nil { + return err + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("cancel run: %w", err) + } + return nil +} + +// stepCancel names the trail entry a stopped run records. +const stepCancel = "cancel" + +// cancelEntry is what that entry holds: the principal that asked for the stop. +// When the run stopped is the entry's own time. +type cancelEntry struct { + By string `json:"by,omitzero"` +} + +// stopTree marks a run and the runs it called cancelled, returning the runs it +// stopped. A run already executing is asked to stop and ends at its next step. +func stopTree(ctx context.Context, tx *sqlx.Tx, id uuid.UUID) ([]uuid.UUID, error) { + rows, err := tx.QueryContext(ctx, ` WITH RECURSIVE tree(id, depth) AS ( SELECT id, 0 FROM runs.runs WHERE id = $1 UNION ALL @@ -472,15 +501,40 @@ func (s *Store) Cancel(ctx context.Context, orgID string, id uuid.UUID) error { SET cancel_requested = true, updated_at = now(), state = CASE WHEN state IN ('queued', 'waiting', 'parked', 'waiting_approval') THEN 'cancelled' ELSE state END, finished_at = CASE WHEN state IN ('queued', 'waiting', 'parked', 'waiting_approval') THEN now() ELSE finished_at END - WHERE id IN (SELECT id FROM tree) AND state NOT IN ('succeeded', 'failed', 'cancelled', 'declined')`, - id, cancelDepth); err != nil { + WHERE id IN (SELECT id FROM tree) AND state NOT IN ('succeeded', 'failed', 'cancelled', 'declined') + RETURNING id`, + id, cancelDepth) + if err != nil { + return nil, fmt.Errorf("cancel run: %w", err) + } + defer func() { _ = rows.Close() }() + var stopped []uuid.UUID + for rows.Next() { + var stoppedID uuid.UUID + if err := rows.Scan(&stoppedID); err != nil { + return nil, fmt.Errorf("cancel run: %w", err) + } + stopped = append(stopped, stoppedID) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("cancel run: %w", err) + } + return stopped, nil +} + +// recordCancel writes the entry a stop leaves on each run's trail. +func recordCancel(ctx context.Context, tx *sqlx.Tx, stopped []uuid.UUID, by string) error { + entry, err := json.Marshal(cancelEntry{By: by}) + if err != nil { return fmt.Errorf("cancel run: %w", err) } - if err := signalParent(ctx, tx, id); err != nil { - return err - } - if err := tx.Commit(); err != nil { - return fmt.Errorf("cancel run: %w", err) + for _, stoppedID := range stopped { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO runs.steps (run_id, seq, name, outcome, output) + VALUES ($1, COALESCE((SELECT max(seq) FROM runs.steps WHERE run_id = $1), 0) + 1, $2, 'done', $3::json)`, + stoppedID, stepCancel, entry); err != nil { + return fmt.Errorf("cancel run: %w", err) + } } return nil } diff --git a/modules/runs/interpreter.go b/modules/runs/interpreter.go index fff7c113b..79207bbe2 100644 --- a/modules/runs/interpreter.go +++ b/modules/runs/interpreter.go @@ -58,11 +58,12 @@ type Judge interface { } // Approver requests approval for actions held by judgement, escalates -// unanswered requests and expires them after the final deadline. An approval -// counts towards an increase in autonomy only when the action is about to run -// using it. If reassessment invalidates the approval, it is discarded instead. +// unanswered requests and expires them after the final deadline. One request +// covers one action or a sequence approved in one act. An approval counts +// towards an increase in autonomy only when the action is about to run using +// it. If reassessment invalidates the approval, it is discarded instead. type Approver interface { - Ask(ctx context.Context, runID uuid.UUID, key string, d judgement.Decision, path []governance.PathStep) (approvals.Request, error) + Ask(ctx context.Context, runID uuid.UUID, key string, ds []judgement.Decision, path []governance.PathStep) (approvals.Request, error) Escalate(ctx context.Context, id uuid.UUID, step int, to governance.PathStep) error Expire(ctx context.Context, id uuid.UUID) error Accept(ctx context.Context, id uuid.UUID) error @@ -139,6 +140,9 @@ type pinned struct { // progress is what the steps of one execution have produced so far. type progress struct { pin pinned + // steps are the document's steps, so an approval can judge the steps it + // covers before the run reaches them. + steps []Step // input is the run's input as it came, and inputs the same decoded, which // references read. input jsontext.Value @@ -148,6 +152,8 @@ type progress struct { agent *AgentResult memory bool remembered bool + // sequences are the approvals that cover later steps, each until it stops. + sequences []*sequence // last is the summary of the most recent step. A run that completes every // step uses it as its detail. last string @@ -168,7 +174,7 @@ func (d Deps) Compile(doc Document) Workflow { settleAtEnd := settlesAtEnd(doc) return func(rc *Context, input jsontext.Value) (jsontext.Value, error) { p := &progress{ - input: input, inputs: decodeInputs(input), instructions: doc.Instructions, + input: input, inputs: decodeInputs(input), instructions: doc.Instructions, steps: doc.Steps, results: map[string]StepResult{}, outcomes: []approvalOutcome{}, settled: map[string]bool{}, } if len(aliases) > 0 { @@ -626,7 +632,7 @@ func settleOne(rc *Context, judge Judge, ask Approver, settings Settings, d judg out := approvalOutcome{digest: d.Action.Digest} for round := 0; ; round++ { out.Action, out.Target = d.Action.Connector+" "+d.Action.Name, d.Action.Target.Kind+":"+d.Action.Target.ID - request, answer, err := askThroughPath(rc, ask, settings, d) + request, answer, err := askThroughPath(rc, ask, settings, d.Key, []judgement.Decision{d}) if err != nil { return out, err } @@ -676,19 +682,27 @@ func settleOne(rc *Context, judge Judge, ask Approver, settings Settings, d judg } } -// askThroughPath puts d to the first step of its escalation path and waits. +// askThroughPath puts ds to the first step of their escalation path and waits. // The path is pinned when it is first asked, so a request that waits keeps the // deadlines it started with whatever the settings become meanwhile. It returns // the request as it stood when it settled, and the answer if there was one. -func askThroughPath(rc *Context, ask Approver, settings Settings, d judgement.Decision) (approvals.Request, approvals.Answer, error) { - path, err := rc.Step("path:"+d.Key, func(ctx context.Context, _ string) ([]governance.PathStep, error) { - return settings.EscalationPath(ctx, d.Owner(), d.Level == judgement.Escalate) +func askThroughPath(rc *Context, ask Approver, settings Settings, key string, ds []judgement.Decision) (approvals.Request, approvals.Answer, error) { + var owner string + var escalate bool + for _, d := range ds { + if owner == "" { + owner = d.Owner() + } + escalate = escalate || d.Level == judgement.Escalate + } + path, err := rc.Step("path:"+key, func(ctx context.Context, _ string) ([]governance.PathStep, error) { + return settings.EscalationPath(ctx, owner, escalate) }) if err != nil { return approvals.Request{}, approvals.Answer{}, err } - request, err := rc.Step("ask:"+d.Key, func(ctx context.Context, _ string) (approvals.Request, error) { - return ask.Ask(ctx, rc.RunID(), waitKey(d.Key), d, path) + request, err := rc.Step("ask:"+key, func(ctx context.Context, _ string) (approvals.Request, error) { + return ask.Ask(ctx, rc.RunID(), waitKey(key), ds, path) }) if err != nil { return request, approvals.Answer{}, err @@ -698,7 +712,7 @@ func askThroughPath(rc *Context, ask Approver, settings Settings, d judgement.De } // A request already answered when it was asked again still has its answer // waiting under the run's key, so the wait returns it at once. - answer, expired, err := waitThroughPath(rc, ask, d.Key, request, path) + answer, expired, err := waitThroughPath(rc, ask, key, request, path) switch { case err != nil: return request, answer, err @@ -896,6 +910,8 @@ func outcomeLines(outcomes []approvalOutcome) string { switch { case o.Unknown: line += ", it was started but its outcome is unknown: " + o.Error + case o.State == stateUnrun: + line += ", because " + o.Error case o.Error != "": line += ", it did not run: " + o.Error case o.Result != "": diff --git a/modules/runs/references.go b/modules/runs/references.go index 9ac20954d..3f70aec97 100644 --- a/modules/runs/references.go +++ b/modules/runs/references.go @@ -4,6 +4,7 @@ import ( json "encoding/json/v2" "fmt" "regexp" + "slices" "strings" "gopkg.in/yaml.v3" @@ -93,6 +94,21 @@ func checkReferences(settings yaml.Node, earlier *refScope) []error { return problems } +// stepRefs lists the steps a step's settings read, once each. +func stepRefs(settings yaml.Node) []string { + var out []string + walkStrings(&settings, func(value string) { + for _, match := range referencePattern.FindAllStringSubmatch(value, -1) { + parts := strings.Split(match[1], ".") + if len(parts) < 2 || parts[0] != "steps" || slices.Contains(out, parts[1]) { + continue + } + out = append(out, parts[1]) + } + }) + return out +} + func checkReference(path string, earlier *refScope) error { parts := strings.Split(path, ".") switch parts[0] { diff --git a/modules/runs/runs.go b/modules/runs/runs.go index 288a4ac48..fbba1c9f2 100644 --- a/modules/runs/runs.go +++ b/modules/runs/runs.go @@ -57,6 +57,12 @@ type runWork interface { runStarter } +// canceller is what Cancel needs from storage: it stops a run and the runs it +// called, and records who asked. It is db except in tests. +type canceller interface { + Cancel(ctx context.Context, orgID string, id uuid.UUID, by string) error +} + // runStarter is what a step that starts another run needs from storage. type runStarter interface { workflowFinder @@ -70,11 +76,13 @@ type Engine struct { defs definitions // queue starts runs; it is db except in tests. queue runQueue - work runWork - log *slog.Logger - opts Options - mu sync.RWMutex - deps *Deps + // cancel stops a run and writes its trail entry; it is db except in tests. + cancel canceller + work runWork + log *slog.Logger + opts Options + mu sync.RWMutex + deps *Deps // referrers finds the triggers that name a workflow. referrers Referrers // claimFailure is the last failed attempt to claim a run, cleared by the @@ -103,7 +111,7 @@ func newEngine(db *store.Store, work runWork, log *slog.Logger, opts Options) *E if opts.Owner == "" { opts.Owner = "archie" } - e := &Engine{db: db, defs: db, queue: db, work: work, log: log, opts: opts} + e := &Engine{db: db, defs: db, queue: db, cancel: db, work: work, log: log, opts: opts} e.load = e.loadDocument return e } @@ -344,7 +352,12 @@ var ErrEnded = errors.New("run has already ended") // Cancel asks a run to stop, along with every run it started through // workflow.call. A run that has already ended is refused. func (e *Engine) Cancel(ctx context.Context, orgID string, id uuid.UUID) error { - err := e.db.Cancel(ctx, orgID, id) + // The trail names who stopped the run, which is the caller asking for it. + by := "" + if p, ok := governance.PrincipalFromContext(ctx); ok { + by = string(p.IdentityID) + } + err := e.cancel.Cancel(ctx, orgID, id, by) if errors.Is(err, store.ErrEnded) { return fmt.Errorf("%w: %w", ErrEnded, err) } diff --git a/modules/runs/sequence.go b/modules/runs/sequence.go new file mode 100644 index 000000000..e499bcbd6 --- /dev/null +++ b/modules/runs/sequence.go @@ -0,0 +1,221 @@ +package runs + +import ( + "context" + "fmt" + "strings" + + "github.com/google/uuid" + "gopkg.in/yaml.v3" + + "github.com/samcharles93/archie-core/modules/approvals" + "github.com/samcharles93/archie-core/modules/judgement" +) + +// stateUnrun is what an action an approval covered settles as when an earlier +// action of the same approval stopped it. +const stateUnrun = "not run" + +// sequence is one approval that covers a list of steps, with the approval each +// step runs under and whether it has stopped. +type sequence struct { + requestID uuid.UUID + steps []coveredStep + // stopped is why no later step of the sequence runs, empty while one may. + stopped string + // counted is whether the approval has already counted for a step that ran, + // which leaves it unable to be discarded. + counted bool +} + +// coveredStep is one step a sequence covers: the action judged when the person +// was asked, and the approval that lets it run. +type coveredStep struct { + name string + decision judgement.Decision + approval judgement.Approval +} + +// covered returns the approval that covers the step this name, and its place +// in that approval's sequence. +func (p *progress) covered(name string) (*sequence, int) { + for _, seq := range p.sequences { + for i := range seq.steps { + if seq.steps[i].name == name { + return seq, i + } + } + } + return nil, 0 +} + +// step returns the document step with this id. +func (p *progress) step(id string) (Step, bool) { + for _, s := range p.steps { + if s.ID == id { + return s, true + } + } + return Step{}, false +} + +// outcomeOf is what became of one covered action. +func outcomeOf(d judgement.Decision, state, by, why string) approvalOutcome { + return approvalOutcome{ + Action: d.Action.Connector + " " + d.Action.Name, + Target: d.Action.Target.Kind + ":" + d.Action.Target.ID, + State: state, By: by, Error: why, digest: d.Action.Digest, + } +} + +// approveCovered judges the steps covers names and asks one person to approve +// them all, in that order. Each step then runs under that one approval, judged +// again first. A step whose action can't be judged now is not covered: an +// approval of something other than the action that will run is no approval. +func (d Deps) approveCovered(rc *Context, p *progress, name string, covers []string) (StepResult, error) { + seq := &sequence{steps: make([]coveredStep, 0, len(covers))} + values := scope(p.inputs, p.results) + for _, id := range covers { + step, ok := p.step(id) + if !ok { + return StepResult{}, fmt.Errorf("no step has id %q", id) + } + if missing := unresolved(step.Settings, p.results); len(missing) > 0 { + return StepResult{}, fmt.Errorf("%q reads steps %s, which haven't run, so its action can't be judged yet", + id, strings.Join(missing, ", ")) + } + var s actionSettings + if err := decodeSettings(renderSettings(step.Settings, values), &s); err != nil { + return StepResult{}, fmt.Errorf("%q: %w", id, err) + } + in, err := actionInput(s) + if err != nil { + return StepResult{}, fmt.Errorf("%q: %w", id, err) + } + decision, err := rc.Step("cover:"+id, func(ctx context.Context, key string) (judgement.Decision, error) { + return d.Judge.Assess(ctx, rc.request(key, s.Connector, s.Name, in)) + }) + if err != nil { + return StepResult{}, err + } + if decision.Level == judgement.Never { + return StepResult{}, fmt.Errorf("%q is refused: %s", id, decision.Reason) + } + seq.steps = append(seq.steps, coveredStep{name: id, decision: decision}) + } + ds := make([]judgement.Decision, len(seq.steps)) + for i, cs := range seq.steps { + ds[i] = cs.decision + } + request, answer, err := askThroughPath(rc, d.Approver, d.Settings, name, ds) + if err != nil { + return StepResult{}, err + } + seq.requestID = request.ID + if request.State != approvals.StateApproved { + // A denial or an expiry stops the sequence: no step it covered runs, not + // even on a judgement of its own. + seq.stopped = "the request was " + request.State + if request.State == approvals.StateExpired { + seq.stopped = "the request expired" + } + out := make([]approvalOutcome, 0, len(seq.steps)) + for _, cs := range seq.steps { + p.settled[cs.decision.Action.Digest] = true + out = append(out, outcomeOf(cs.decision, stateUnrun, answer.By, seq.stopped)) + } + p.outcomes = append(p.outcomes, out...) + p.sequences = append(p.sequences, seq) + return StepResult{Summary: outcomeLines(out)}, nil + } + approval := request.Approval(answer) + for i := range seq.steps { + p.settled[seq.steps[i].decision.Action.Digest] = true + seq.steps[i].approval = approval + } + p.sequences = append(p.sequences, seq) + return StepResult{Summary: fmt.Sprintf("%d actions approved by %s", len(seq.steps), answer.By)}, nil +} + +// runCovered runs one step of an approved sequence. The step's action is judged +// again first: a judgement that refuses it, is stricter than the one approved, +// or names a changed target or effect stops the sequence, as does an action +// that fails, and every action after it is reported unrun. +func (d Deps) runCovered(rc *Context, p *progress, seq *sequence, i int) (StepResult, error) { + cs := seq.steps[i] + level := cs.decision.Level.String() + if why := seq.stopped; why != "" { + res := ranStep(level, outcomeOf(cs.decision, stateUnrun, "", why)) + res.Summary = stateUnrun + ": " + why + return res, nil + } + // The steps are named after the decision's key, as one settled alone is, + // so the trail folds each reassessment into the action it reassessed. + name := cs.decision.Key + fresh, err := rc.Step("judge-again:"+name, func(ctx context.Context, key string) (judgement.Decision, error) { + return d.Judge.Assess(ctx, rc.request(key, cs.decision.Action.Connector, cs.decision.Action.Name, cs.decision.Action.Input)) + }) + if err != nil { + return StepResult{}, err + } + out := outcomeOf(cs.decision, approvals.StateApproved, cs.approval.By, "") + switch next, why := afterApproval(cs.decision, fresh); next { + case runApproval: + if _, err := rc.Step("count:"+name, func(ctx context.Context, _ string) (bool, error) { + return true, d.Approver.Accept(ctx, seq.requestID) + }); err != nil { + return StepResult{}, err + } + seq.counted = true + out.State = EffectRan + out.Result, out.Error, out.Unknown = runJudged(rc, d.Judge, cs.decision, &cs.approval) + case runFresh: + // The step no longer needs approval, so it runs on its own judgement + // and the approval isn't counted. + out.State = EffectRan + out.Result, out.Error, out.Unknown = runJudged(rc, d.Judge, fresh, nil) + default: + // The person approved one act, not whatever the steps become: a step + // that no longer matches it isn't asked about again, it stops the rest. + out.State, out.Error = approvals.StateDiscarded, why + if seq.counted { + // An approval that already let an action of the sequence run has + // counted and can't be discarded, so the step is reported unrun under + // it and the record keeps agreeing with the report. + out.State = stateUnrun + } else if _, err := rc.Step("discard:"+name, func(ctx context.Context, _ string) (bool, error) { + return true, d.Approver.Discard(ctx, seq.requestID, why) + }); err != nil { + return StepResult{}, err + } + } + p.outcomes = append(p.outcomes, out) + p.stopped = p.stopped || out.Unknown + if out.State != EffectRan || out.Error != "" || out.Unknown { + p.stopSequence(seq, i, firstText(out.Error, "an earlier action of the sequence did not run")) + } + return ranStep(level, out), nil +} + +// stopSequence reports the actions after the one at from as unrun, so the run +// says what the approval covered and did not do. +func (p *progress) stopSequence(seq *sequence, from int, why string) { + seq.stopped = why + for _, cs := range seq.steps[from+1:] { + p.outcomes = append(p.outcomes, outcomeOf(cs.decision, stateUnrun, "", why)) + } +} + +// unresolved lists the steps a step's settings read that have no result yet. +// Their values render empty, so the action they belong to can't be judged now. +// The checker refuses an approval that covers such a step, which leaves a +// document saved before it did, or a step an earlier condition skipped. +func unresolved(settings yaml.Node, results map[string]StepResult) []string { + var out []string + for _, id := range stepRefs(settings) { + if _, done := results[id]; !done { + out = append(out, id) + } + } + return out +} diff --git a/modules/runs/sequence_test.go b/modules/runs/sequence_test.go new file mode 100644 index 000000000..4a441f085 --- /dev/null +++ b/modules/runs/sequence_test.go @@ -0,0 +1,335 @@ +package runs + +import ( + "context" + "encoding/json/jsontext" + "slices" + "strings" + "testing" + + "github.com/google/uuid" + + "github.com/samcharles93/archie-core/modules/connectors" + "github.com/samcharles93/archie-core/modules/judgement" + "github.com/samcharles93/archie-core/modules/runs/internal/store" +) + +// sequenceJudge decides each action at the level it lists, and can decide one +// action differently the second time, as a target or an effect that changed +// after the person approved it. +type sequenceJudge struct { + levels map[string]judgement.Level + again map[string]func(judgement.Decision) judgement.Decision + // judged counts how often each action was judged. + judged map[string]int + ran []string + decisions []judgement.Decision +} + +func (j *sequenceJudge) Assess(_ context.Context, req judgement.Request) (judgement.Decision, error) { + if j.judged == nil { + j.judged = map[string]int{} + } + j.judged[req.Action]++ + d := judgement.Decision{ + ID: uuid.New(), Key: req.Key, Level: j.levels[req.Action], + Action: judgement.Action{ + Connector: req.Connector, Name: req.Action, Input: req.Input, + Digest: connectors.Digest(req.Action, req.Input), + Target: connectors.Target{Kind: "container", ID: "web"}, + }, + } + if j.judged[req.Action] > 1 { + if change := j.again[req.Action]; change != nil { + d = change(d) + } + } + j.decisions = append(j.decisions, d) + return d, nil +} + +func (j *sequenceJudge) Execute(_ context.Context, d judgement.Decision, _ jsontext.Value, _ string) (string, error) { + j.ran = append(j.ran, d.Action.Name) + return "done", nil +} + +func (j *sequenceJudge) ExecuteApproved(_ context.Context, d judgement.Decision, a judgement.Approval, _ jsontext.Value, _ string) (string, error) { + if !a.Covers(d) { + return "", judgement.ErrUnapproved + } + j.ran = append(j.ran, d.Action.Name) + return "done", nil +} + +func (j *sequenceJudge) ForRun(context.Context, uuid.UUID) ([]judgement.Decision, error) { + return j.decisions, nil +} + +// answerWork answers the run's approval wait as the case says: approval, a +// denial, or nothing at all, so the request runs out unanswered. +type answerWork struct { + fakeWork + denied bool + silent bool +} + +func (w *answerWork) Signalled(context.Context, uuid.UUID, string) (jsontext.Value, bool, error) { + switch { + case w.silent: + return nil, false, nil + case w.denied: + return jsontext.Value(`{"approved":false,"by":"Second"}`), true, nil + } + return jsontext.Value(`{"approved":true,"by":"Second"}`), true, nil +} + +// TestASequenceStopsWhenAnActionChangesAfterItIsApproved guards the approval of +// a sequence: one request covers every action in the order the person saw +// them, each is judged again before it runs, and an action whose target changed, +// whose judgement is now stricter, or that is now refused does not run and +// leaves the rest of the sequence unrun and reported. A request nobody approves +// runs none of it, on any judgement of its own. +func TestASequenceStopsWhenAnActionChangesAfterItIsApproved(t *testing.T) { + const doc = `steps: + - id: approve + type: approval.wait + settings: {covers: [snapshot, clean, delete, verify]} + - id: snapshot + type: connector.action + settings: {connector: host, name: snapshot} + - id: clean + type: connector.action + settings: {connector: host, name: clean} + - id: delete + type: connector.action + settings: {connector: host, name: delete} + - id: verify + type: connector.action + settings: {connector: host, name: verify} + - type: run.notify +` + held := map[string]judgement.Level{ + "snapshot": judgement.ProposeAndWait, "clean": judgement.ProposeAndWait, + "delete": judgement.ProposeAndWait, "verify": judgement.ProposeAndWait, + } + targetMoved := func(d judgement.Decision) judgement.Decision { + d.Action.Target.ID = "db-2" + return d + } + stricter := func(d judgement.Decision) judgement.Decision { + d.Level = judgement.Escalate + return d + } + refused := func(d judgement.Decision) judgement.Decision { + d.Level, d.Reason = judgement.Never, "a release is in flight" + return d + } + unattended := func(d judgement.Decision) judgement.Decision { + d.Level = judgement.ActQuietly + return d + } + // Judgement lets every action of the sequence run unattended, as it may once + // the reason it was held no longer applies. + runsAlone := map[string]func(judgement.Decision) judgement.Decision{ + "snapshot": unattended, "clean": unattended, "delete": unattended, "verify": unattended, + } + tests := []struct { + name string + // again is how an action is judged the second time. + again map[string]func(judgement.Decision) judgement.Decision + // denied and silent are how the person answers the request, if at all. + denied bool + silent bool + // wantRan are the actions that ran, in order. + wantRan []string + // wantBody is what the run reports of the actions after the one that + // did not run. + wantBody []string + }{ + { + name: "every action of the sequence runs", + wantRan: []string{"snapshot", "clean", "delete", "verify"}, + }, + { + name: "an action whose target changed after the approval does not run", + again: map[string]func(judgement.Decision) judgement.Decision{"delete": targetMoved}, + wantRan: []string{"snapshot", "clean"}, + wantBody: []string{ + "host delete on container:web: not run, because the target changed since it was approved", + "host verify on container:web: not run, because the target changed since it was approved", + }, + }, + { + name: "an action judged stricter after the approval stops the rest", + again: map[string]func(judgement.Decision) judgement.Decision{"delete": stricter}, + wantRan: []string{"snapshot", "clean"}, + wantBody: []string{ + "host delete on container:web: not run, because judgement is stricter than when the action was approved: now escalate", + "host verify on container:web: not run, because judgement is stricter than when the action was approved: now escalate", + }, + }, + { + name: "an action refused after the approval stops the rest", + again: map[string]func(judgement.Decision) judgement.Decision{"delete": refused}, + wantRan: []string{"snapshot", "clean"}, + wantBody: []string{ + "host delete on container:web: not run, because refused after approval: a release is in flight", + }, + }, + { + name: "a denied request runs none of the actions it covered", + again: runsAlone, + denied: true, + wantBody: []string{ + "host snapshot on container:web: not run, because the request was denied", + "host verify on container:web: not run, because the request was denied", + }, + }, + { + name: "a request nobody answers in time runs none of the actions it covered", + again: runsAlone, + silent: true, + wantBody: []string{ + "host snapshot on container:web: not run, because the request expired", + "host verify on container:web: not run, because the request expired", + }, + }, + { + name: "every action after the one that changed is reported unrun", + again: map[string]func(judgement.Decision) judgement.Decision{"clean": targetMoved}, + wantRan: []string{"snapshot"}, + wantBody: []string{ + "host delete on container:web: not run, because the target changed since it was approved", + "host verify on container:web: not run, because the target changed since it was approved", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + parsed, err := ParseDocument(doc) + if err != nil { + t.Fatalf("ParseDocument: %v", err) + } + judge := &sequenceJudge{levels: held, again: tt.again} + ask := &askCounter{} + told := ¬ices{} + wf := Deps{Settings: onePersonPath{}, Judge: judge, Approver: ask, Notifier: told}.Compile(parsed) + work := &answerWork{fakeWork: fakeWork{}, denied: tt.denied, silent: tt.silent} + run := store.Run{ID: uuid.New()} + rc := newContext(t.Context(), work, run, uuid.New(), nil) + if _, err := wf(rc, jsontext.Value(`{}`)); err != nil { + t.Fatalf("run error = %v", err) + } + if rc.ending == nil || rc.ending.State != store.StateSucceeded { + t.Fatalf("ending = %+v, want the run succeeded", rc.ending) + } + if ask.asked != 1 { + t.Fatalf("asked %d times, want one approval for the whole sequence", ask.asked) + } + if !slices.Equal(judge.ran, tt.wantRan) { + t.Fatalf("ran %q, want %q", judge.ran, tt.wantRan) + } + if len(told.sent) != 1 { + t.Fatalf("notices = %+v, want one", told.sent) + } + for _, want := range tt.wantBody { + if !strings.Contains(told.sent[0].Body, want) { + t.Fatalf("report is %q, want it to contain %q", told.sent[0].Body, want) + } + } + }) + } +} + +// TestACoveredStepReportsTheSameResultAsAnUncoveredOne guards what a covered +// action hands the steps after the sequence: the state and the output an action +// step reports when no approval covers it. +func TestACoveredStepReportsTheSameResultAsAnUncoveredOne(t *testing.T) { + doc, err := ParseDocument(`steps: + - id: approve + type: approval.wait + settings: {covers: [snapshot]} + - id: snapshot + type: connector.action + settings: {connector: host, name: snapshot} + - type: message.send + settings: {channel: chat, chat_id: ops, text: "{{ steps.snapshot.result.state }} {{ steps.snapshot.result.result }}"} +`) + if err != nil { + t.Fatalf("ParseDocument: %v", err) + } + judge := &sequenceJudge{levels: map[string]judgement.Level{"snapshot": judgement.ProposeAndWait}} + sent := &chats{} + wf := Deps{Settings: onePersonPath{}, Judge: judge, Approver: &askCounter{}, Messenger: sent, Notifier: ¬ices{}}.Compile(doc) + rc := newContext(t.Context(), &answerWork{fakeWork: fakeWork{}}, store.Run{ID: uuid.New()}, uuid.New(), nil) + if _, err := wf(rc, jsontext.Value(`{}`)); err != nil { + t.Fatalf("run error = %v", err) + } + if want := []string{"chat/ops: ran done"}; !slices.Equal(sent.sent, want) { + t.Fatalf("sent %q, want %q", sent.sent, want) + } +} + +// TestCoversNamesLaterActionSteps guards the save-time check on a sequence: an +// approval covers action steps after it, each one only once and none of them +// reading another step of the same approval, so every action it covers can be +// judged when it asks. +func TestCoversNamesLaterActionSteps(t *testing.T) { + tests := []struct { + name string + doc string + want string + }{ + { + name: "an approval covering later action steps is accepted", + doc: `steps: + - {type: approval.wait, settings: {covers: [snapshot]}} + - {id: snapshot, type: connector.action, settings: {connector: host, name: snapshot}} +`, + }, + { + name: "a covered step before the approval is refused", + doc: `steps: + - {id: snapshot, type: connector.action, settings: {connector: host, name: snapshot}} + - {type: approval.wait, settings: {covers: [snapshot]}} +`, + want: `steps[1].settings.covers[0]: no step after this one has id "snapshot"`, + }, + { + name: "a covered step that is not an action is refused", + doc: `steps: + - {type: approval.wait, settings: {covers: [announce]}} + - {id: announce, type: message.send, settings: {channel: chat, chat_id: ops, text: hi}} +`, + want: `steps[0].settings.covers[0]: step "announce" is message.send, and an approval covers connector.action steps only`, + }, + { + name: "a step named twice by one approval is refused", + doc: `steps: + - {type: approval.wait, settings: {covers: [snapshot, snapshot]}} + - {id: snapshot, type: connector.action, settings: {connector: host, name: snapshot}} +`, + want: `steps[0].settings: covers names step "snapshot" twice`, + }, + { + name: "a covered step that reads another covered step is refused", + doc: `steps: + - {type: approval.wait, settings: {covers: [snapshot, delete]}} + - {id: snapshot, type: connector.action, settings: {connector: host, name: snapshot}} + - {id: delete, type: connector.action, settings: {connector: host, name: delete, input: {taken: "{{ steps.snapshot.result.id }}"}}} +`, + want: `steps[2].settings: step "delete" reads step "snapshot", which the same approval covers and which hasn't run yet when it asks`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := ParseDocument(tt.doc) + switch { + case tt.want == "" && err != nil: + t.Fatalf("ParseDocument: %v", err) + case tt.want != "" && (err == nil || !strings.Contains(err.Error(), tt.want)): + t.Fatalf("ParseDocument error = %v, want %q", err, tt.want) + } + }) + } +} diff --git a/modules/runs/steps_test.go b/modules/runs/steps_test.go index 2cb15d777..4f139d766 100644 --- a/modules/runs/steps_test.go +++ b/modules/runs/steps_test.go @@ -68,13 +68,20 @@ type askCounter struct { failFirst int } -func (a *askCounter) Ask(_ context.Context, _ uuid.UUID, _ string, d judgement.Decision, _ []governance.PathStep) (approvals.Request, error) { +func (a *askCounter) Ask(_ context.Context, _ uuid.UUID, _ string, ds []judgement.Decision, _ []governance.PathStep) (approvals.Request, error) { a.asked++ if a.failFirst > 0 { a.failFirst-- return approvals.Request{}, errors.New("approvals unavailable") } - return approvals.Request{ID: uuid.New(), State: approvals.StatePending, Decision: d}, nil + request := approvals.Request{ID: uuid.New(), State: approvals.StatePending, Decision: ds[0]} + for _, d := range ds { + request.Actions = append(request.Actions, approvals.Step{ + DecisionID: d.ID, Digest: d.Action.Digest, Level: d.Level.String(), + Action: d.Action.Connector + " " + d.Action.Name, Target: d.Action.Target.Kind + ":" + d.Action.Target.ID, + }) + } + return request, nil } func (a *askCounter) Escalate(context.Context, uuid.UUID, int, governance.PathStep) error { return nil } diff --git a/modules/runs/trail.go b/modules/runs/trail.go index 2e704a733..cb6e89829 100644 --- a/modules/runs/trail.go +++ b/modules/runs/trail.go @@ -92,6 +92,9 @@ type ActionTrail struct { // Approval is the request put to a person, with the summary they were shown // and who answered. An action that needed none has none. Approval *approvals.View `json:"approval,omitzero"` + // Stop is why an action of a sequence stopped the rest of it: its target, + // effect or judgement no longer matched what the person approved. + Stop string `json:"stop,omitzero"` // Effect is what the action did. An action that never ran has none. Effect *Effect `json:"effect,omitzero"` } @@ -380,15 +383,11 @@ func actions(decisions []judgement.Decision, asked []approvals.Request, steps [] } for i := range out { d := out[i].Decision + view, covers := approvedBy(asked, d) + out[i].Approval = view if r, ok := rejudged[d.Key]; ok { out[i].Rejudged = &r - } - for _, req := range asked { - if req.DecisionID == d.ID { - v := req.View() - out[i].Approval = &v - break - } + out[i].Stop = stoppedBy(d, r, covers) } switch run, ran := byName["run:"+d.Key]; { case ran: @@ -402,6 +401,30 @@ func actions(decisions []judgement.Decision, asked []approvals.Request, steps [] return out } +// approvedBy returns the request that covered d, and how many actions it +// covers, or nil when no person was asked. +func approvedBy(asked []approvals.Request, d judgement.Decision) (*approvals.View, int) { + for _, req := range asked { + if req.Covers(d) { + v := req.View() + return &v, len(v.Steps) + } + } + return nil, 0 +} + +// stoppedBy is why a step judged again stopped the sequence that covers it, or +// empty when it didn't: a request for a single action stops nothing. +func stoppedBy(d, fresh judgement.Decision, covers int) string { + if covers < 2 { + return "" + } + if next, why := afterApproval(d, fresh); next == reaskPerson || next == refuseAction { + return why + } + return "" +} + // stepKey is the idempotency key the engine gave the step at s. func stepKey(s store.Recorded) string { return s.RunID.String() + ":" + strconv.Itoa(s.Seq) } diff --git a/modules/runs/vocabulary.go b/modules/runs/vocabulary.go index cc734f5c4..e5e6efaca 100644 --- a/modules/runs/vocabulary.go +++ b/modules/runs/vocabulary.go @@ -2,10 +2,12 @@ package runs import ( "context" + "encoding/json/jsontext" json "encoding/json/v2" "errors" "fmt" "slices" + "strings" "time" "github.com/google/jsonschema-go/jsonschema" @@ -89,9 +91,7 @@ func define[T any](name, title string, valid func(T) error, describe func(T) str var stepTypes = vocabulary( define(typeAgent, "Run an agent", agentSettings.valid, agentSettings.describe, runAgent), define(typeAction, "Run a connector action", actionSettings.valid, actionSettings.describe, runAction), - define(typeApproval, "Wait for approval", noSettings.valid, func(noSettings) string { - return "Requests approval for actions held by judgement and runs approved actions" - }, runApprovalWait), + define(typeApproval, "Wait for approval", approvalSettings.valid, approvalSettings.describe, runApprovalWait), define(typeNotify, "Report the findings", notifySettings.valid, notifySettings.describe, runNotify), define(typeSleep, "Wait", sleepSettings.valid, sleepSettings.describe, runSleep), define(typeFinish, "Finish", finishSettings.valid, finishSettings.describe, runFinish), @@ -176,9 +176,33 @@ func (s actionSettings) describe() string { return fmt.Sprintf("Submits %s %s for judgement and runs it if allowed to run unattended", s.Connector, s.Name) } -type noSettings struct{} +// approvalSettings decide what one approval covers. Without covers it asks +// about the actions judgement held before it; with covers it asks once about +// the named steps, which run later under that one approval. +type approvalSettings struct { + Covers []string `yaml:"covers,omitempty" json:"covers,omitempty" jsonschema:"the ids of the steps this approval covers, in the order they run"` +} -func (noSettings) valid() error { return nil } +func (s approvalSettings) valid() error { + seen := make(map[string]bool, len(s.Covers)) + for _, id := range s.Covers { + if id == "" { + return errors.New("covers names the id of each step this approval covers") + } + if seen[id] { + return fmt.Errorf("covers names step %q twice", id) + } + seen[id] = true + } + return nil +} + +func (s approvalSettings) describe() string { + if len(s.Covers) == 0 { + return "Requests approval for actions held by judgement and runs approved actions" + } + return "Asks once to approve " + strings.Join(s.Covers, ", then ") + ", and runs each as approved" +} type notifySettings struct { Title string `yaml:"title,omitempty" json:"title,omitempty"` @@ -209,16 +233,40 @@ func (s sleepSettings) duration() time.Duration { return d } -// runAction executes only actions allowed to run unattended. A later -// approval step handles actions held for approval. -func runAction(d Deps, rc *Context, p *progress, name string, s actionSettings) (StepResult, error) { +// actionInput is an action step's input as JSON: the judged input, with an +// empty object for a step that names none. +func actionInput(s actionSettings) (jsontext.Value, error) { input := s.Input if input == nil { input = map[string]any{} } in, err := json.Marshal(input, json.Deterministic(true)) if err != nil { - return StepResult{}, fmt.Errorf("step %q: encode input: %w", name, err) + return nil, fmt.Errorf("encode input: %w", err) + } + return in, nil +} + +// ranStep is what a step reports for the action it was judged for: the same +// shape whether or not an approval covered it, so a later step reads +// steps..result either way. +func ranStep(level string, out approvalOutcome) StepResult { + return StepResult{ + Summary: firstText(out.Error, out.Result, out.State), + Result: map[string]any{"level": level, "state": out.State, "result": out.Result, "error": out.Error, "unknown": out.Unknown}, + } +} + +// runAction executes only actions allowed to run unattended, and the steps an +// earlier approval covers. A later approval step handles actions held for +// approval. +func runAction(d Deps, rc *Context, p *progress, name string, s actionSettings) (StepResult, error) { + if seq, i := p.covered(name); seq != nil { + return d.runCovered(rc, p, seq, i) + } + in, err := actionInput(s) + if err != nil { + return StepResult{}, fmt.Errorf("step %q: %w", name, err) } decision, err := rc.Step("judge:"+name, func(ctx context.Context, key string) (judgement.Decision, error) { return d.Judge.Assess(ctx, rc.request(key, s.Connector, s.Name, in)) @@ -238,13 +286,15 @@ func runAction(d Deps, rc *Context, p *progress, name string, s actionSettings) out.Result, out.Error, out.Unknown = runJudged(rc, d.Judge, decision, nil) p.outcomes = append(p.outcomes, out) p.stopped = p.stopped || out.Unknown - return StepResult{ - Summary: firstText(out.Error, out.Result, out.State), - Result: map[string]any{"level": level, "state": out.State, "result": out.Result, "error": out.Error, "unknown": out.Unknown}, - }, nil + return ranStep(level, out), nil } -func runApprovalWait(d Deps, rc *Context, p *progress, _ string, _ noSettings) (StepResult, error) { +func runApprovalWait(d Deps, rc *Context, p *progress, name string, s approvalSettings) (StepResult, error) { + // A dry run asks nobody, so it has nothing to cover up front: each covered + // step is judged at its own place instead. + if len(s.Covers) > 0 && !rc.Dry() { + return d.approveCovered(rc, p, name, s.Covers) + } out, err := d.settle(rc, p) if err != nil { return StepResult{}, err diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index f002f67d8..46f3c219e 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -845,6 +845,8 @@ export interface RunAction { rejudged?: Decision; approval?: Approval; effect?: { state: string; output?: string; error?: string; at?: string }; + /** Why an action of a sequence stopped the rest of it. */ + stop?: string; } export interface RunEntry { diff --git a/ui/src/pages/runs/[id].vue b/ui/src/pages/runs/[id].vue index c2c16bd08..15950f9be 100644 --- a/ui/src/pages/runs/[id].vue +++ b/ui/src/pages/runs/[id].vue @@ -25,13 +25,14 @@ import { Skeleton } from "@/components/ui/skeleton"; import { StatusDot } from "@/components/ui/status-dot"; import { Timestamp } from "@/components/ui/timestamp"; import { errors } from "@/copy/errors"; -import { api, describeError, type RunAction, type RunEntry, type RunStage } from "@/lib/api"; +import { api, describeError, type Approval, type RunAction, type RunEntry, type RunStage } from "@/lib/api"; import { duration, emptyValue } from "@/lib/format"; import AgentTranscript from "@/workflows/AgentTranscript.vue"; import UserReference from "@/org/UserReference.vue"; import { usePoll, useRead } from "@/lib/use-read"; import { useLiveResource } from "@/stores/session"; import ApprovalsSection from "@/runs/ApprovalsSection.vue"; +import { coveredSteps, coversSequence } from "@/runs/sequence"; import { ended, stateLabel, stateTone } from "@/runs/state"; /** A run's decision trail: where it came from, each action it asked to take @@ -140,6 +141,23 @@ const result = computed(() => { const value = data.value?.run.result; return emptyValue(value) ? "" : JSON.stringify(value, null, 2); }); + +/* An approval that covers several actions is shown once, in the order it + * covers them, so the trail says which of them ran. Its actions are not + * listed again on their own. */ +const sequences = computed(() => { + const trail = data.value?.actions ?? []; + const requests = new Map(); + for (const action of trail) { + if (action.approval && coversSequence(action.approval)) requests.set(action.approval.id, action.approval); + } + const ended = !!data.value?.run.finished_at; + return [...requests.values()].map((request) => ({ request, steps: coveredSteps(request, trail, ended) })); +}); +const alone = computed(() => { + const covered = new Set(sequences.value.flatMap((sequence) => sequence.steps.map((step) => step.decisionId))); + return (data.value?.actions ?? []).filter((action) => !covered.has(action.decision.id)); +});