Files
archie/modules/approvals/approvals.go
T
samandCopilot 64dfad6d53 feat(runs): add typed results and model aliases (#2043)
Also fix repository-free message.send validation (#2046) and add a single-binary development smoke path (#1977).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-18 23:47:35 +11:00

682 lines
23 KiB
Go

// Package approvals manages requests for human approval and records responses.
// A response to an action request resumes the waiting run. The request binds
// the approval to the decision ID and action digest so it cannot authorize a
// different action.
package approvals
import (
"context"
"database/sql"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
"maps"
"net/http"
"slices"
"strings"
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
"github.com/samcharles93/archie-core/modules/deliveries"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement"
)
// A settled request cannot be answered again. An approved request may still
// be discarded before the approval is counted.
const (
StatePending = "pending"
StateApproved = "approved"
StateDenied = "denied"
StateExpired = "expired"
StateDiscarded = "discarded"
)
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")
// ErrUnverified means the answer came from an identity no person holds.
ErrUnverified = errors.New("that identity isn't held by any person, so its answer is refused")
// ErrNotApprover means the person may not answer approvals for actions.
ErrNotApprover = errors.New("that person isn't the default owner, on the escalation path or an authority, so their answer is refused")
// ErrNotAsked means the request hasn't yet reached that person on its
// escalation path.
ErrNotAsked = errors.New("that person hasn't been asked yet, so their answer is refused")
// ErrNeedsAuthority means the action needs a person with authority, and
// the answer came from one without.
ErrNeedsAuthority = errors.New("that action needs a person with authority, so their answer is refused")
// ErrNoAuthority means the answer to a raise came from a person without
// authority over policy and ceilings.
ErrNoAuthority = errors.New("that person holds no authority over policy and ceilings, so their answer to a raise is refused")
)
// The kinds of request. A raise asks whether an action class may act with one
// level more autonomy; no run waits on it.
const (
KindAction = "action"
KindRaise = "raise"
)
// Request tracks approval of an action 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
RequestedAt time.Time
Connector string
Action string
TargetKind string
TargetID string
Level string
Summary string
State string
// Deadline applies to the whole request, not just the current escalation step.
Deadline time.Time
// Step and StepDeadline track the current escalation step and its deadline.
Step int
StepDeadline time.Time
// ChangeRequest is whether the request went through a change request
// rather than the approvers' channels.
ChangeRequest bool
AnsweredAt time.Time
AnsweredBy string
AnsweredVia string
}
// Answer records the decision and who made it.
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 binds the approver's identity and response time to the decision ID
// and action digest.
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 the API representation of an approval request.
type View struct {
ID uuid.UUID `json:"id"`
Kind string `json:"kind"`
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"`
// Step and StepDeadline describe the current escalation step.
Step int `json:"step"`
StepDeadline time.Time `json:"step_deadline,omitzero"`
// DecisionID identifies the judgement decision or, for a raise request, the proposed raise.
DecisionID uuid.UUID `json:"decision_id"`
RequestedAt time.Time `json:"requested_at"`
AnsweredBy string `json:"answered_by,omitzero"`
AnsweredVia string `json:"answered_via,omitzero"`
AnsweredAt time.Time `json:"answered_at,omitzero"`
}
// View converts a request to its API representation.
func (r Request) View() View {
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,
AnsweredBy: r.AnsweredBy, AnsweredVia: r.AnsweredVia, AnsweredAt: r.AnsweredAt,
}
}
// 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 sends approval requests and publishes responses and notifications.
type Delivery interface {
Ask(ctx context.Context, a deliveries.ApprovalRequest) error
Told(ctx context.Context, a deliveries.ApprovalRequest, answer string) error
Notify(ctx context.Context, n deliveries.Notification) error
}
// Classes updates action-class autonomy. Denials reduce autonomy; approvals
// count towards an increase that a person must approve separately.
type Classes interface {
Approved(ctx context.Context, decisionID uuid.UUID, by string, need int, deadline time.Time) (*judgement.Raise, error)
Denied(ctx context.Context, decisionID uuid.UUID) error
AnswerRaise(ctx context.Context, id uuid.UUID, by string, approve bool) (bool, error)
CancelRaise(ctx context.Context, id uuid.UUID) error
}
// Policy provides the organisation's deadline and approval threshold for raises.
type Policy interface {
ApprovalDeadline(ctx context.Context) (time.Duration, error)
RaiseAfter(ctx context.Context) (int, error)
}
// People resolves verified channel identities to people.
type People interface {
Verify(ctx context.Context, identity string) (governance.Verified, bool, error)
}
// Module owns one organisation's approval requests.
type Module struct {
orgID string
store *store.Store
tell Delivery
wake Signaller
classes Classes
policy Policy
people People
changes ChangeRequests
log *slog.Logger
now func() time.Time
}
// NewModule creates the approvals module for orgID.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake Signaller, classes Classes, policy Policy, people People) *Module {
return &Module{
orgID: orgID, store: store.New(db), tell: tell, wake: wake, classes: classes, policy: policy, people: people,
log: log, now: time.Now,
}
}
// 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) {
if len(path) == 0 {
return Request{}, ErrNoPath
}
changeRequest := d.ChangeRequest && m.changes != nil
now := m.now().UTC()
var total time.Duration
for _, st := range path {
total += st.Deadline()
}
asked := []string{}
if path[0].Person != "" {
asked = append(asked, path[0].Person)
}
askedJSON, err := json.Marshal(asked)
if err != nil {
return Request{}, fmt.Errorf("encode asked: %w", err)
}
row, err := m.store.Put(ctx, store.Request{
ID: uuid.New(), OrgID: m.orgID, RunID: runID, Key: key,
DecisionID: d.ID, Kind: KindAction, 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: now.Add(total),
StepDeadline: sql.NullTime{Time: now.Add(path[0].Deadline()), Valid: true}, Asked: string(askedJSON),
ChangeRequest: changeRequest,
})
if err != nil {
return Request{}, err
}
r := requestOf(row, d)
if row.State != StatePending {
return r, nil
}
if row.ChangeRequest {
if err := m.changes.Open(ctx, r); err != nil {
return Request{}, fmt.Errorf("open change request: %w", err)
}
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.StepDeadline,
}); err != nil {
return Request{}, fmt.Errorf("send approval request: %w", err)
}
return r, nil
}
func (m *Module) answerAs(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 row.Kind == KindRaise {
if err := m.answerRaise(ctx, row, answer); err != nil {
return Request{}, err
}
return requestOf(row, judgement.Decision{}), nil
}
if err := m.wakeWith(ctx, row, answer); err != nil {
return Request{}, err
}
// Count denials immediately. Defer counting approvals until execution
// is imminent so discarded approvals do not increase autonomy.
if !answer.Approved {
if err := m.classes.Denied(ctx, row.DecisionID); err != nil {
return Request{}, err
}
}
return requestOf(row, judgement.Decision{}), nil
}
func (m *Module) learn(ctx context.Context, row store.Request, a Answer) error {
need, err := m.policy.RaiseAfter(ctx)
if err != nil {
return fmt.Errorf("read raise count: %w", err)
}
wait, err := m.policy.ApprovalDeadline(ctx)
if err != nil {
return fmt.Errorf("read approval deadline: %w", err)
}
raise, err := m.classes.Approved(ctx, row.DecisionID, a.By, need, a.At.Add(wait))
if err != nil || raise == nil {
return err
}
return m.askRaise(ctx, raise)
}
func (m *Module) askRaise(ctx context.Context, r *judgement.Raise) error {
class := r.Class
row, err := m.store.Put(ctx, store.Request{
ID: uuid.New(), OrgID: m.orgID, Key: "raise:" + r.ID.String(),
DecisionID: r.ID, Kind: KindRaise, Level: r.From.String(),
Connector: class.Connector, Action: class.Action, TargetKind: class.TargetKind, TargetID: class.Environment,
Summary: raiseSummary(r), State: StatePending, Deadline: r.Deadline,
})
if err == nil {
err = m.tell.Ask(ctx, deliveries.ApprovalRequest{
RequestID: row.ID, Key: row.Key + ":ask",
Title: "Raise autonomy: " + class.Connector + " " + class.Action,
Body: row.Summary, ExpiresAt: row.Deadline,
})
}
if err != nil {
// Cancel the raise so a later approval can trigger another proposal.
if cerr := m.classes.CancelRaise(ctx, r.ID); cerr != nil {
err = errors.Join(err, cerr)
}
return fmt.Errorf("ask to raise a class: %w", err)
}
return nil
}
// answerRaise applies a person's answer to a raise. No run waits on it.
func (m *Module) answerRaise(ctx context.Context, row store.Request, a Answer) error {
raised, err := m.classes.AnswerRaise(ctx, row.DecisionID, a.By, a.Approved)
if err != nil {
return fmt.Errorf("answer raise: %w", err)
}
text := answerText(a)
if a.Approved && !raised {
text += " This approval did not increase the action class's autonomy level."
}
return m.tell.Told(ctx, deliveries.ApprovalRequest{
RequestID: row.ID, Key: row.Key + ":ask", Title: "Raise answered",
}, text)
}
func raiseSummary(r *judgement.Raise) string {
c := r.Class
var s strings.Builder
fmt.Fprintf(&s, "%s: %s on %s in %s. Proposed autonomy increase: %s to %s.\nConsecutive approvals (%d):",
c.Connector, c.Action, c.TargetKind, c.Environment, r.From, r.To, len(r.Evidence))
for _, e := range r.Evidence {
fmt.Fprintf(&s, "\n- %s, %s", e.By, e.At.UTC().Format("2006-01-02 15:04 UTC"))
}
return s.String()
}
// Settle processes a response from a channel identity such as "telegram:1001".
// It records why it rejected an unverified or unauthorized response. It returns
// false without an error for recorded rejections and for requests that are
// missing, expired or already answered, since retrying won't help.
func (m *Module) Settle(ctx context.Context, id uuid.UUID, identity, via string, approved bool) (bool, error) {
row, err := m.store.ByID(ctx, m.orgID, id)
if errors.Is(err, ErrNotFound) {
return false, nil
}
if err != nil {
return false, err
}
who, err := m.verify(ctx, identity, row)
if refusal(err) {
m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", err.Error())
return false, m.store.Refuse(ctx, store.Refusal{
ID: uuid.New(), OrgID: m.orgID, RequestID: id, Identity: identity, Via: via, Reason: err.Error(), At: m.now().UTC(),
})
}
if err != nil {
return false, err
}
_, err = m.answerAs(ctx, id, who.Name+" ("+identity+")", via, approved)
switch {
case err == nil:
return true, nil
case errors.Is(err, ErrAnswered), errors.Is(err, ErrExpired), errors.Is(err, ErrNotFound):
return false, nil
}
return false, err
}
func (m *Module) verify(ctx context.Context, identity string, row store.Request) (governance.Verified, error) {
who, ok, err := m.people.Verify(ctx, identity)
if err != nil {
return governance.Verified{}, fmt.Errorf("verify %s: %w", identity, err)
}
if !ok {
return governance.Verified{}, ErrUnverified
}
return who, mayAnswer(who, row)
}
func mayAnswer(who governance.Verified, row store.Request) error {
switch {
case row.Kind == KindRaise && !who.Authority:
return ErrNoAuthority
case row.Kind == KindRaise:
return nil
case !who.Approver && !slices.Contains(askedOf(row), who.ID):
return ErrNotApprover
case row.Level == judgement.Escalate.String() && !who.Authority:
return ErrNeedsAuthority
case !who.Authority && !slices.Contains(askedOf(row), who.ID):
return ErrNotAsked
}
return nil
}
func askedOf(row store.Request) []string {
var ids []string
if err := json.Unmarshal([]byte(row.Asked), &ids); err != nil {
return nil
}
return ids
}
// refusal distinguishes a rejected response from an operational error.
func refusal(err error) bool {
return errors.Is(err, ErrUnverified) || errors.Is(err, ErrNotApprover) || errors.Is(err, ErrNoAuthority) ||
errors.Is(err, ErrNotAsked) || errors.Is(err, ErrNeedsAuthority)
}
// Expire records a timeout without reducing the action class's autonomy:
// receiving no response is not a denial.
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)
withdrawn := ""
if row.ChangeRequest {
if err := m.changes.Withdraw(ctx, requestOf(row, judgement.Decision{})); err != nil {
return fmt.Errorf("withdraw change request: %w", err)
}
withdrawn = " Its change request was withdrawn."
}
if err := m.tell.Told(ctx, deliveries.ApprovalRequest{
RunID: row.RunID, RequestID: row.ID, Key: row.Key + ":ask",
Title: "Approval expired", Body: "The approval request expired without a response. The action did not run." + withdrawn,
}, "Expired without an answer."); err != nil {
return err
}
// 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 +
" did not run." + withdrawn + " " + row.Summary,
})
}
// 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
}
// ForRun returns a run's requests in the order they were made.
func (m *Module) ForRun(ctx context.Context, runID uuid.UUID) ([]Request, error) {
rows, err := m.store.ForRun(ctx, m.orgID, runID)
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
}
// Outcomes returns approval outcomes by decision ID for the action class history.
func (m *Module) Outcomes(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]judgement.Outcome, error) {
rows, err := m.store.ByDecisions(ctx, m.orgID, ids)
if err != nil {
return nil, err
}
out := make(map[uuid.UUID]judgement.Outcome, len(rows))
for _, row := range rows {
o := judgement.Outcome{State: row.State}
if row.AnsweredBy.Valid {
o.By = row.AnsweredBy.String
}
if row.AnsweredAt.Valid {
o.At = row.AnsweredAt.Time
}
out[row.DecisionID] = o
}
return out, nil
}
// Register adds the approvals API.
func (m *Module) Register(api huma.API) {
tags := []string{"Approvals"}
huma.Register(api, huma.Operation{
OperationID: "list-approvals", Method: http.MethodGet, Path: "/api/approvals",
Summary: "List approval requests waiting for an answer", Tags: tags,
}, m.list)
huma.Register(api, huma.Operation{
OperationID: "answer-approval", Method: http.MethodPost, Path: "/api/approvals/{id}/answer",
Summary: "Approve or refuse an action as the bootstrap admin", Tags: tags,
}, m.answer)
}
// The token guard authenticates the bootstrap admin before the API handler,
// so the handler does not look up a channel identity.
const bootstrapAdmin = "admin"
type answerInput struct {
ID string `path:"id" format:"uuid"`
Body struct {
Approved bool `json:"approved"`
}
}
func (m *Module) list(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]View], error) {
pending, err := m.Pending(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list approvals", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't list approvals")
}
out := make([]View, 0, len(pending))
for _, p := range pending {
out = append(out, p.View())
}
return httpapi.OK(out), nil
}
func (m *Module) answer(ctx context.Context, in *answerInput) (*httpapi.Reply[View], error) {
id, err := uuid.Parse(in.ID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, "id is a request id")
}
req := in.Body
out, err := m.answerAs(ctx, id, bootstrapAdmin, "composer", req.Approved)
switch {
case errors.Is(err, ErrNotFound):
return nil, huma.NewError(http.StatusNotFound, "no such approval request")
case errors.Is(err, ErrAnswered), errors.Is(err, ErrExpired):
return nil, huma.NewError(http.StatusConflict, err.Error())
case err != nil:
m.log.ErrorContext(ctx, "answer approval", "request", id, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't record the answer")
}
return httpapi.OK(out.View()), nil
}
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
}
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 via %s.", verb, a.By, a.Via)
}
// 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)
if d.Action.Effect.Summary != "" {
s += " " + d.Action.Effect.Summary
}
// The exact input is what is approved, so the person sees every value.
if in := inputLine(d.Action.Input); in != "" {
s += "\nWith: " + in
}
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
}
// inputLine renders an action's input as "key=value" pairs in key order, or
// the raw JSON when it is not a nonempty object.
func inputLine(input jsontext.Value) string {
var fields map[string]jsontext.Value
if err := json.Unmarshal(input, &fields); err != nil || len(fields) == 0 {
return strings.TrimSpace(string(input))
}
parts := make([]string, 0, len(fields))
for _, k := range slices.Sorted(maps.Keys(fields)) {
v := string(fields[k])
var text string
if json.Unmarshal(fields[k], &text) == nil {
v = text
}
parts = append(parts, k+"="+v)
}
return strings.Join(parts, ", ")
}
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, RequestedAt: row.CreatedAt,
Connector: row.Connector, Action: row.Action, TargetKind: row.TargetKind, TargetID: row.TargetID,
Level: row.Level, Summary: row.Summary, State: row.State, Deadline: row.Deadline,
Step: row.Step, ChangeRequest: row.ChangeRequest,
}
if row.StepDeadline.Valid {
r.StepDeadline = row.StepDeadline.Time
}
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
}