diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index 26fd2dd6a..0dc3b5ca3 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -22,6 +22,7 @@ import ( "github.com/samcharles93/archie-core/internal/platform/httpjson" "github.com/samcharles93/archie-core/internal/platform/hub" "github.com/samcharles93/archie-core/internal/platform/pg" + "github.com/samcharles93/archie-core/modules/approvals" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/dashboard" "github.com/samcharles93/archie-core/modules/deliveries" @@ -84,7 +85,11 @@ func Run(ctx context.Context, configPath string) error { // from the request. judge := judgement.NewModule(db, log.With("module", "judgement"), orgID, conns, nil, []judgement.Guard{judgement.Reversibility{}, judgement.Precedent{}}) - engine.Register("investigate", runs.Investigate(settings, conns, judge, tell)) //nolint:contextcheck // see above + // An approval request is carried by deliveries, and its answer wakes the run + // that is waiting on it. + allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, engine) + allow.Routes(mux, guard) + engine.Register("investigate", runs.Investigate(settings, conns, judge, allow, tell)) //nolint:contextcheck // see above hear := events.NewModule(db, log.With("module", "events"), orgID, conns, engine) hear.Routes(mux, guard) @@ -107,7 +112,7 @@ func Run(ctx context.Context, configPath string) error { const orgID = "default" // schemas are the module schemas the runtime role is granted DML on. -var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement"} +var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement", "approvals"} // owner names this process in run leases. func owner() string { diff --git a/internal/platform/pg/migrations/00009_approvals_requests.sql b/internal/platform/pg/migrations/00009_approvals_requests.sql new file mode 100644 index 000000000..53e3889cb --- /dev/null +++ b/internal/platform/pg/migrations/00009_approvals_requests.sql @@ -0,0 +1,28 @@ +-- +goose Up +CREATE SCHEMA approvals; + +-- A request is one judged action waiting for a person's answer. key is the run +-- wait an answer wakes, and the decision columns bind the answer to the action +-- that was judged, so it can't be replayed onto another one. +CREATE TABLE approvals.requests ( + id uuid PRIMARY KEY, + org_id text NOT NULL, + run_id uuid NOT NULL, + key text NOT NULL, + decision_id uuid NOT NULL, + digest text NOT NULL, + level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')), + summary text NOT NULL, + state text NOT NULL CHECK (state IN ('pending', 'approved', 'denied', 'expired')), + deadline timestamptz NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + answered_at timestamptz, + answered_by text, + answered_via text, + UNIQUE (org_id, run_id, key) +); + +CREATE INDEX requests_by_state ON approvals.requests (org_id, state, created_at); + +-- +goose Down +DROP SCHEMA approvals CASCADE; diff --git a/internal/platform/pg/migrations/00010_deliveries_approval_requests.sql b/internal/platform/pg/migrations/00010_deliveries_approval_requests.sql new file mode 100644 index 000000000..cb571f1e4 --- /dev/null +++ b/internal/platform/pg/migrations/00010_deliveries_approval_requests.sql @@ -0,0 +1,15 @@ +-- +goose Up +-- An approval request is a message a person answers, so a message grows the +-- request it carries and when that request runs out of time. +ALTER TABLE deliveries.messages DROP CONSTRAINT messages_kind_check; +ALTER TABLE deliveries.messages ADD CONSTRAINT messages_kind_check + CHECK (kind IN ('notification', 'approval_request', 'approval_answer')); +ALTER TABLE deliveries.messages ADD COLUMN request_id uuid; +ALTER TABLE deliveries.messages ADD COLUMN expires_at timestamptz; + +-- +goose Down +ALTER TABLE deliveries.messages DROP COLUMN expires_at; +ALTER TABLE deliveries.messages DROP COLUMN request_id; +ALTER TABLE deliveries.messages DROP CONSTRAINT messages_kind_check; +ALTER TABLE deliveries.messages ADD CONSTRAINT messages_kind_check + CHECK (kind IN ('notification')); diff --git a/internal/platform/pg/migrations/00011_governance_settings.sql b/internal/platform/pg/migrations/00011_governance_settings.sql new file mode 100644 index 000000000..96f370462 --- /dev/null +++ b/internal/platform/pg/migrations/00011_governance_settings.sql @@ -0,0 +1,12 @@ +-- +goose Up +-- An organisation's settings are one row: what Archie does when nobody has +-- decided otherwise. A missing row means every field keeps its default. +CREATE TABLE governance.settings ( + org_id text PRIMARY KEY, + -- approval_deadline is how long an approval request waits for an answer. + approval_deadline interval NOT NULL, + updated_at timestamptz NOT NULL DEFAULT now() +); + +-- +goose Down +DROP TABLE governance.settings; diff --git a/internal/platform/pg/migrations/00012_governance_approval_deadline_ms.sql b/internal/platform/pg/migrations/00012_governance_approval_deadline_ms.sql new file mode 100644 index 000000000..caabfcf97 --- /dev/null +++ b/internal/platform/pg/migrations/00012_governance_approval_deadline_ms.sql @@ -0,0 +1,11 @@ +-- +goose Up +-- A Postgres interval scans as text, so it can't be read straight into a Go +-- duration. Milliseconds are exact and scan as a number. The default fills a +-- row written before this change; it is dropped straight after. +ALTER TABLE governance.settings DROP COLUMN approval_deadline; +ALTER TABLE governance.settings ADD COLUMN approval_deadline_ms bigint NOT NULL DEFAULT 86400000; +ALTER TABLE governance.settings ALTER COLUMN approval_deadline_ms DROP DEFAULT; + +-- +goose Down +ALTER TABLE governance.settings DROP COLUMN approval_deadline_ms; +ALTER TABLE governance.settings ADD COLUMN approval_deadline interval NOT NULL DEFAULT '24 hours'; diff --git a/internal/platform/pg/migrations/00013_approvals_request_action.sql b/internal/platform/pg/migrations/00013_approvals_request_action.sql new file mode 100644 index 000000000..b052f2a09 --- /dev/null +++ b/internal/platform/pg/migrations/00013_approvals_request_action.sql @@ -0,0 +1,17 @@ +-- +goose Up +-- A request is read back without the decision it came from, so it keeps the +-- action's own names: what the person is shown has to survive a restart. +ALTER TABLE approvals.requests ADD COLUMN connector text NOT NULL DEFAULT ''; +ALTER TABLE approvals.requests ADD COLUMN action text NOT NULL DEFAULT ''; +ALTER TABLE approvals.requests ADD COLUMN target_kind text NOT NULL DEFAULT ''; +ALTER TABLE approvals.requests ADD COLUMN target_id text NOT NULL DEFAULT ''; +ALTER TABLE approvals.requests ALTER COLUMN connector DROP DEFAULT; +ALTER TABLE approvals.requests ALTER COLUMN action DROP DEFAULT; +ALTER TABLE approvals.requests ALTER COLUMN target_kind DROP DEFAULT; +ALTER TABLE approvals.requests ALTER COLUMN target_id DROP DEFAULT; + +-- +goose Down +ALTER TABLE approvals.requests DROP COLUMN connector; +ALTER TABLE approvals.requests DROP COLUMN action; +ALTER TABLE approvals.requests DROP COLUMN target_kind; +ALTER TABLE approvals.requests DROP COLUMN target_id; diff --git a/internal/platform/prompts/investigate.md b/internal/platform/prompts/investigate.md index 798760302..ab4b6f501 100644 --- a/internal/platform/prompts/investigate.md +++ b/internal/platform/prompts/investigate.md @@ -10,9 +10,10 @@ guess at facts a tool could tell you, and don't call a tool to learn something you already know. Some of your tools act instead of reading. Judgement checks an action against -the organisation's rules before it runs, so calling one commits nothing. -When your investigation points at an action, call it with the target you -picked rather than only describing it: that call is what gets it judged. +the organisation's rules before it runs, so calling one commits nothing. When +an action is held, it is put to a person when your investigation ends and the +run waits for their answer, so call the action you recommend with the target +you picked rather than only describing it. The event is a claim, not a fact. Check it against what you measure, and if they disagree (an alert says a disk is full and it is at 40%), say so first: @@ -38,7 +39,7 @@ When you're done, reply with your findings in plain text: - The likely cause, and how sure you are. - The evidence: what you looked at and what it showed. - What should happen next, naming the action and its target precisely. Say what - judgement answered if you called it. Don't claim an action ran unless the call - came back having run it. + judgement answered if you called it. Don't claim a call you didn't make: only + a tool call counts, and a failed one says so. If you couldn't find out, say what you tried and what is missing. diff --git a/modules/approvals/approvals.go b/modules/approvals/approvals.go new file mode 100644 index 000000000..670ddf901 --- /dev/null +++ b/modules/approvals/approvals.go @@ -0,0 +1,363 @@ +// Package approvals owns an approval request: one judged action waiting for a +// person's answer, and the answer that settles it. A request is made when +// judgement holds an action at propose and wait, and an answer is an event in: +// it wakes the run waiting on that key, which then runs the action only if the +// answer named the exact action that was judged. +// +// The request binds to the decision and its digest, so an approval covers the +// action that was shown and nothing else. +package approvals + +import ( + "context" + "encoding/json/jsontext" + json "encoding/json/v2" + "errors" + "fmt" + "log/slog" + "net/http" + "strings" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + + "github.com/samcharles93/archie-core/internal/platform/httpjson" + "github.com/samcharles93/archie-core/modules/approvals/internal/store" + "github.com/samcharles93/archie-core/modules/deliveries" + "github.com/samcharles93/archie-core/modules/judgement" +) + +// The states a request can be in. A settled request never changes again. +const ( + StatePending = "pending" + StateApproved = "approved" + StateDenied = "denied" + StateExpired = "expired" +) + +var ( + // ErrNotFound means no request has that id. + ErrNotFound = store.ErrNotFound + // ErrAnswered means the request was already settled. + ErrAnswered = errors.New("that request was already answered") + // ErrExpired means the answer arrived after the request's deadline. + ErrExpired = errors.New("that request has expired") +) + +// Request is one judged action waiting for a person's answer. +type Request struct { + ID uuid.UUID + RunID uuid.UUID + // Key is the run's wait key, stored so an answer knows what to wake. + Key string + Decision judgement.Decision + Connector string + Action string + TargetKind string + TargetID string + Level string + Summary string + State string + Deadline time.Time + AnsweredAt time.Time + AnsweredBy string + AnsweredVia string +} + +// Answer is what the run wakes with. +type Answer struct { + RequestID uuid.UUID `json:"request_id"` + Approved bool `json:"approved"` + By string `json:"by"` + Via string `json:"via"` + At time.Time `json:"at"` +} + +// Approval is the authority this answer gives judgement to run the action. +func (a Answer) Approval(d judgement.Decision) judgement.Approval { + return judgement.Approval{DecisionID: d.ID, Digest: d.Action.Digest, By: a.By, At: a.At} +} + +// View is a request as the API shows it. +type View struct { + ID uuid.UUID `json:"id"` + RunID uuid.UUID `json:"run_id"` + Action string `json:"action"` + Target string `json:"target"` + Level string `json:"level"` + Summary string `json:"summary"` + State string `json:"state"` + Deadline time.Time `json:"deadline"` + AnsweredBy string `json:"answered_by,omitzero"` +} + +// View is r as the API shows it. +func (r Request) View() View { + return View{ + ID: r.ID, 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, AnsweredBy: r.AnsweredBy, + } +} + +// Signaller wakes a run waiting on a key. +type Signaller interface { + Signal(ctx context.Context, id uuid.UUID, key string, payload jsontext.Value) error +} + +// Delivery carries a request to every channel someone can answer on. +type Delivery interface { + Ask(ctx context.Context, a deliveries.ApprovalRequest) error + Told(ctx context.Context, a deliveries.ApprovalRequest, answer string) error +} + +// Module owns one organisation's approval requests. +type Module struct { + orgID string + store *store.Store + tell Delivery + wake Signaller + log *slog.Logger + now func() time.Time +} + +// NewModule returns the approvals module for orgID. Answers are delivered by +// tell and wake the run through wake. +func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake Signaller) *Module { + return &Module{orgID: orgID, store: store.New(db), tell: tell, wake: wake, log: log, now: time.Now} +} + +// Ask records a request for d and tells people about it. Asking again for the +// same run and key returns the request that stands, so a replayed step asks +// once. +func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgement.Decision, deadline time.Time) (Request, error) { + row, err := m.store.Put(ctx, store.Request{ + ID: uuid.New(), OrgID: m.orgID, RunID: runID, Key: key, + DecisionID: d.ID, Digest: d.Action.Digest, Level: d.Level.String(), + Connector: d.Action.Connector, Action: d.Action.Name, + TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID, + Summary: Summary(d), State: StatePending, Deadline: deadline.UTC(), + }) + if err != nil { + return Request{}, err + } + r := requestOf(row, d) + if row.State != StatePending { + return r, nil + } + 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, + Body: r.Summary, ExpiresAt: r.Deadline, + }); err != nil { + return Request{}, fmt.Errorf("send approval request: %w", err) + } + return r, nil +} + +// Answer settles request id with a person's decision and wakes the run waiting +// on it. Only a pending request settles: a second answer, or one that arrives +// after the deadline, is refused and wakes nobody. +func (m *Module) Answer(ctx context.Context, id uuid.UUID, by, via string, approved bool) (Request, error) { + now := m.now().UTC() + if _, err := m.pending(ctx, id, now); err != nil { + return Request{}, err + } + state := StateDenied + if approved { + state = StateApproved + } + row, err := m.store.Answer(ctx, m.orgID, id, state, by, via, now) + if err != nil { + return Request{}, err + } + if row.State != state { + return Request{}, fmt.Errorf("%w: %s", ErrAnswered, row.State) + } + answer := Answer{RequestID: row.ID, Approved: approved, By: by, Via: via, At: now} + if err := m.wakeWith(ctx, row, answer); err != nil { + return Request{}, err + } + return requestOf(row, judgement.Decision{}), nil +} + +// Expire settles a request whose deadline passed, so the trail shows why it +// never ran. +func (m *Module) Expire(ctx context.Context, id uuid.UUID) error { + row, err := m.store.Answer(ctx, m.orgID, id, StateExpired, "deadline", "clock", m.now().UTC()) + if err != nil { + if errors.Is(err, ErrNotFound) { + return nil + } + return err + } + if row.State != StateExpired { + return nil + } + m.log.InfoContext(ctx, "approval request expired", "request", row.ID, "run", row.RunID) + return m.tell.Told(ctx, deliveries.ApprovalRequest{ + RunID: row.RunID, RequestID: row.ID, Key: row.Key + ":ask", + Title: "Approval expired", Body: "The request ran out of time, so nothing was run.", + }, "Expired without an answer.") +} + +// Pending returns the requests waiting for an answer, oldest first. +func (m *Module) Pending(ctx context.Context) ([]Request, error) { + rows, err := m.store.Pending(ctx, m.orgID) + if err != nil { + return nil, err + } + out := make([]Request, 0, len(rows)) + for _, row := range rows { + out = append(out, requestOf(row, judgement.Decision{})) + } + return out, nil +} + +// Routes adds the approvals API to mux behind guard. +func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) { + mux.Handle("GET /api/approvals", guard(http.HandlerFunc(m.list))) + mux.Handle("POST /api/approvals/{id}/answer", guard(http.HandlerFunc(m.answer))) +} + +// bootstrapAdmin names the identity the bootstrap admin token stands for. It +// is recorded as the approver until identities exist. +const bootstrapAdmin = "admin" + +type answerRequest struct { + Approved bool `json:"approved"` +} + +func (m *Module) list(w http.ResponseWriter, r *http.Request) { + pending, err := m.Pending(r.Context()) + if err != nil { + m.log.ErrorContext(r.Context(), "list approvals", "error", err) + httpjson.Error(w, http.StatusInternalServerError, "couldn't list approvals") + return + } + out := make([]View, 0, len(pending)) + for _, p := range pending { + out = append(out, p.View()) + } + httpjson.Write(w, http.StatusOK, out) +} + +func (m *Module) answer(w http.ResponseWriter, r *http.Request) { + id, err := uuid.Parse(r.PathValue("id")) + if err != nil { + httpjson.Error(w, http.StatusBadRequest, "id is a request id") + return + } + var req answerRequest + if err := httpjson.Read(r, &req); err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + out, err := m.Answer(r.Context(), id, bootstrapAdmin, "composer", req.Approved) + switch { + case errors.Is(err, ErrNotFound): + httpjson.Error(w, http.StatusNotFound, "no such approval request") + return + case errors.Is(err, ErrAnswered), errors.Is(err, ErrExpired): + httpjson.Error(w, http.StatusConflict, err.Error()) + return + case err != nil: + m.log.ErrorContext(r.Context(), "answer approval", "request", id, "error", err) + httpjson.Error(w, http.StatusInternalServerError, "couldn't record the answer") + return + } + httpjson.Write(w, http.StatusOK, out.View()) +} + +// pending reads a request that is still open and inside its deadline. The +// store settles only a pending row; this refuses the answer before that, with +// the reason. +func (m *Module) pending(ctx context.Context, id uuid.UUID, now time.Time) (store.Request, error) { + row, err := m.store.ByID(ctx, m.orgID, id) + if err != nil { + return store.Request{}, err + } + if err := settleable(row, now); err != nil { + return store.Request{}, err + } + return row, nil +} + +// settleable says whether an answer now may settle r. A request settles once: +// a second answer, and one that arrives after the deadline, changes nothing. +func settleable(r store.Request, now time.Time) error { + switch { + case r.State != StatePending: + return fmt.Errorf("%w: %s", ErrAnswered, r.State) + case !now.Before(r.Deadline): + return ErrExpired + } + return nil +} + +func (m *Module) wakeWith(ctx context.Context, row store.Request, answer Answer) error { + payload, err := json.Marshal(answer) + if err != nil { + return fmt.Errorf("encode answer: %w", err) + } + if err := m.wake.Signal(ctx, row.RunID, row.Key, payload); err != nil { + return fmt.Errorf("wake run %s: %w", row.RunID, err) + } + return m.tell.Told(ctx, deliveries.ApprovalRequest{ + RunID: row.RunID, RequestID: row.ID, Key: row.Key + ":ask", + Title: "Approval answered", Body: answerText(answer), + }, answerText(answer)) +} + +func answerText(a Answer) string { + verb := "Denied" + if a.Approved { + verb = "Approved" + } + return fmt.Sprintf("%s by %s on the %s.", verb, a.By, a.Via) +} + +// Summary is what a person is shown about the action they are asked to allow: +// what it does, to what, and what held it back. +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) + if d.Action.Effect.Summary != "" { + s += " " + d.Action.Effect.Summary + } + var held strings.Builder + for _, v := range d.Verdicts { + if v.Advisory || v.Ceiling != d.Level { + continue + } + for _, f := range v.Findings { + fmt.Fprintf(&held, "\n- %s: %s", v.Guard, f.Text) + } + if v.Failed != "" { + fmt.Fprintf(&held, "\n- %s: couldn't judge: %s", v.Guard, v.Failed) + } + } + if held.String() != "" { + s += "\nHeld because:" + held.String() + } + return s +} + +// requestOf is a stored row as the module's Request. +func requestOf(row store.Request, d judgement.Decision) Request { + r := Request{ + ID: row.ID, RunID: row.RunID, Key: row.Key, Decision: d, + Connector: row.Connector, Action: row.Action, TargetKind: row.TargetKind, TargetID: row.TargetID, + Level: row.Level, Summary: row.Summary, State: row.State, Deadline: row.Deadline, + } + if row.AnsweredAt.Valid { + r.AnsweredAt = row.AnsweredAt.Time + } + if row.AnsweredBy.Valid { + r.AnsweredBy = row.AnsweredBy.String + } + if row.AnsweredVia.Valid { + r.AnsweredVia = row.AnsweredVia.String + } + return r +} diff --git a/modules/approvals/approvals_test.go b/modules/approvals/approvals_test.go new file mode 100644 index 000000000..dfffbb1a0 --- /dev/null +++ b/modules/approvals/approvals_test.go @@ -0,0 +1,38 @@ +package approvals + +import ( + "errors" + "testing" + "time" + + "github.com/samcharles93/archie-core/modules/approvals/internal/store" +) + +// TestSettleableRefusesASecondAnswerOrALateOne guards the rule that makes an +// approval one decision: the first answer settles a request, so a replaying +// answer or one that arrives after the deadline wakes no run and runs nothing. +func TestSettleableRefusesASecondAnswerOrALateOne(t *testing.T) { + deadline := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC) + request := func(state string) store.Request { + return store.Request{State: state, Deadline: deadline} + } + tests := []struct { + name string + row store.Request + now time.Time + wantErr error + }{ + {name: "a pending request settles inside its deadline", row: request(StatePending), now: deadline.Add(-time.Minute)}, + {name: "a pending request is too late after its deadline", row: request(StatePending), now: deadline, wantErr: ErrExpired}, + {name: "an approved request doesn't settle again", row: request(StateApproved), now: deadline.Add(-time.Minute), wantErr: ErrAnswered}, + {name: "a denied request doesn't settle again", row: request(StateDenied), now: deadline.Add(-time.Minute), wantErr: ErrAnswered}, + {name: "an expired request doesn't settle", row: request(StateExpired), now: deadline.Add(-time.Minute), wantErr: ErrAnswered}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := settleable(tt.row, tt.now); !errors.Is(err, tt.wantErr) { + t.Fatalf("err = %v, want %v", err, tt.wantErr) + } + }) + } +} diff --git a/modules/approvals/internal/store/store.go b/modules/approvals/internal/store/store.go new file mode 100644 index 000000000..ba241b58f --- /dev/null +++ b/modules/approvals/internal/store/store.go @@ -0,0 +1,129 @@ +// Package store holds the approvals module's SQL: the requests waiting for an +// answer, and what was answered. +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" +) + +// Request is one judged action waiting for a person's answer. +type Request struct { + ID uuid.UUID `db:"id"` + OrgID string `db:"org_id"` + RunID uuid.UUID `db:"run_id"` + Key string `db:"key"` + DecisionID uuid.UUID `db:"decision_id"` + Digest string `db:"digest"` + // The action's own names, kept so a request reads back without its + // decision. + Connector string `db:"connector"` + Action string `db:"action"` + TargetKind string `db:"target_kind"` + TargetID string `db:"target_id"` + Level string `db:"level"` + Summary string `db:"summary"` + State string `db:"state"` + Deadline time.Time `db:"deadline"` + CreatedAt time.Time `db:"created_at"` + AnsweredAt sql.NullTime `db:"answered_at"` + AnsweredBy sql.NullString `db:"answered_by"` + AnsweredVia sql.NullString `db:"answered_via"` +} + +// Store is the approvals module's Postgres store. +type Store struct { + db *sqlx.DB +} + +// New returns a store on db. +func New(db *sqlx.DB) *Store { return &Store{db: db} } + +const requestColumns = `id, org_id, run_id, key, decision_id, digest, connector, action, target_kind, + target_id, level, summary, state, deadline, created_at, answered_at, answered_by, answered_via` + +// Put records r unless a request already exists for its run and key, and +// returns the request that stands either way. +func (s *Store) Put(ctx context.Context, r Request) (Request, error) { + var out Request + err := s.db.GetContext(ctx, &out, ` + INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, digest, connector, action, + target_kind, target_id, level, summary, state, deadline) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) + ON CONFLICT (org_id, run_id, key) DO NOTHING + RETURNING `+requestColumns, + r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.Digest, r.Connector, r.Action, r.TargetKind, + r.TargetID, r.Level, r.Summary, r.State, r.Deadline) + if errors.Is(err, sql.ErrNoRows) { + return s.Get(ctx, r.OrgID, r.RunID, r.Key) + } + if err != nil { + return Request{}, fmt.Errorf("put request: %w", err) + } + return out, nil +} + +// Get returns the request for one run's key. +func (s *Store) Get(ctx context.Context, orgID string, runID uuid.UUID, key string) (Request, error) { + var out Request + if err := s.db.GetContext(ctx, &out, ` + SELECT `+requestColumns+` FROM approvals.requests + WHERE org_id = $1 AND run_id = $2 AND key = $3`, orgID, runID, key); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return Request{}, ErrNotFound + } + return Request{}, fmt.Errorf("read request: %w", err) + } + return out, nil +} + +// Answer settles one request, and only while it is still pending. It returns +// the request as it now stands, or the one that already settled it. +func (s *Store) Answer(ctx context.Context, orgID string, id uuid.UUID, state, by, via string, at time.Time) (Request, error) { + var out Request + err := s.db.GetContext(ctx, &out, ` + UPDATE approvals.requests + SET state = $3, answered_at = $4, answered_by = $5, answered_via = $6 + WHERE org_id = $1 AND id = $2 AND state = 'pending' + RETURNING `+requestColumns, orgID, id, state, at, by, via) + if errors.Is(err, sql.ErrNoRows) { + return s.ByID(ctx, orgID, id) + } + if err != nil { + return Request{}, fmt.Errorf("answer request: %w", err) + } + return out, nil +} + +// ByID returns one request. +func (s *Store) ByID(ctx context.Context, orgID string, id uuid.UUID) (Request, error) { + var out Request + if err := s.db.GetContext(ctx, &out, ` + SELECT `+requestColumns+` FROM approvals.requests WHERE org_id = $1 AND id = $2`, orgID, id); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return Request{}, ErrNotFound + } + return Request{}, fmt.Errorf("read request: %w", err) + } + return out, nil +} + +// Pending returns the requests still waiting for an answer, oldest first. +func (s *Store) Pending(ctx context.Context, orgID string) ([]Request, error) { + var out []Request + if err := s.db.SelectContext(ctx, &out, ` + SELECT `+requestColumns+` FROM approvals.requests + WHERE org_id = $1 AND state = 'pending' ORDER BY created_at`, orgID); err != nil { + return nil, fmt.Errorf("list pending requests: %w", err) + } + return out, nil +} + +// ErrNotFound means no request has that id or key. +var ErrNotFound = errors.New("no such approval request") diff --git a/modules/deliveries/deliveries.go b/modules/deliveries/deliveries.go index f239cc260..312b40865 100644 --- a/modules/deliveries/deliveries.go +++ b/modules/deliveries/deliveries.go @@ -7,6 +7,7 @@ package deliveries import ( "context" + "database/sql" "errors" "fmt" "log/slog" @@ -29,6 +30,16 @@ const ( heartbeat = 25 * time.Second ) +// The kinds of message a channel carries. +const ( + // KindNotification tells people what happened or was done. + KindNotification = "notification" + // KindApprovalRequest is an action waiting for someone's answer. + KindApprovalRequest = "approval_request" + // KindApprovalAnswer records what they answered. + KindApprovalAnswer = "approval_answer" +) + // Notification is something a run tells people: what happened, what was done, // what is needed. type Notification struct { @@ -40,14 +51,29 @@ type Notification struct { Body string } +// ApprovalRequest is one judged action waiting for a person's answer. It is +// carried like a notification, with the request an answer names and the time +// it runs out. +type ApprovalRequest struct { + RunID uuid.UUID + RequestID uuid.UUID + // Key makes the request idempotent, as a notification's does. + Key string + Title string + Body string + ExpiresAt time.Time +} + // Message is a composer message as the API shows it. type Message struct { Seq int64 `json:"seq"` ID uuid.UUID `json:"id"` Kind string `json:"kind"` RunID *uuid.UUID `json:"run_id,omitzero"` + RequestID *uuid.UUID `json:"request_id,omitzero"` Title string `json:"title"` Body string `json:"body"` + ExpiresAt *time.Time `json:"expires_at,omitzero"` CreatedAt time.Time `json:"created_at"` } @@ -71,10 +97,39 @@ func (m *Module) Notify(ctx context.Context, n Notification) error { if n.Key == "" { return errors.New("a notification needs a key") } - seq, created, err := m.store.Insert(ctx, store.Message{ - ID: uuid.New(), OrgID: m.orgID, Channel: channelComposer, Kind: "notification", - RunID: uuid.NullUUID{UUID: n.RunID, Valid: n.RunID != uuid.Nil}, Title: n.Title, Body: n.Body, Key: n.Key, + return m.send(ctx, store.Message{ + ID: uuid.New(), Kind: KindNotification, RunID: uuid.NullUUID{UUID: n.RunID, Valid: n.RunID != uuid.Nil}, + Title: n.Title, Body: n.Body, Key: n.Key, }) +} + +// Ask delivers an approval request on every channel. Asking again for the same +// key changes nothing. +func (m *Module) Ask(ctx context.Context, a ApprovalRequest) error { + if a.Key == "" { + return errors.New("an approval request needs a key") + } + return m.send(ctx, store.Message{ + ID: uuid.New(), Kind: KindApprovalRequest, RunID: uuid.NullUUID{UUID: a.RunID, Valid: a.RunID != uuid.Nil}, + RequestID: uuid.NullUUID{UUID: a.RequestID, Valid: a.RequestID != uuid.Nil}, + Title: a.Title, Body: a.Body, Key: a.Key, ExpiresAt: sql.NullTime{Time: a.ExpiresAt, Valid: !a.ExpiresAt.IsZero()}, + }) +} + +// Told records what someone answered, so the composer shows the answer beside +// the request it settles. +func (m *Module) Told(ctx context.Context, a ApprovalRequest, answer string) error { + return m.send(ctx, store.Message{ + ID: uuid.New(), Kind: KindApprovalAnswer, RunID: uuid.NullUUID{UUID: a.RunID, Valid: a.RunID != uuid.Nil}, + RequestID: uuid.NullUUID{UUID: a.RequestID, Valid: a.RequestID != uuid.Nil}, + Title: a.Title, Body: answer, Key: a.Key + ":answer", + }) +} + +// send writes msg to every channel and wakes the composer's readers. +func (m *Module) send(ctx context.Context, msg store.Message) error { + msg.OrgID, msg.Channel = m.orgID, channelComposer + seq, created, err := m.store.Insert(ctx, msg) if err != nil { return err } @@ -117,6 +172,12 @@ func (m *Module) messages(w http.ResponseWriter, r *http.Request) { if row.RunID.Valid { msg.RunID = &row.RunID.UUID } + if row.RequestID.Valid { + msg.RequestID = &row.RequestID.UUID + } + if row.ExpiresAt.Valid { + msg.ExpiresAt = &row.ExpiresAt.Time + } out = append(out, msg) } httpjson.Write(w, http.StatusOK, out) diff --git a/modules/deliveries/internal/store/store.go b/modules/deliveries/internal/store/store.go index 3ba294bca..5c3a789a4 100644 --- a/modules/deliveries/internal/store/store.go +++ b/modules/deliveries/internal/store/store.go @@ -13,17 +13,21 @@ import ( "github.com/jmoiron/sqlx" ) -// Message is one notification on one channel. +// Message is one notification or approval request on one channel. type Message struct { - Seq int64 `db:"seq"` - ID uuid.UUID `db:"id"` - OrgID string `db:"org_id"` - Channel string `db:"channel"` - Kind string `db:"kind"` - RunID uuid.NullUUID `db:"run_id"` - Title string `db:"title"` - Body string `db:"body"` - Key string `db:"key"` + Seq int64 `db:"seq"` + ID uuid.UUID `db:"id"` + OrgID string `db:"org_id"` + Channel string `db:"channel"` + Kind string `db:"kind"` + RunID uuid.NullUUID `db:"run_id"` + Title string `db:"title"` + Body string `db:"body"` + Key string `db:"key"` + // RequestID is the approval request a person answers, on a message that + // carries one. + RequestID uuid.NullUUID `db:"request_id"` + ExpiresAt sql.NullTime `db:"expires_at"` CreatedAt time.Time `db:"created_at"` } @@ -40,10 +44,10 @@ func New(db *sqlx.DB) *Store { return &Store{db: db} } func (s *Store) Insert(ctx context.Context, m Message) (int64, bool, error) { var seq int64 err := s.db.GetContext(ctx, &seq, ` - INSERT INTO deliveries.messages (id, org_id, channel, kind, run_id, title, body, key) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + INSERT INTO deliveries.messages (id, org_id, channel, kind, run_id, title, body, key, request_id, expires_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) ON CONFLICT (org_id, channel, key) DO NOTHING - RETURNING seq`, m.ID, m.OrgID, m.Channel, m.Kind, m.RunID, m.Title, m.Body, m.Key) + RETURNING seq`, m.ID, m.OrgID, m.Channel, m.Kind, m.RunID, m.Title, m.Body, m.Key, m.RequestID, m.ExpiresAt) if errors.Is(err, sql.ErrNoRows) { err = s.db.GetContext(ctx, &seq, ` SELECT seq FROM deliveries.messages WHERE org_id = $1 AND channel = $2 AND key = $3`, @@ -63,7 +67,7 @@ func (s *Store) Insert(ctx context.Context, m Message) (int64, bool, error) { func (s *Store) After(ctx context.Context, orgID, channel string, seq int64, limit int) ([]Message, error) { var out []Message if err := s.db.SelectContext(ctx, &out, ` - SELECT seq, id, org_id, channel, kind, run_id, title, body, key, created_at + SELECT seq, id, org_id, channel, kind, run_id, title, body, key, request_id, expires_at, created_at FROM deliveries.messages WHERE org_id = $1 AND channel = $2 AND seq > $3 ORDER BY seq LIMIT $4`, orgID, channel, seq, limit); err != nil { return nil, fmt.Errorf("list messages: %w", err) @@ -76,7 +80,7 @@ func (s *Store) Latest(ctx context.Context, orgID, channel string, limit int) ([ var out []Message if err := s.db.SelectContext(ctx, &out, ` SELECT * FROM ( - SELECT seq, id, org_id, channel, kind, run_id, title, body, key, created_at + SELECT seq, id, org_id, channel, kind, run_id, title, body, key, request_id, expires_at, created_at FROM deliveries.messages WHERE org_id = $1 AND channel = $2 ORDER BY seq DESC LIMIT $3) latest ORDER BY seq`, orgID, channel, limit); err != nil { diff --git a/modules/governance/governance.go b/modules/governance/governance.go index 97150cbde..7558dca25 100644 --- a/modules/governance/governance.go +++ b/modules/governance/governance.go @@ -11,6 +11,7 @@ import ( "log/slog" "net/http" "net/url" + "time" "github.com/jmoiron/sqlx" "github.com/samcharles93/ai-sdk/chat" @@ -26,6 +27,31 @@ var ErrNoAgentModel = errors.New("no agent model is set for the organisation") const roleAgent = "agent" +// DefaultApprovalDeadline is how long an approval request waits for an answer +// when the organisation hasn't said. +const DefaultApprovalDeadline = 24 * time.Hour + +// The bounds on an approval deadline. Below a minute nobody could answer; past +// a month the request outlives the incident it was raised for. +const ( + minApprovalDeadline = time.Minute + maxApprovalDeadline = 30 * 24 * time.Hour +) + +// Settings is what the organisation decides about how Archie acts. +type Settings struct { + // ApprovalDeadline is how long an approval request waits for an answer + // before the run gives up on it. + ApprovalDeadline time.Duration +} + +// settingsRequest is the settings as the API shows and sets them. A duration +// travels as a Go duration string ("24h"), the same form every other duration +// in the config takes. +type settingsRequest struct { + ApprovalDeadline string `json:"approval_deadline"` +} + // Model is the model chosen for a role. type Model struct { Class string `json:"class"` @@ -76,10 +102,78 @@ func (m *Module) AgentModel(ctx context.Context) (Model, error) { return Model{Class: role.Class, BaseURL: role.BaseURL, Model: role.Model}, nil } +// Settings returns the organisation's settings, with a default for every one it +// hasn't set. +func (m *Module) Settings(ctx context.Context) (Settings, error) { + row, ok, err := m.store.Settings(ctx, m.orgID) + if err != nil { + return Settings{}, err + } + if !ok { + return Settings{ApprovalDeadline: DefaultApprovalDeadline}, nil + } + return Settings{ApprovalDeadline: time.Duration(row.ApprovalDeadlineMS) * time.Millisecond}, nil +} + +// ApprovalDeadline is how long an approval request waits for an answer. +func (m *Module) ApprovalDeadline(ctx context.Context) (time.Duration, error) { + set, err := m.Settings(ctx) + if err != nil { + return 0, err + } + return set.ApprovalDeadline, nil +} + // Routes adds the settings API to mux behind guard. func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) { mux.Handle("GET /api/settings/agent-model", guard(http.HandlerFunc(m.getAgentModel))) mux.Handle("PUT /api/settings/agent-model", guard(http.HandlerFunc(m.putAgentModel))) + mux.Handle("GET /api/settings", guard(http.HandlerFunc(m.getSettings))) + mux.Handle("PUT /api/settings", guard(http.HandlerFunc(m.putSettings))) +} + +func (m *Module) getSettings(w http.ResponseWriter, r *http.Request) { + set, err := m.Settings(r.Context()) + if err != nil { + m.log.ErrorContext(r.Context(), "read settings", "error", err) + httpjson.Error(w, http.StatusInternalServerError, "couldn't read the settings") + return + } + httpjson.Write(w, http.StatusOK, settingsRequest{ApprovalDeadline: set.ApprovalDeadline.String()}) +} + +func (m *Module) putSettings(w http.ResponseWriter, r *http.Request) { + var req settingsRequest + if err := httpjson.Read(r, &req); err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + deadline, err := time.ParseDuration(req.ApprovalDeadline) + if err != nil { + httpjson.Error(w, http.StatusBadRequest, "approval deadline is a duration, such as 24h") + return + } + set := Settings{ApprovalDeadline: deadline} + if err := set.validate(); err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + if err := m.store.PutSettings(r.Context(), store.Settings{ + OrgID: m.orgID, ApprovalDeadlineMS: set.ApprovalDeadline.Milliseconds(), + }); err != nil { + m.log.ErrorContext(r.Context(), "put settings", "error", err) + httpjson.Error(w, http.StatusInternalServerError, "couldn't save the settings") + return + } + httpjson.Write(w, http.StatusOK, settingsRequest{ApprovalDeadline: set.ApprovalDeadline.String()}) +} + +// validate keeps a deadline inside the range an answer can be given in. +func (s Settings) validate() error { + if s.ApprovalDeadline < minApprovalDeadline || s.ApprovalDeadline > maxApprovalDeadline { + return fmt.Errorf("approval deadline must be between %s and %s", minApprovalDeadline, maxApprovalDeadline) + } + return nil } func (m *Module) getAgentModel(w http.ResponseWriter, r *http.Request) { diff --git a/modules/governance/internal/store/store.go b/modules/governance/internal/store/store.go index a8bc79c83..f7a1df6ab 100644 --- a/modules/governance/internal/store/store.go +++ b/modules/governance/internal/store/store.go @@ -55,3 +55,38 @@ func (s *Store) PutModelRole(ctx context.Context, m ModelRole) error { } return nil } + +// Settings is an organisation's settings as stored. A duration is kept in +// milliseconds: Postgres has no duration type that scans into one. +type Settings struct { + OrgID string `db:"org_id"` + // ApprovalDeadlineMS is how long an approval request waits for an answer. + ApprovalDeadlineMS int64 `db:"approval_deadline_ms"` +} + +// Settings returns the organisation's settings; ok is false when none were +// saved. +func (s *Store) Settings(ctx context.Context, orgID string) (Settings, bool, error) { + var out Settings + err := s.db.GetContext(ctx, &out, ` + SELECT org_id, approval_deadline_ms FROM governance.settings WHERE org_id = $1`, orgID) + if errors.Is(err, sql.ErrNoRows) { + return Settings{}, false, nil + } + if err != nil { + return Settings{}, false, fmt.Errorf("read settings: %w", err) + } + return out, true, nil +} + +// PutSettings records the organisation's settings. +func (s *Store) PutSettings(ctx context.Context, set Settings) error { + if _, err := s.db.NamedExecContext(ctx, ` + INSERT INTO governance.settings (org_id, approval_deadline_ms) + VALUES (:org_id, :approval_deadline_ms) + ON CONFLICT (org_id) DO UPDATE + SET approval_deadline_ms = EXCLUDED.approval_deadline_ms, updated_at = now()`, set); err != nil { + return fmt.Errorf("put settings: %w", err) + } + return nil +} diff --git a/modules/judgement/judgement.go b/modules/judgement/judgement.go index e967e34d8..f3c7e0c69 100644 --- a/modules/judgement/judgement.go +++ b/modules/judgement/judgement.go @@ -31,6 +31,9 @@ var ( ErrHeld = errors.New("held for approval") // ErrAltered means the action to run isn't the one that was judged. ErrAltered = errors.New("action differs from the one judged") + // ErrUnapproved means the action needs an approval it doesn't have, or the + // approval offered was given for a different action. + ErrUnapproved = errors.New("not approved") ) // Action is one concrete action: the exact operation on the exact target. @@ -233,6 +236,40 @@ func (m *Module) Execute(ctx context.Context, d Decision, input jsontext.Value, return tool.Invoke(ctx, connectors.Invocation{Action: d.Action.Name, Input: input, IdempotencyKey: key}) } +// 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 { + DecisionID uuid.UUID `json:"decision_id"` + Digest string `json:"digest"` + By string `json:"by"` + At time.Time `json:"at"` +} + +// 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 +} + +// ExecuteApproved runs an action a person approved. A refusal still refuses, +// and an approval that names another decision or another action runs nothing. +// The action that runs is the one judged, whatever input comes with it. +func (m *Module) ExecuteApproved(ctx context.Context, d Decision, a Approval, input jsontext.Value, key string) (string, error) { + switch { + case d.Level == Never: + return "", fmt.Errorf("%w: %s: %s", ErrRefused, d.RefusedBy, d.Reason) + case !a.Covers(d): + return "", fmt.Errorf("%w: the approval names another action", ErrUnapproved) + case connectors.Digest(d.Action.Name, input) != d.Action.Digest: + return "", ErrAltered + } + tool, ok := m.tools.Tool(d.Action.Connector) + if !ok { + return "", fmt.Errorf("%q isn't running", d.Action.Connector) + } + return tool.Invoke(ctx, connectors.Invocation{Action: d.Action.Name, Input: input, IdempotencyKey: key}) +} + // ForRun returns a run's decisions in the order they were made. func (m *Module) ForRun(ctx context.Context, runID uuid.UUID) ([]Decision, error) { rows, err := m.store.ForRun(ctx, m.orgID, runID) diff --git a/modules/judgement/judgement_test.go b/modules/judgement/judgement_test.go index 7ebb23899..e3099d333 100644 --- a/modules/judgement/judgement_test.go +++ b/modules/judgement/judgement_test.go @@ -6,6 +6,9 @@ import ( "errors" "sync/atomic" "testing" + "time" + + "github.com/google/uuid" "github.com/samcharles93/archie-core/modules/connectors" ) @@ -180,3 +183,86 @@ func TestExecuteRunsOnlyTheJudgedAction(t *testing.T) { }) } } + +// TestExecuteApprovedRunsOnlyWhatThePersonSaw guards the approval boundary: an +// approval covers the decision and the exact action a person was shown, so a +// replayed or replayed-onto-another-action approval runs nothing, and a +// refusal still refuses with one. +func TestExecuteApprovedRunsOnlyWhatThePersonSaw(t *testing.T) { + judged := jsontext.Value(`{"path":"/tmp/runner"}`) + const key = "run:1:3" + decided := func() Decision { + return Decision{ + ID: uuid.MustParse("11111111-1111-1111-1111-111111111111"), + Level: ProposeAndWait, + Action: Action{ + Connector: "c", Name: "delete", Input: judged, + Digest: connectors.Digest("delete", judged), + }, + } + } + approval := func(d Decision) Approval { + return Approval{DecisionID: d.ID, Digest: d.Action.Digest, By: "admin", At: time.Now().UTC()} + } + tests := []struct { + name string + d func() Decision + a func(Decision) Approval + input jsontext.Value + wantErr error + }{ + {name: "an approval for this action runs it", d: decided, a: approval, input: judged}, + { + name: "an approval naming another decision runs nothing", + d: decided, input: judged, + a: func(d Decision) Approval { + other := approval(d) + other.DecisionID = uuid.MustParse("22222222-2222-2222-2222-222222222222") + return other + }, + wantErr: ErrUnapproved, + }, + { + name: "an approval for another action runs nothing", + d: decided, input: judged, + a: func(d Decision) Approval { + other := approval(d) + other.Digest = connectors.Digest("delete", jsontext.Value(`{"path":"/"}`)) + return other + }, + wantErr: ErrUnapproved, + }, + { + name: "input that differs from the judged action is refused", + d: decided, a: approval, input: jsontext.Value(`{"path":"/"}`), + wantErr: ErrAltered, + }, + { + name: "a refusal still refuses with one", + d: func() Decision { + d := decided() + d.Level, d.RefusedBy, d.Reason = Never, "blackout", "a release is in flight" + return d + }, + a: approval, input: judged, wantErr: ErrRefused, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var invoked atomic.Int32 + m := &Module{tools: oneTool{countingTool{&invoked}}} + d := tt.d() + _, err := m.ExecuteApproved(t.Context(), d, tt.a(d), tt.input, key) + if !errors.Is(err, tt.wantErr) { + t.Fatalf("err = %v, want %v", err, tt.wantErr) + } + want := int32(1) + if tt.wantErr != nil { + want = 0 + } + if got := invoked.Load(); got != want { + t.Fatalf("connector invoked %d times, want %d", got, want) + } + }) + } +} diff --git a/modules/runs/approvals_test.go b/modules/runs/approvals_test.go new file mode 100644 index 000000000..a8948e7f2 --- /dev/null +++ b/modules/runs/approvals_test.go @@ -0,0 +1,42 @@ +package runs + +import ( + "testing" + + "github.com/samcharles93/archie-core/modules/judgement" +) + +// TestHeldByJudgementAsksOncePerAction guards against asking a person twice: an +// agent that proposes the same action more than once gets one request, an +// action that runs unattended is not put to them, and a refusal is not offered +// either. +func TestHeldByJudgementAsksOncePerAction(t *testing.T) { + decided := func(level judgement.Level, digest string) judgement.Decision { + return judgement.Decision{Level: level, Action: judgement.Action{Digest: digest}} + } + tests := []struct { + name string + in []judgement.Decision + wantN int + }{ + {name: "nothing proposed asks nothing", in: nil, wantN: 0}, + {name: "a held action is asked about", in: []judgement.Decision{decided(judgement.ProposeAndWait, "a")}, wantN: 1}, + {name: "the same action twice is asked about once", in: []judgement.Decision{ + decided(judgement.ProposeAndWait, "a"), decided(judgement.ProposeAndWait, "a"), + }, wantN: 1}, + {name: "two different actions are both asked about", in: []judgement.Decision{ + decided(judgement.ProposeAndWait, "a"), decided(judgement.Escalate, "b"), + }, wantN: 2}, + {name: "an action that runs unattended is not asked about", in: []judgement.Decision{ + decided(judgement.ActAndTell, "a"), + }, wantN: 0}, + {name: "a refused action is not asked about", in: []judgement.Decision{decided(judgement.Never, "a")}, wantN: 0}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := len(heldByJudgement(tt.in)); got != tt.wantN { + t.Fatalf("asked about %d actions, want %d", got, tt.wantN) + } + }) + } +} diff --git a/modules/runs/investigate.go b/modules/runs/investigate.go index cfdf3e902..ec19f3905 100644 --- a/modules/runs/investigate.go +++ b/modules/runs/investigate.go @@ -15,15 +15,18 @@ import ( "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/archie-core/internal/platform/prompts" + "github.com/samcharles93/archie-core/modules/approvals" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/deliveries" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement" ) -// AgentModels is where a workflow finds the organisation's agent model. -type AgentModels interface { +// Settings is where a workflow finds what the organisation decided: the agent +// model it runs, and how long an approval request waits for an answer. +type Settings interface { AgentModel(ctx context.Context) (governance.Model, error) + ApprovalDeadline(ctx context.Context) (time.Duration, error) } // Toolbox is where a workflow finds the connector lookups and actions and the @@ -38,6 +41,15 @@ type Toolbox interface { type Judge interface { Assess(ctx context.Context, req judgement.Request) (judgement.Decision, error) Execute(ctx context.Context, d judgement.Decision, input jsontext.Value, key string) (string, error) + ExecuteApproved(ctx context.Context, d judgement.Decision, a judgement.Approval, input jsontext.Value, key string) (string, error) + ForRun(ctx context.Context, runID uuid.UUID) ([]judgement.Decision, error) +} + +// Approver asks people to allow an action judgement held, and settles a request +// whose deadline passed. +type Approver interface { + Ask(ctx context.Context, runID uuid.UUID, key string, d judgement.Decision, deadline time.Time) (approvals.Request, error) + Expire(ctx context.Context, id uuid.UUID) error } // Notifier tells people what a run found. @@ -52,15 +64,31 @@ var investigateBudget = agentloop.Budget{MaxSteps: 20, MaxTokens: 200_000, WallC // Investigate is the workflow that has an agent look into the event that // started the run and report its findings. The agent model and the tools are // pinned in the run's first steps, so a resumed run asks the same model with -// the same tools even if settings or connectors changed meanwhile. -func Investigate(models AgentModels, box Toolbox, judge Judge, notify Notifier) Workflow { +// the same tools even if settings or connectors changed meanwhile. An action +// the agent proposes is judged as it calls it; one judgement holds is put to a +// person, and the run waits for the answer before running it. +func Investigate(settings Settings, box Toolbox, judge Judge, ask Approver, notify Notifier) Workflow { return func(rc *Context, input jsontext.Value) (jsontext.Value, error) { model, err := rc.Step("agent-model", func(ctx context.Context, _ string) (governance.Model, error) { - return models.AgentModel(ctx) + return settings.AgentModel(ctx) }) if err != nil { return nil, err } + // Pinned here, like the model: a run that waits keeps the deadline it + // started with, whatever the setting becomes meanwhile. A step's value + // is encoded, so it travels as the duration's own text. + deadlineText, err := rc.Step("approval-deadline", func(ctx context.Context, _ string) (string, error) { + d, err := settings.ApprovalDeadline(ctx) + return d.String(), err + }) + if err != nil { + return nil, err + } + deadline, err := time.ParseDuration(deadlineText) + if err != nil { + return nil, fmt.Errorf("approval deadline %q: %w", deadlineText, err) + } decls, err := rc.Step("agent-tools", func(context.Context, string) ([]connectors.Declaration, error) { return box.Declarations(), nil }) @@ -84,8 +112,12 @@ func Investigate(models AgentModels, box Toolbox, judge Judge, notify Notifier) if err != nil { return nil, err } + outcomes, err := settleProposals(rc, judge, ask, deadline) + if err != nil { + return nil, err + } if _, err := rc.Step("notify", func(ctx context.Context, key string) (bool, error) { - return true, notify.Notify(ctx, findings(rc.RunID(), key, res)) + return true, notify.Notify(ctx, findings(rc.RunID(), key, res, outcomes)) }); err != nil { return nil, err } @@ -100,16 +132,187 @@ func Investigate(models AgentModels, box Toolbox, judge Judge, notify Notifier) } } +// approvalOutcome is what became of one action the agent proposed. +type approvalOutcome struct { + Action string `json:"action"` + Target string `json:"target"` + RequestID uuid.UUID `json:"request_id"` + State string `json:"state"` + By string `json:"by,omitzero"` + Result string `json:"result,omitzero"` + Error string `json:"error,omitzero"` +} + +// settleProposals puts every action judgement held to a person, one at a time, +// and runs the ones they allow. Each ask, wait and run is its own step, so a +// resumed run picks up where it waited. A proposal nobody answers in time is +// settled as expired and nothing runs. +func settleProposals(rc *Context, judge Judge, ask Approver, deadline time.Duration) ([]approvalOutcome, error) { + held, err := rc.Step("proposals", func(ctx context.Context, _ string) ([]judgement.Decision, error) { + decisions, err := judge.ForRun(ctx, rc.RunID()) + if err != nil { + return nil, err + } + return heldByJudgement(decisions), nil + }) + if err != nil { + return nil, err + } + out := make([]approvalOutcome, 0, len(held)) + for _, d := range held { + outcome, err := settleOne(rc, judge, ask, d, deadline) + if err != nil { + return nil, err + } + out = append(out, outcome) + } + return out, nil +} + +func settleOne(rc *Context, judge Judge, ask Approver, d judgement.Decision, deadline time.Duration) (approvalOutcome, error) { + out := approvalOutcome{Action: d.Action.Connector + " " + d.Action.Name, Target: d.Action.Target.Kind + ":" + d.Action.Target.ID} + 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, time.Now().Add(deadline)) + }) + if err != nil { + return out, err + } + out.RequestID, out.State = request.ID, request.State + if request.State != approvals.StatePending { + return out, nil + } + answer, expired, err := waitForAnswer(rc, ask, d.Key, request, deadline) + if err != nil { + return out, err + } + if expired { + out.State = approvals.StateExpired + return out, nil + } + if !answer.Approved { + out.State, out.By = approvals.StateDenied, answer.By + return out, nil + } + out.By = answer.By + // The action's own failure is part of what the answer led to, and its step + // has recorded it, so the investigation still reports. + run, runErr := runApproved(rc, judge, d, answer) + out.State, out.Result, out.Error = approvals.StateApproved, run, errText(runErr) + return out, nil +} + +// errText is a failed action's reason, or nothing when it ran. +func errText(err error) string { + if err == nil { + return "" + } + return err.Error() +} + +// waitForAnswer waits for the person's answer. When the deadline passes with +// none, the request is settled as expired and the caller runs nothing. +func waitForAnswer(rc *Context, ask Approver, key string, request approvals.Request, deadline time.Duration) (approvals.Answer, bool, error) { + payload, err := rc.Wait(waitKey(key), deadline) + if errors.Is(err, ErrWaitTimedOut) { + if _, eerr := rc.Step("expire:"+key, func(ctx context.Context, _ string) (bool, error) { + return true, ask.Expire(ctx, request.ID) + }); eerr != nil { + return approvals.Answer{}, true, eerr + } + return approvals.Answer{}, true, nil + } + if err != nil { + return approvals.Answer{}, false, err + } + var answer approvals.Answer + if err := json.Unmarshal(payload, &answer); err != nil { + return approvals.Answer{}, false, fmt.Errorf("decode approval answer: %w", err) + } + return answer, false, nil +} + +// runApproved judges the action again and runs it, once. An approval covers +// the action the person was shown, so a judgement that came back worse than +// it was cannot be run on that approval. +func runApproved(rc *Context, judge Judge, d judgement.Decision, answer approvals.Answer) (string, error) { + fresh, err := rc.Step("judge-again:"+d.Key, func(ctx context.Context, key string) (judgement.Decision, error) { + return judge.Assess(ctx, judgement.Request{ + RunID: rc.RunID(), Key: key, Connector: d.Action.Connector, Action: d.Action.Name, Input: d.Action.Input, + }) + }) + if err != nil { + return "", err + } + return rc.Step("run:"+d.Key, func(ctx context.Context, key string) (string, error) { + switch { + case fresh.Level == judgement.Never: + return "", fmt.Errorf("refused after approval: %s", fresh.Reason) + case fresh.Level.Runs(): + return judge.Execute(ctx, fresh, d.Action.Input, key) + case fresh.Level > d.Level: + return "", fmt.Errorf("judgement got worse after approval: now %s", fresh.Level) + } + return judge.ExecuteApproved(ctx, d, answer.Approval(d), d.Action.Input, key) + }) +} + +// heldByJudgement is the actions an agent proposed that need a person before +// they run, once each: an agent that asks for the same action twice is asked +// about it once. +func heldByJudgement(decisions []judgement.Decision) []judgement.Decision { + seen := make(map[string]bool, len(decisions)) + out := make([]judgement.Decision, 0, len(decisions)) + for _, d := range decisions { + if d.Level < judgement.ProposeAndWait || d.Level == judgement.Never || seen[d.Action.Digest] { + continue + } + seen[d.Action.Digest] = true + out = append(out, d) + } + return out +} + +// waitKey is the run key an approval answer wakes. +func waitKey(key string) string { return "approval:" + key } + // findings is the notification an investigation ends with, finished or not. -func findings(runID uuid.UUID, key string, res AgentResult) deliveries.Notification { +func findings(runID uuid.UUID, key string, res AgentResult, outcomes []approvalOutcome) deliveries.Notification { n := deliveries.Notification{RunID: runID, Key: key, Title: "Investigation finished", Body: res.Answer} if !res.Completed { n.Title = "Investigation stopped" n.Body = fmt.Sprintf("The investigation stopped before it finished (%s). %s", res.StopReason, res.Detail) } + // The record says plainly when nothing was proposed, whatever the findings + // then claim. + n.Body += "\n\n" + outcomeLines(outcomes) return n } +// outcomeLines says what became of each action the investigation proposed, and +// that none was when that is the case. +func outcomeLines(outcomes []approvalOutcome) string { + if len(outcomes) == 0 { + return "Actions: none proposed." + } + lines := make([]string, 0, len(outcomes)) + for _, o := range outcomes { + line := fmt.Sprintf("- %s on %s: %s", o.Action, o.Target, o.State) + switch { + case o.Error != "": + line += ", " + o.Error + case o.Result != "": + line += ", it ran: " + o.Result + case o.State == approvals.StateApproved: + line += ", it ran" + } + if o.By != "" { + line += " (" + o.By + ")" + } + lines = append(lines, line) + } + return "Actions:\n" + strings.Join(lines, "\n") +} + // unsafeToolChars are those a model API refuses in a tool name. var unsafeToolChars = regexp.MustCompile(`[^a-zA-Z0-9_-]`) @@ -147,8 +350,9 @@ func call(ctx context.Context, box Toolbox, judge Judge, runID uuid.UUID, d conn } return out, nil } - // An action is judged first and runs only as decided. A held one comes - // back to the agent as a failed call naming the level and the findings. + // An action is judged first and runs only as decided. One judgement holds + // is proposed to a person when the investigation ends, so it comes back to + // the agent as something waiting rather than a failure. key := core.IdempotencyKey(ctx) decision, err := judge.Assess(ctx, judgement.Request{RunID: runID, Key: key, Connector: d.Connector, Action: d.Name, Input: input}) if err != nil { @@ -156,7 +360,7 @@ func call(ctx context.Context, box Toolbox, judge Judge, runID uuid.UUID, d conn } out, err := judge.Execute(ctx, decision, input, key) if errors.Is(err, judgement.ErrHeld) { - return "", fmt.Errorf("%w: %s; approvals aren't available yet, so propose it in your findings instead", err, findingsOf(decision)) + return fmt.Sprintf("held at %s for a person's approval: %s. It is asked when your investigation ends, so don't propose it again.", decision.Level, findingsOf(decision)), nil } if errors.Is(err, connectors.ErrOutcomeUnknown) { return "", fmt.Errorf("%w: %w", core.ErrOutcomeUnknown, err) diff --git a/ui/src/archie/App.vue b/ui/src/archie/App.vue index f7ec33542..300b74677 100644 --- a/ui/src/archie/App.vue +++ b/ui/src/archie/App.vue @@ -34,6 +34,7 @@ function signOut() { Composer Runs + Settings Sign out diff --git a/ui/src/archie/ComposerView.vue b/ui/src/archie/ComposerView.vue index 216c0b28f..33d25a45c 100644 --- a/ui/src/archie/ComposerView.vue +++ b/ui/src/archie/ComposerView.vue @@ -1,13 +1,14 @@ + + + + + + + + + + + + How long an approval request waits for an answer. Nothing runs when it expires. + + + Save + {{ saved }} + + + + diff --git a/ui/src/archie/api.ts b/ui/src/archie/api.ts index 5a2581843..edeae90f8 100644 --- a/ui/src/archie/api.ts +++ b/ui/src/archie/api.ts @@ -25,10 +25,12 @@ async function get(path: string, signal?: AbortSignal): Promise { export interface Message { seq: number; id: string; - kind: "notification"; + kind: "notification" | "approval_request" | "approval_answer"; run_id?: string; + request_id?: string; title: string; body: string; + expires_at?: string; created_at: string; } @@ -82,9 +84,43 @@ export interface Trail { entries: TrailEntry[]; } +export interface Settings { + /** A Go duration, such as "24h". */ + approval_deadline: string; +} + +export const getSettings = (signal?: AbortSignal) => get("/api/settings", signal); + +export async function saveSettings(next: Settings): Promise { + const res = await fetch("/api/settings", { + method: "PUT", + headers: { Authorization: `Bearer ${token()}`, "Content-Type": "application/json" }, + body: JSON.stringify(next), + }); + if (res.status === 401) throw new Unauthorized("The admin token was refused."); + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { error?: string }; + throw new Error(body.error ?? `${res.status} ${res.statusText}`); + } +} + export const latestMessages = (signal?: AbortSignal) => get("/api/composer/messages", signal); export const messagesAfter = (seq: number, signal?: AbortSignal) => get(`/api/composer/messages?after=${seq}`, signal); + +/** Answers an approval request the composer is showing. */ +export async function answerApproval(id: string, approved: boolean): Promise { + const res = await fetch(`/api/approvals/${encodeURIComponent(id)}/answer`, { + method: "POST", + headers: { Authorization: `Bearer ${token()}`, "Content-Type": "application/json" }, + body: JSON.stringify({ approved }), + }); + if (res.status === 401) throw new Unauthorized("The admin token was refused."); + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { error?: string }; + throw new Error(body.error ?? `${res.status} ${res.statusText}`); + } +} export const listRuns = (signal?: AbortSignal) => get("/api/runs", signal); export const runTrail = (id: string, signal?: AbortSignal) => get(`/api/runs/${encodeURIComponent(id)}`, signal); diff --git a/ui/src/archie/router.ts b/ui/src/archie/router.ts index 4eb4fe846..b1afc179a 100644 --- a/ui/src/archie/router.ts +++ b/ui/src/archie/router.ts @@ -6,6 +6,7 @@ export default createRouter({ { path: "/", redirect: "/composer" }, { path: "/composer", name: "composer", component: () => import("./ComposerView.vue") }, { path: "/runs", name: "runs", component: () => import("./RunsView.vue") }, + { path: "/settings", name: "settings", component: () => import("./SettingsView.vue") }, { path: "/runs/:id", name: "run", component: () => import("./RunView.vue"), props: true }, ], });
+ How long an approval request waits for an answer. Nothing runs when it expires. +