feat(judgement,approvals,ui): action classes are records with a level, history and reset; the precedent guard reads the class level (#2003)
This commit is contained in:
15 files changed
+900
-16
No files matched your search
@@ -15,6 +15,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/jmoiron/sqlx"
|
||||||
"github.com/samcharles93/ai-sdk/runtime"
|
"github.com/samcharles93/ai-sdk/runtime"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/buildinfo"
|
"github.com/samcharles93/archie-core/internal/buildinfo"
|
||||||
@@ -85,12 +86,12 @@ func Run(ctx context.Context, configPath string) error {
|
|||||||
engine := runs.New(db, log.With("module", "runs"), runs.Options{Owner: owner()})
|
engine := runs.New(db, log.With("module", "runs"), runs.Options{Owner: owner()})
|
||||||
// A workflow takes its context from the run handle, as a handler takes it
|
// A workflow takes its context from the run handle, as a handler takes it
|
||||||
// from the request.
|
// from the request.
|
||||||
judge := judgement.NewModule(db, log.With("module", "judgement"), orgID, conns, nil,
|
judge, classes := newJudgement(db, log, conns)
|
||||||
[]judgement.Guard{judgement.Reversibility{}, judgement.Precedent{}})
|
|
||||||
// An approval request is carried by deliveries, and its answer wakes the run
|
// An approval request is carried by deliveries, and its answer wakes the run
|
||||||
// that is waiting on it.
|
// that is waiting on it.
|
||||||
allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, engine)
|
allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, engine)
|
||||||
allow.Routes(mux, guard)
|
allow.Routes(mux, guard)
|
||||||
|
classes.Routes(mux, guard, allow)
|
||||||
engine.Register("investigate", runs.Investigate(settings, conns, judge, allow, tell)) //nolint:contextcheck // see above
|
engine.Register("investigate", runs.Investigate(settings, conns, judge, allow, tell)) //nolint:contextcheck // see above
|
||||||
|
|
||||||
// An answer a channel delivers is an event, and settles its request.
|
// An answer a channel delivers is an event, and settles its request.
|
||||||
@@ -101,17 +102,32 @@ func Run(ctx context.Context, configPath string) error {
|
|||||||
|
|
||||||
ctx, stop := context.WithCancel(ctx)
|
ctx, stop := context.WithCancel(ctx)
|
||||||
defer stop()
|
defer stop()
|
||||||
var workers sync.WaitGroup
|
wait := work(ctx, engine.Work, hear.Work, tell.Work)
|
||||||
workers.Go(func() { engine.Work(ctx) })
|
|
||||||
workers.Go(func() { hear.Work(ctx) })
|
|
||||||
workers.Go(func() { tell.Work(ctx) })
|
|
||||||
|
|
||||||
err = serve(ctx, log, cfg.Listen, mux)
|
err = serve(ctx, log, cfg.Listen, mux)
|
||||||
stop()
|
stop()
|
||||||
workers.Wait()
|
wait()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// work runs each loop until ctx ends and returns a function that waits for
|
||||||
|
// them all.
|
||||||
|
func work(ctx context.Context, loops ...func(context.Context)) func() {
|
||||||
|
var workers sync.WaitGroup
|
||||||
|
for _, loop := range loops {
|
||||||
|
workers.Go(func() { loop(ctx) })
|
||||||
|
}
|
||||||
|
return workers.Wait
|
||||||
|
}
|
||||||
|
|
||||||
|
// newJudgement returns the judgement module and the action classes its
|
||||||
|
// precedent guard reads.
|
||||||
|
func newJudgement(db *sqlx.DB, log *slog.Logger, conns judgement.Tools) (*judgement.Module, *judgement.Classes) {
|
||||||
|
classes := judgement.NewClasses(db, log.With("module", "judgement"), orgID)
|
||||||
|
return judgement.NewModule(db, log.With("module", "judgement"), orgID, conns, nil,
|
||||||
|
[]judgement.Guard{judgement.Reversibility{}, judgement.Precedent{Classes: classes}}), classes
|
||||||
|
}
|
||||||
|
|
||||||
// orgID is the one organisation until hosting is multi-tenant.
|
// orgID is the one organisation until hosting is multi-tenant.
|
||||||
const orgID = "default"
|
const orgID = "default"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
-- +goose Up
|
||||||
|
-- An action class is what earned autonomy belongs to: one connector's action on
|
||||||
|
-- one kind of target in one environment. A class is made the first time an
|
||||||
|
-- action of it is judged, at the level its kind of action starts at, and its
|
||||||
|
-- decisions stay in judgement.decisions under the same four names. A target
|
||||||
|
-- that moves environment is a different class, which starts as any new one.
|
||||||
|
CREATE TABLE judgement.classes (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
org_id text NOT NULL,
|
||||||
|
connector text NOT NULL,
|
||||||
|
action text NOT NULL,
|
||||||
|
target_kind text NOT NULL,
|
||||||
|
environment text NOT NULL,
|
||||||
|
read_only boolean NOT NULL,
|
||||||
|
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
reset_at timestamptz,
|
||||||
|
UNIQUE (org_id, connector, action, target_kind, environment)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- A reset returns a class to its default and keeps what led there.
|
||||||
|
CREATE TABLE judgement.class_resets (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
org_id text NOT NULL,
|
||||||
|
class_id uuid NOT NULL REFERENCES judgement.classes (id),
|
||||||
|
from_level text NOT NULL,
|
||||||
|
to_level text NOT NULL,
|
||||||
|
by text NOT NULL,
|
||||||
|
at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX class_resets_by_class ON judgement.class_resets (class_id, at);
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
DROP TABLE judgement.class_resets;
|
||||||
|
DROP TABLE judgement.classes;
|
||||||
@@ -262,6 +262,27 @@ func (m *Module) ForRun(ctx context.Context, runID uuid.UUID) ([]Request, error)
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Outcomes says what became of the requests made for the decisions in ids,
|
||||||
|
// for the history of the action class they belong to.
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
// Routes adds the approvals API to mux behind guard.
|
// Routes adds the approvals API to mux behind guard.
|
||||||
func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) {
|
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("GET /api/approvals", guard(http.HandlerFunc(m.list)))
|
||||||
|
|||||||
@@ -136,5 +136,23 @@ func (s *Store) ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]Re
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ByDecisions returns the requests made for the decisions in ids.
|
||||||
|
func (s *Store) ByDecisions(ctx context.Context, orgID string, ids []uuid.UUID) ([]Request, error) {
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
query, args, err := sqlx.In(`
|
||||||
|
SELECT `+requestColumns+` FROM approvals.requests
|
||||||
|
WHERE org_id = ? AND decision_id IN (?) ORDER BY created_at`, orgID, ids)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("list requests by decision: %w", err)
|
||||||
|
}
|
||||||
|
var out []Request
|
||||||
|
if err := s.db.SelectContext(ctx, &out, s.db.Rebind(query), args...); err != nil {
|
||||||
|
return nil, fmt.Errorf("list requests by decision: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
// ErrNotFound means no request has that id or key.
|
// ErrNotFound means no request has that id or key.
|
||||||
var ErrNotFound = errors.New("no such approval request")
|
var ErrNotFound = errors.New("no such approval request")
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
package judgement
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
json "encoding/json/v2"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jmoiron/sqlx"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||||
|
"github.com/samcharles93/archie-core/modules/judgement/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
// historyLimit bounds the decisions one class's history returns.
|
||||||
|
const historyLimit = 100
|
||||||
|
|
||||||
|
// ErrNoClass means no action class has that id.
|
||||||
|
var ErrNoClass = store.ErrNoClass
|
||||||
|
|
||||||
|
// DefaultLevel is the level a class starts at, and returns to on a reset:
|
||||||
|
// reading starts at act quietly, everything else at propose and wait.
|
||||||
|
func DefaultLevel(readOnly bool) Level {
|
||||||
|
if readOnly {
|
||||||
|
return ActQuietly
|
||||||
|
}
|
||||||
|
return ProposeAndWait
|
||||||
|
}
|
||||||
|
|
||||||
|
// Outcome is what became of a decision's request for approval.
|
||||||
|
type Outcome struct {
|
||||||
|
State string
|
||||||
|
By string
|
||||||
|
At time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Outcomes says what became of decisions that were held for approval. It is
|
||||||
|
// the approvals module's to answer, so a class's history can show it.
|
||||||
|
type Outcomes interface {
|
||||||
|
Outcomes(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]Outcome, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Classes owns one organisation's action classes: the level each stands at and
|
||||||
|
// the history behind it.
|
||||||
|
type Classes struct {
|
||||||
|
orgID string
|
||||||
|
store *store.Store
|
||||||
|
log *slog.Logger
|
||||||
|
now func() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewClasses returns the action classes of orgID.
|
||||||
|
func NewClasses(db *sqlx.DB, log *slog.Logger, orgID string) *Classes {
|
||||||
|
return &Classes{orgID: orgID, store: store.New(db), log: log, now: time.Now}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Level returns the level c stands at, making the class at its default if this
|
||||||
|
// is the first action of it. readOnly is the action's own declaration and is
|
||||||
|
// kept with the class, so a reset knows what its default is.
|
||||||
|
func (c *Classes) Level(ctx context.Context, class Class, readOnly bool) (Level, error) {
|
||||||
|
row, err := c.store.EnsureClass(ctx, store.Class{
|
||||||
|
ID: uuid.New(), OrgID: c.orgID, Connector: class.Connector, Action: class.Action,
|
||||||
|
TargetKind: class.TargetKind, Environment: class.Environment,
|
||||||
|
ReadOnly: readOnly, Level: DefaultLevel(readOnly).String(),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return parseLevel(row.Level)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseLevel(s string) (Level, error) {
|
||||||
|
var l Level
|
||||||
|
if err := l.UnmarshalText([]byte(s)); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return l, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClassView is an action class as the API lists it.
|
||||||
|
type ClassView struct {
|
||||||
|
ID uuid.UUID `json:"id"`
|
||||||
|
Connector string `json:"connector"`
|
||||||
|
Action string `json:"action"`
|
||||||
|
TargetKind string `json:"target_kind"`
|
||||||
|
Environment string `json:"environment"`
|
||||||
|
Level Level `json:"level"`
|
||||||
|
Default Level `json:"default"`
|
||||||
|
Decisions int `json:"decisions"`
|
||||||
|
LastDecidedAt *time.Time `json:"last_decided_at,omitzero"`
|
||||||
|
ResetAt *time.Time `json:"reset_at,omitzero"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// HistoryEntry is one decision in a class's history, with what became of its
|
||||||
|
// request for approval.
|
||||||
|
type HistoryEntry struct {
|
||||||
|
DecisionID uuid.UUID `json:"decision_id"`
|
||||||
|
RunID uuid.UUID `json:"run_id"`
|
||||||
|
Target string `json:"target"`
|
||||||
|
Level Level `json:"level"`
|
||||||
|
Refused string `json:"refused_by,omitzero"`
|
||||||
|
// Approval is the state of the request for approval: pending, approved,
|
||||||
|
// denied or expired. It is empty when none was asked.
|
||||||
|
Approval string `json:"approval,omitzero"`
|
||||||
|
AnsweredBy string `json:"answered_by,omitzero"`
|
||||||
|
At time.Time `json:"at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResetView is one return of a class to its default.
|
||||||
|
type ResetView struct {
|
||||||
|
From Level `json:"from"`
|
||||||
|
To Level `json:"to"`
|
||||||
|
By string `json:"by"`
|
||||||
|
At time.Time `json:"at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClassDetail is a class with its history, newest first.
|
||||||
|
type ClassDetail struct {
|
||||||
|
ClassView
|
||||||
|
History []HistoryEntry `json:"history"`
|
||||||
|
Resets []ResetView `json:"resets"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List returns every class, most recently decided first.
|
||||||
|
func (c *Classes) List(ctx context.Context) ([]ClassView, error) {
|
||||||
|
rows, err := c.store.Classes(ctx, c.orgID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := make([]ClassView, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
v, err := viewOf(r.Class)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
v.Decisions = r.Decisions
|
||||||
|
if r.LastAt.Valid {
|
||||||
|
v.LastDecidedAt = &r.LastAt.Time
|
||||||
|
}
|
||||||
|
out = append(out, v)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func viewOf(r store.Class) (ClassView, error) {
|
||||||
|
level, err := parseLevel(r.Level)
|
||||||
|
if err != nil {
|
||||||
|
return ClassView{}, fmt.Errorf("class %s: %w", r.ID, err)
|
||||||
|
}
|
||||||
|
v := ClassView{
|
||||||
|
ID: r.ID, Connector: r.Connector, Action: r.Action, TargetKind: r.TargetKind,
|
||||||
|
Environment: r.Environment, Level: level, Default: DefaultLevel(r.ReadOnly),
|
||||||
|
}
|
||||||
|
if r.ResetAt.Valid {
|
||||||
|
v.ResetAt = &r.ResetAt.Time
|
||||||
|
}
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detail returns one class with its newest decisions and resets. The approval
|
||||||
|
// outcomes come from outcomes.
|
||||||
|
func (c *Classes) Detail(ctx context.Context, id uuid.UUID, outcomes Outcomes) (ClassDetail, error) {
|
||||||
|
row, err := c.store.ClassByID(ctx, c.orgID, id)
|
||||||
|
if err != nil {
|
||||||
|
return ClassDetail{}, err
|
||||||
|
}
|
||||||
|
view, err := viewOf(row)
|
||||||
|
if err != nil {
|
||||||
|
return ClassDetail{}, err
|
||||||
|
}
|
||||||
|
decisions, err := c.store.ClassDecisions(ctx, row, historyLimit)
|
||||||
|
if err != nil {
|
||||||
|
return ClassDetail{}, err
|
||||||
|
}
|
||||||
|
resets, err := c.store.ClassResets(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return ClassDetail{}, err
|
||||||
|
}
|
||||||
|
ids := make([]uuid.UUID, len(decisions))
|
||||||
|
for i, d := range decisions {
|
||||||
|
ids[i] = d.ID
|
||||||
|
}
|
||||||
|
got, err := outcomes.Outcomes(ctx, ids)
|
||||||
|
if err != nil {
|
||||||
|
return ClassDetail{}, err
|
||||||
|
}
|
||||||
|
detail := ClassDetail{ClassView: view, History: make([]HistoryEntry, 0, len(decisions)), Resets: make([]ResetView, 0, len(resets))}
|
||||||
|
for _, d := range decisions {
|
||||||
|
var body Decision
|
||||||
|
if err := json.Unmarshal(d.Body, &body); err != nil {
|
||||||
|
return ClassDetail{}, fmt.Errorf("decision %s: %w", d.ID, err)
|
||||||
|
}
|
||||||
|
level, err := parseLevel(d.Level)
|
||||||
|
if err != nil {
|
||||||
|
return ClassDetail{}, fmt.Errorf("decision %s: %w", d.ID, err)
|
||||||
|
}
|
||||||
|
o := got[d.ID]
|
||||||
|
detail.History = append(detail.History, HistoryEntry{
|
||||||
|
DecisionID: d.ID, RunID: d.RunID, Target: body.Action.Target.ID, Level: level,
|
||||||
|
Refused: body.RefusedBy, Approval: o.State, AnsweredBy: o.By, At: d.CreatedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
for _, r := range resets {
|
||||||
|
from, err := parseLevel(r.FromLevel)
|
||||||
|
if err != nil {
|
||||||
|
return ClassDetail{}, err
|
||||||
|
}
|
||||||
|
to, err := parseLevel(r.ToLevel)
|
||||||
|
if err != nil {
|
||||||
|
return ClassDetail{}, err
|
||||||
|
}
|
||||||
|
detail.Resets = append(detail.Resets, ResetView{From: from, To: to, By: r.By, At: r.At})
|
||||||
|
}
|
||||||
|
return detail, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset returns a class to its default level. Its decisions and earlier resets
|
||||||
|
// stay.
|
||||||
|
func (c *Classes) Reset(ctx context.Context, id uuid.UUID, by string) (ClassView, error) {
|
||||||
|
row, err := c.store.ClassByID(ctx, c.orgID, id)
|
||||||
|
if err != nil {
|
||||||
|
return ClassView{}, err
|
||||||
|
}
|
||||||
|
row, err = c.store.ResetClass(ctx, c.orgID, id, DefaultLevel(row.ReadOnly).String(), by, c.now().UTC())
|
||||||
|
if err != nil {
|
||||||
|
return ClassView{}, err
|
||||||
|
}
|
||||||
|
return viewOf(row)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bootstrapAdmin names the identity the bootstrap admin token stands for.
|
||||||
|
const bootstrapAdmin = "admin"
|
||||||
|
|
||||||
|
// Routes adds the action classes API to mux behind guard.
|
||||||
|
func (c *Classes) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler, outcomes Outcomes) {
|
||||||
|
mux.Handle("GET /api/classes", guard(http.HandlerFunc(c.list)))
|
||||||
|
mux.Handle("GET /api/classes/{id}", guard(c.detail(outcomes)))
|
||||||
|
mux.Handle("POST /api/classes/{id}/reset", guard(http.HandlerFunc(c.reset)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Classes) list(w http.ResponseWriter, r *http.Request) {
|
||||||
|
out, err := c.List(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
c.log.ErrorContext(r.Context(), "list classes", "error", err)
|
||||||
|
httpjson.Error(w, http.StatusInternalServerError, "couldn't list action classes")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
httpjson.Write(w, http.StatusOK, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Classes) detail(outcomes Outcomes) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := classID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out, err := c.Detail(r.Context(), id, outcomes)
|
||||||
|
if !c.found(w, r, err) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
httpjson.Write(w, http.StatusOK, out)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Classes) reset(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := classID(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out, err := c.Reset(r.Context(), id, bootstrapAdmin)
|
||||||
|
if !c.found(w, r, err) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
httpjson.Write(w, http.StatusOK, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
func classID(w http.ResponseWriter, r *http.Request) (uuid.UUID, bool) {
|
||||||
|
id, err := uuid.Parse(r.PathValue("id"))
|
||||||
|
if err != nil {
|
||||||
|
httpjson.Error(w, http.StatusBadRequest, "id is a class id")
|
||||||
|
return uuid.Nil, false
|
||||||
|
}
|
||||||
|
return id, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// found writes the error response for err and reports whether there was none.
|
||||||
|
func (c *Classes) found(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
return true
|
||||||
|
case errors.Is(err, ErrNoClass):
|
||||||
|
httpjson.Error(w, http.StatusNotFound, "no such action class")
|
||||||
|
default:
|
||||||
|
c.log.ErrorContext(r.Context(), "action class", "path", r.URL.Path, "error", err)
|
||||||
|
httpjson.Error(w, http.StatusInternalServerError, "couldn't read the action class")
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package judgement
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/modules/connectors"
|
"github.com/samcharles93/archie-core/modules/connectors"
|
||||||
)
|
)
|
||||||
@@ -33,10 +34,17 @@ func (Reversibility) Judge(_ context.Context, a Action) (Verdict, error) {
|
|||||||
return Verdict{}, errors.New("the connector declares no reversibility for this action")
|
return Verdict{}, errors.New("the connector declares no reversibility for this action")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Precedent sets a ceiling from the action class's earned level. Until a
|
// ClassLevels says what level an action class stands at.
|
||||||
// class has history, it is the fresh-install default: read-only classes act
|
type ClassLevels interface {
|
||||||
// quietly, every other class proposes and waits.
|
Level(ctx context.Context, c Class, readOnly bool) (Level, error)
|
||||||
type Precedent struct{}
|
}
|
||||||
|
|
||||||
|
// Precedent sets a ceiling from the action class's current level. A class
|
||||||
|
// starts at its default (read-only classes act quietly, every other class
|
||||||
|
// proposes and waits) and stays wherever its history has put it.
|
||||||
|
type Precedent struct {
|
||||||
|
Classes ClassLevels
|
||||||
|
}
|
||||||
|
|
||||||
// Name is the guard's name in verdicts.
|
// Name is the guard's name in verdicts.
|
||||||
func (Precedent) Name() string { return "precedent" }
|
func (Precedent) Name() string { return "precedent" }
|
||||||
@@ -45,9 +53,10 @@ func (Precedent) Name() string { return "precedent" }
|
|||||||
func (Precedent) Advisory() bool { return false }
|
func (Precedent) Advisory() bool { return false }
|
||||||
|
|
||||||
// Judge returns the class's level.
|
// Judge returns the class's level.
|
||||||
func (Precedent) Judge(_ context.Context, a Action) (Verdict, error) {
|
func (p Precedent) Judge(ctx context.Context, a Action) (Verdict, error) {
|
||||||
if a.Effect.ReadOnly {
|
level, err := p.Classes.Level(ctx, a.Class(), a.Effect.ReadOnly)
|
||||||
return Verdict{Ceiling: ActQuietly}, nil
|
if err != nil {
|
||||||
|
return Verdict{}, fmt.Errorf("read class level: %w", err)
|
||||||
}
|
}
|
||||||
return Verdict{Ceiling: ProposeAndWait, Findings: []Finding{{Text: "this action class has no approvals yet"}}}, nil
|
return Verdict{Ceiling: level, Findings: []Finding{{Text: "this action class is at " + level.String()}}}, nil
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrNoClass means no class has that id.
|
||||||
|
var ErrNoClass = errors.New("no such action class")
|
||||||
|
|
||||||
|
// Class is one action class and the level it stands at.
|
||||||
|
type Class struct {
|
||||||
|
ID uuid.UUID `db:"id"`
|
||||||
|
OrgID string `db:"org_id"`
|
||||||
|
Connector string `db:"connector"`
|
||||||
|
Action string `db:"action"`
|
||||||
|
TargetKind string `db:"target_kind"`
|
||||||
|
Environment string `db:"environment"`
|
||||||
|
ReadOnly bool `db:"read_only"`
|
||||||
|
Level string `db:"level"`
|
||||||
|
CreatedAt time.Time `db:"created_at"`
|
||||||
|
ResetAt sql.NullTime `db:"reset_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClassSummary is a class with how many decisions it holds.
|
||||||
|
type ClassSummary struct {
|
||||||
|
Class
|
||||||
|
Decisions int `db:"decisions"`
|
||||||
|
LastAt sql.NullTime `db:"last_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset is one return of a class to its default.
|
||||||
|
type Reset struct {
|
||||||
|
ID uuid.UUID `db:"id"`
|
||||||
|
FromLevel string `db:"from_level"`
|
||||||
|
ToLevel string `db:"to_level"`
|
||||||
|
By string `db:"by"`
|
||||||
|
At time.Time `db:"at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const classColumns = `id, org_id, connector, action, target_kind, environment, read_only, level, created_at, reset_at`
|
||||||
|
|
||||||
|
// EnsureClass returns the class c names, creating it at c.Level when it is
|
||||||
|
// new. An existing class keeps its level.
|
||||||
|
func (s *Store) EnsureClass(ctx context.Context, c Class) (Class, error) {
|
||||||
|
var out Class
|
||||||
|
err := s.db.GetContext(ctx, &out, `
|
||||||
|
INSERT INTO judgement.classes (id, org_id, connector, action, target_kind, environment, read_only, level)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||||
|
ON CONFLICT (org_id, connector, action, target_kind, environment)
|
||||||
|
DO UPDATE SET read_only = judgement.classes.read_only
|
||||||
|
RETURNING `+classColumns,
|
||||||
|
c.ID, c.OrgID, c.Connector, c.Action, c.TargetKind, c.Environment, c.ReadOnly, c.Level)
|
||||||
|
if err != nil {
|
||||||
|
return Class{}, fmt.Errorf("ensure class: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Classes returns every class, most recently decided first.
|
||||||
|
func (s *Store) Classes(ctx context.Context, orgID string) ([]ClassSummary, error) {
|
||||||
|
var out []ClassSummary
|
||||||
|
err := s.db.SelectContext(ctx, &out, `
|
||||||
|
SELECT c.id, c.org_id, c.connector, c.action, c.target_kind, c.environment, c.read_only, c.level,
|
||||||
|
c.created_at, c.reset_at, count(d.id) AS decisions, max(d.created_at) AS last_at
|
||||||
|
FROM judgement.classes c
|
||||||
|
LEFT JOIN judgement.decisions d ON d.org_id = c.org_id AND d.connector = c.connector
|
||||||
|
AND d.action = c.action AND d.target_kind = c.target_kind AND d.environment = c.environment
|
||||||
|
WHERE c.org_id = $1
|
||||||
|
GROUP BY c.id
|
||||||
|
ORDER BY coalesce(max(d.created_at), c.created_at) DESC, c.id`, orgID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("list classes: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClassByID returns one class.
|
||||||
|
func (s *Store) ClassByID(ctx context.Context, orgID string, id uuid.UUID) (Class, error) {
|
||||||
|
var out Class
|
||||||
|
err := s.db.GetContext(ctx, &out, `SELECT `+classColumns+` FROM judgement.classes WHERE org_id = $1 AND id = $2`, orgID, id)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return Class{}, ErrNoClass
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return Class{}, fmt.Errorf("read class: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClassDecisions returns a class's newest decisions, newest first.
|
||||||
|
func (s *Store) ClassDecisions(ctx context.Context, c Class, limit int) ([]Decision, error) {
|
||||||
|
var out []Decision
|
||||||
|
err := s.db.SelectContext(ctx, &out, `
|
||||||
|
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body, created_at
|
||||||
|
FROM judgement.decisions
|
||||||
|
WHERE org_id = $1 AND connector = $2 AND action = $3 AND target_kind = $4 AND environment = $5
|
||||||
|
ORDER BY created_at DESC, id LIMIT $6`,
|
||||||
|
c.OrgID, c.Connector, c.Action, c.TargetKind, c.Environment, limit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("list class decisions: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClassResets returns a class's resets, newest first.
|
||||||
|
func (s *Store) ClassResets(ctx context.Context, id uuid.UUID) ([]Reset, error) {
|
||||||
|
var out []Reset
|
||||||
|
err := s.db.SelectContext(ctx, &out, `
|
||||||
|
SELECT id, from_level, to_level, by, at FROM judgement.class_resets
|
||||||
|
WHERE class_id = $1 ORDER BY at DESC, id`, id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("list class resets: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResetClass sets a class to level and records the reset, in one transaction.
|
||||||
|
func (s *Store) ResetClass(ctx context.Context, orgID string, id uuid.UUID, level, by string, at time.Time) (Class, error) {
|
||||||
|
tx, err := s.db.BeginTxx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return Class{}, fmt.Errorf("reset class: %w", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = tx.Rollback() }()
|
||||||
|
var before Class
|
||||||
|
err = tx.GetContext(ctx, &before, `SELECT `+classColumns+` FROM judgement.classes WHERE org_id = $1 AND id = $2 FOR UPDATE`, orgID, id)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return Class{}, ErrNoClass
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return Class{}, fmt.Errorf("reset class: %w", err)
|
||||||
|
}
|
||||||
|
var out Class
|
||||||
|
if err := tx.GetContext(ctx, &out, `
|
||||||
|
UPDATE judgement.classes SET level = $2, reset_at = $3 WHERE id = $1 RETURNING `+classColumns, id, level, at); err != nil {
|
||||||
|
return Class{}, fmt.Errorf("reset class: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx, `
|
||||||
|
INSERT INTO judgement.class_resets (id, org_id, class_id, from_level, to_level, by, at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7)`, uuid.New(), orgID, id, before.Level, level, by, at); err != nil {
|
||||||
|
return Class{}, fmt.Errorf("record reset: %w", err)
|
||||||
|
}
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return Class{}, fmt.Errorf("reset class: %w", err)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/jmoiron/sqlx"
|
"github.com/jmoiron/sqlx"
|
||||||
@@ -24,6 +25,8 @@ type Decision struct {
|
|||||||
Environment string `db:"environment"`
|
Environment string `db:"environment"`
|
||||||
Level string `db:"level"`
|
Level string `db:"level"`
|
||||||
Body []byte `db:"body"`
|
Body []byte `db:"body"`
|
||||||
|
// CreatedAt is set by the database and read only by the class history.
|
||||||
|
CreatedAt time.Time `db:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Store is the judgement module's Postgres store.
|
// Store is the judgement module's Postgres store.
|
||||||
|
|||||||
@@ -266,3 +266,35 @@ func TestExecuteApprovedRunsOnlyWhatThePersonSaw(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type classLevel struct{ level Level }
|
||||||
|
|
||||||
|
func (c classLevel) Level(context.Context, Class, bool) (Level, error) { return c.level, nil }
|
||||||
|
|
||||||
|
// TestPrecedentCeilingIsTheClassLevel guards the earned-autonomy seam: the
|
||||||
|
// precedent guard's ceiling is the level its action class stands at, not a
|
||||||
|
// default, so a class that was reset, raised or lowered judges accordingly.
|
||||||
|
func TestPrecedentCeilingIsTheClassLevel(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
level Level
|
||||||
|
read bool
|
||||||
|
}{
|
||||||
|
{name: "a read-only class at its default", level: ActQuietly, read: true},
|
||||||
|
{name: "a changing class raised to act and tell", level: ActAndTell},
|
||||||
|
{name: "a changing class at its default", level: ProposeAndWait},
|
||||||
|
{name: "a read-only class lowered to escalate", level: Escalate, read: true},
|
||||||
|
{name: "a class that never runs", level: Never},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
v, err := Precedent{Classes: classLevel{tt.level}}.Judge(t.Context(), Action{Effect: connectors.Effect{ReadOnly: tt.read}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if v.Ceiling != tt.level {
|
||||||
|
t.Fatalf("ceiling = %s, want the class level %s", v.Ceiling, tt.level)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,6 +34,7 @@ function signOut() {
|
|||||||
<nav v-if="signedIn" class="flex flex-1 items-center gap-3 text-label">
|
<nav v-if="signedIn" class="flex flex-1 items-center gap-3 text-label">
|
||||||
<RouterLink to="/composer" active-class="text-foreground" class="text-muted-foreground">Composer</RouterLink>
|
<RouterLink to="/composer" active-class="text-foreground" class="text-muted-foreground">Composer</RouterLink>
|
||||||
<RouterLink to="/runs" active-class="text-foreground" class="text-muted-foreground">Runs</RouterLink>
|
<RouterLink to="/runs" active-class="text-foreground" class="text-muted-foreground">Runs</RouterLink>
|
||||||
|
<RouterLink to="/classes" active-class="text-foreground" class="text-muted-foreground">Classes</RouterLink>
|
||||||
<RouterLink to="/settings" active-class="text-foreground" class="text-muted-foreground">Settings</RouterLink>
|
<RouterLink to="/settings" active-class="text-foreground" class="text-muted-foreground">Settings</RouterLink>
|
||||||
<Button variant="ghost" size="xs" class="ml-auto" @click="signOut">Sign out</Button>
|
<Button variant="ghost" size="xs" class="ml-auto" @click="signOut">Sign out</Button>
|
||||||
</nav>
|
</nav>
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onBeforeUnmount, ref, watch } from "vue";
|
||||||
|
import { useRouter } from "vue-router";
|
||||||
|
|
||||||
|
import PageHeader from "@/base/PageHeader.vue";
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from "@/components/ui/alert-dialog";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||||
|
import { ReadError } from "@/components/ui/read-error";
|
||||||
|
import { Section } from "@/components/ui/section";
|
||||||
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||||
|
import { Timestamp } from "@/components/ui/timestamp";
|
||||||
|
import { type ClassDetail, classDetail, resetClass, Unauthorized } from "./api";
|
||||||
|
import { className, levelLabel } from "./state";
|
||||||
|
|
||||||
|
/** One action class: its level, and every decision made in it. */
|
||||||
|
const props = defineProps<{ id: string }>();
|
||||||
|
const emit = defineEmits<{ unauthorized: [] }>();
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const detail = ref<ClassDetail>();
|
||||||
|
const loading = ref(true);
|
||||||
|
const error = ref("");
|
||||||
|
const confirming = ref(false);
|
||||||
|
const resetting = ref(false);
|
||||||
|
let controller = new AbortController();
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
controller.abort();
|
||||||
|
controller = new AbortController();
|
||||||
|
const signal = controller.signal;
|
||||||
|
loading.value = true;
|
||||||
|
error.value = "";
|
||||||
|
try {
|
||||||
|
const got = await classDetail(props.id, signal);
|
||||||
|
if (!signal.aborted) detail.value = got;
|
||||||
|
} catch (err) {
|
||||||
|
fail(err, signal);
|
||||||
|
} finally {
|
||||||
|
if (!signal.aborted) loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reset() {
|
||||||
|
resetting.value = true;
|
||||||
|
error.value = "";
|
||||||
|
try {
|
||||||
|
await resetClass(props.id);
|
||||||
|
await load();
|
||||||
|
} catch (err) {
|
||||||
|
fail(err, controller.signal);
|
||||||
|
} finally {
|
||||||
|
resetting.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fail(err: unknown, signal: AbortSignal) {
|
||||||
|
if (signal.aborted) return;
|
||||||
|
if (err instanceof Unauthorized) emit("unauthorized");
|
||||||
|
error.value = err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(() => props.id, load, { immediate: true });
|
||||||
|
onBeforeUnmount(() => controller.abort());
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<Spinner v-if="loading && !detail" />
|
||||||
|
<ReadError v-else-if="error && !detail" :message="error" retry-label="Retry" @retry="load" />
|
||||||
|
<template v-else-if="detail">
|
||||||
|
<PageHeader :title="className(detail)">
|
||||||
|
<Badge variant="outline">{{ levelLabel(detail.level) }}</Badge>
|
||||||
|
<Button variant="outline" size="sm" :disabled="resetting || detail.level === detail.default" @click="confirming = true">
|
||||||
|
Reset to {{ levelLabel(detail.default).toLowerCase() }}
|
||||||
|
</Button>
|
||||||
|
</PageHeader>
|
||||||
|
<ReadError v-if="error" :message="error" retry-label="Retry" @retry="load" />
|
||||||
|
<Section title="History">
|
||||||
|
<Empty v-if="detail.history.length === 0">
|
||||||
|
<EmptyHeader><EmptyTitle>No decisions yet</EmptyTitle></EmptyHeader>
|
||||||
|
</Empty>
|
||||||
|
<Table v-else>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Target</TableHead>
|
||||||
|
<TableHead>Level</TableHead>
|
||||||
|
<TableHead>Approval</TableHead>
|
||||||
|
<TableHead>When</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
<TableRow
|
||||||
|
v-for="h in detail.history"
|
||||||
|
:key="h.decision_id"
|
||||||
|
class="cursor-pointer"
|
||||||
|
tabindex="0"
|
||||||
|
@click="router.push({ name: 'run', params: { id: h.run_id } })"
|
||||||
|
@keydown.enter="router.push({ name: 'run', params: { id: h.run_id } })"
|
||||||
|
>
|
||||||
|
<TableCell>{{ h.target }}</TableCell>
|
||||||
|
<TableCell>{{ h.refused_by ? `Refused by ${h.refused_by}` : levelLabel(h.level) }}</TableCell>
|
||||||
|
<TableCell>{{ h.approval }}<template v-if="h.answered_by"> by {{ h.answered_by }}</template></TableCell>
|
||||||
|
<TableCell><Timestamp :at="h.at" /></TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</Section>
|
||||||
|
<Section v-if="detail.resets.length > 0" title="Resets" class="mt-4">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>From</TableHead>
|
||||||
|
<TableHead>To</TableHead>
|
||||||
|
<TableHead>By</TableHead>
|
||||||
|
<TableHead>When</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
<TableRow v-for="r in detail.resets" :key="r.at">
|
||||||
|
<TableCell>{{ levelLabel(r.from) }}</TableCell>
|
||||||
|
<TableCell>{{ levelLabel(r.to) }}</TableCell>
|
||||||
|
<TableCell>{{ r.by }}</TableCell>
|
||||||
|
<TableCell><Timestamp :at="r.at" /></TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</Section>
|
||||||
|
<AlertDialog :open="confirming" @update:open="(v: boolean) => (confirming = v)">
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>Reset class?</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
{{ className(detail) }} returns to {{ levelLabel(detail.default).toLowerCase() }}. Its history stays.
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||||
|
<AlertDialogAction @click="reset">Reset</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||||
|
import { useRouter } from "vue-router";
|
||||||
|
|
||||||
|
import PageHeader from "@/base/PageHeader.vue";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||||
|
import { ReadError } from "@/components/ui/read-error";
|
||||||
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||||
|
import { Timestamp } from "@/components/ui/timestamp";
|
||||||
|
import { type ActionClass, listClasses, Unauthorized } from "./api";
|
||||||
|
import { levelLabel } from "./state";
|
||||||
|
|
||||||
|
const emit = defineEmits<{ unauthorized: [] }>();
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const classes = ref<ActionClass[]>([]);
|
||||||
|
const loading = ref(true);
|
||||||
|
const error = ref("");
|
||||||
|
const controller = new AbortController();
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
loading.value = true;
|
||||||
|
error.value = "";
|
||||||
|
try {
|
||||||
|
classes.value = await listClasses(controller.signal);
|
||||||
|
} catch (err) {
|
||||||
|
if (controller.signal.aborted) return;
|
||||||
|
if (err instanceof Unauthorized) emit("unauthorized");
|
||||||
|
error.value = err instanceof Error ? err.message : String(err);
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const open = (id: string) => router.push({ name: "class", params: { id } });
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
onBeforeUnmount(() => controller.abort());
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<PageHeader title="Classes" />
|
||||||
|
<Spinner v-if="loading" />
|
||||||
|
<ReadError v-else-if="error" :message="error" retry-label="Retry" @retry="load" />
|
||||||
|
<Empty v-else-if="classes.length === 0">
|
||||||
|
<EmptyHeader><EmptyTitle>No action classes yet</EmptyTitle></EmptyHeader>
|
||||||
|
</Empty>
|
||||||
|
<Table v-else>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Action</TableHead>
|
||||||
|
<TableHead>Target</TableHead>
|
||||||
|
<TableHead>Environment</TableHead>
|
||||||
|
<TableHead>Level</TableHead>
|
||||||
|
<TableHead>Decisions</TableHead>
|
||||||
|
<TableHead>Last</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
<TableRow v-for="c in classes" :key="c.id" class="cursor-pointer" tabindex="0" @click="open(c.id)" @keydown.enter="open(c.id)">
|
||||||
|
<TableCell>{{ c.connector }} {{ c.action }}</TableCell>
|
||||||
|
<TableCell>{{ c.target_kind }}</TableCell>
|
||||||
|
<TableCell>{{ c.environment }}</TableCell>
|
||||||
|
<TableCell><Badge variant="outline">{{ levelLabel(c.level) }}</Badge></TableCell>
|
||||||
|
<TableCell>{{ c.decisions }}</TableCell>
|
||||||
|
<TableCell><Timestamp v-if="c.last_decided_at" :at="c.last_decided_at" /></TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -174,6 +174,54 @@ export async function answerApproval(id: string, approved: boolean): Promise<voi
|
|||||||
throw new Error(body.error ?? `${res.status} ${res.statusText}`);
|
throw new Error(body.error ?? `${res.status} ${res.statusText}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
export type Level = "act_quietly" | "act_and_tell" | "propose_and_wait" | "escalate" | "never";
|
||||||
|
|
||||||
|
export interface ActionClass {
|
||||||
|
id: string;
|
||||||
|
connector: string;
|
||||||
|
action: string;
|
||||||
|
target_kind: string;
|
||||||
|
environment: string;
|
||||||
|
level: Level;
|
||||||
|
default: Level;
|
||||||
|
decisions: number;
|
||||||
|
last_decided_at?: string;
|
||||||
|
reset_at?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HistoryEntry {
|
||||||
|
decision_id: string;
|
||||||
|
run_id: string;
|
||||||
|
target: string;
|
||||||
|
level: Level;
|
||||||
|
refused_by?: string;
|
||||||
|
approval?: "pending" | "approved" | "denied" | "expired";
|
||||||
|
answered_by?: string;
|
||||||
|
at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClassDetail extends ActionClass {
|
||||||
|
history: HistoryEntry[];
|
||||||
|
resets: { from: Level; to: Level; by: string; at: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const listClasses = (signal?: AbortSignal) => get<ActionClass[]>("/api/classes", signal);
|
||||||
|
export const classDetail = (id: string, signal?: AbortSignal) =>
|
||||||
|
get<ClassDetail>(`/api/classes/${encodeURIComponent(id)}`, signal);
|
||||||
|
|
||||||
|
/** Returns an action class to its default level; its history stays. */
|
||||||
|
export async function resetClass(id: string): Promise<void> {
|
||||||
|
const res = await fetch(`/api/classes/${encodeURIComponent(id)}/reset`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { Authorization: `Bearer ${token()}` },
|
||||||
|
});
|
||||||
|
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<Run[]>("/api/runs", signal);
|
export const listRuns = (signal?: AbortSignal) => get<Run[]>("/api/runs", signal);
|
||||||
export const runTrail = (id: string, signal?: AbortSignal) => get<Trail>(`/api/runs/${encodeURIComponent(id)}`, signal);
|
export const runTrail = (id: string, signal?: AbortSignal) => get<Trail>(`/api/runs/${encodeURIComponent(id)}`, signal);
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ export default createRouter({
|
|||||||
{ path: "/", redirect: "/composer" },
|
{ path: "/", redirect: "/composer" },
|
||||||
{ path: "/composer", name: "composer", component: () => import("./ComposerView.vue") },
|
{ path: "/composer", name: "composer", component: () => import("./ComposerView.vue") },
|
||||||
{ path: "/runs", name: "runs", component: () => import("./RunsView.vue") },
|
{ path: "/runs", name: "runs", component: () => import("./RunsView.vue") },
|
||||||
|
{ path: "/classes", name: "classes", component: () => import("./ClassesView.vue") },
|
||||||
|
{ path: "/classes/:id", name: "class", component: () => import("./ClassView.vue"), props: true },
|
||||||
{ path: "/settings", name: "settings", component: () => import("./SettingsView.vue") },
|
{ path: "/settings", name: "settings", component: () => import("./SettingsView.vue") },
|
||||||
{ path: "/runs/:id", name: "run", component: () => import("./RunView.vue"), props: true },
|
{ path: "/runs/:id", name: "run", component: () => import("./RunView.vue"), props: true },
|
||||||
],
|
],
|
||||||
|
|||||||
+15
-1
@@ -1,4 +1,4 @@
|
|||||||
import type { Run } from "./api";
|
import type { Level, Run } from "./api";
|
||||||
|
|
||||||
/** The StatusDot tone for a run's state. */
|
/** The StatusDot tone for a run's state. */
|
||||||
export function runTone(state: Run["state"]): "ok" | "warn" | "danger" | "info" | "idle" {
|
export function runTone(state: Run["state"]): "ok" | "warn" | "danger" | "info" | "idle" {
|
||||||
@@ -16,3 +16,17 @@ export function runTone(state: Run["state"]): "ok" | "warn" | "danger" | "info"
|
|||||||
return "idle";
|
return "idle";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const levelLabels: Record<Level, string> = {
|
||||||
|
act_quietly: "Act quietly",
|
||||||
|
act_and_tell: "Act and tell",
|
||||||
|
propose_and_wait: "Propose and wait",
|
||||||
|
escalate: "Escalate",
|
||||||
|
never: "Never",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const levelLabel = (level: Level): string => levelLabels[level];
|
||||||
|
|
||||||
|
/** The class's own names, as one line. */
|
||||||
|
export const className = (c: { connector: string; action: string; target_kind: string; environment: string }): string =>
|
||||||
|
`${c.connector} ${c.action} on ${c.target_kind} in ${c.environment || "no environment"}`;
|
||||||
Reference in new issue
Block a user