Agents can now ask to publish or schedule a post, send an email, add someone to a mailing list, or apply an SEO change. Each waits on the Approvals page (with a count in the sidebar) for an admin or a member with edit on its module, who can edit it first, approve or refuse it, and let the agent take that class of action on its own with a cap per day. A rotation after a leak revokes the old keys and withdraws everything allowed. All of it is in the audit log. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
255 lines
7.5 KiB
Go
255 lines
7.5 KiB
Go
// Package approvals holds what agents ask to send out of Supermarket (a
|
|
// post, an email, a mailing-list add, a change to a site) until a person
|
|
// says yes or no, and the kinds of action a person has let an agent take
|
|
// on its own, each with a cap per day.
|
|
package approvals
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"time"
|
|
|
|
"supermarket/internal/db"
|
|
)
|
|
|
|
// Statuses.
|
|
const (
|
|
Waiting = "waiting"
|
|
Done = "done" // approved and carried out (or done on its own)
|
|
Refused = "refused"
|
|
Failed = "failed" // approved, but carrying it out failed
|
|
)
|
|
|
|
// Request is something an agent asked to do.
|
|
type Request struct {
|
|
ID int64
|
|
Agent int64
|
|
Class string
|
|
Module string
|
|
Target int64
|
|
Params map[string]string
|
|
Summary string
|
|
Status string
|
|
Created time.Time
|
|
Decided time.Time
|
|
DecidedBy int64 // 0 with Done: on its own
|
|
Result string
|
|
}
|
|
|
|
// OnItsOwn says whether the agent did it without asking.
|
|
func (r *Request) OnItsOwn() bool {
|
|
return r.Status != Waiting && r.Status != Refused && r.DecidedBy == 0
|
|
}
|
|
|
|
// Grant lets an agent take a class of action on its own.
|
|
type Grant struct {
|
|
Agent int64
|
|
Class string
|
|
Label string
|
|
Module string
|
|
DailyCap int // 0: none
|
|
GrantedBy int64
|
|
Granted time.Time
|
|
}
|
|
|
|
const timeFormat = "2006-01-02T15:04:05.000Z"
|
|
|
|
func ts(t time.Time) string {
|
|
if t.IsZero() {
|
|
return ""
|
|
}
|
|
return t.UTC().Format(timeFormat)
|
|
}
|
|
|
|
func parseTS(s string) time.Time {
|
|
t, _ := time.Parse(timeFormat, s)
|
|
return t
|
|
}
|
|
|
|
var ErrNotFound = errors.New("no such request")
|
|
|
|
// ErrDecided is a request someone has already decided.
|
|
var ErrDecided = errors.New("this request was already decided")
|
|
|
|
// Add records a request, waiting (or, done on its own, with its result).
|
|
func Add(d *db.DB, r *Request, now time.Time) error {
|
|
params, _ := json.Marshal(r.Params)
|
|
if r.Status == "" {
|
|
r.Status = Waiting
|
|
}
|
|
r.Created = now
|
|
decided := ""
|
|
if r.Status != Waiting {
|
|
r.Decided = now
|
|
decided = ts(now)
|
|
}
|
|
var err error
|
|
r.ID, err = d.Insert(`INSERT INTO approvals (agent_id, class, module, target_id, params, summary, status, created_at, decided_at, decided_by, result)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, r.Agent, r.Class, r.Module, r.Target, string(params), r.Summary, r.Status, ts(now), decided, r.DecidedBy, r.Result)
|
|
return err
|
|
}
|
|
|
|
const cols = `id, agent_id, class, module, target_id, params, summary, status, created_at, decided_at, decided_by, result`
|
|
|
|
func scan(row interface{ Scan(...any) error }) (*Request, error) {
|
|
var r Request
|
|
var params, created, decided string
|
|
if err := row.Scan(&r.ID, &r.Agent, &r.Class, &r.Module, &r.Target, ¶ms, &r.Summary, &r.Status, &created, &decided, &r.DecidedBy, &r.Result); err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
_ = json.Unmarshal([]byte(params), &r.Params)
|
|
if r.Params == nil {
|
|
r.Params = map[string]string{}
|
|
}
|
|
r.Created, r.Decided = parseTS(created), parseTS(decided)
|
|
return &r, nil
|
|
}
|
|
|
|
// Get finds a request.
|
|
func Get(d *db.DB, id int64) (*Request, error) {
|
|
return scan(d.QueryRow(`SELECT `+cols+` FROM approvals WHERE id = ?`, id))
|
|
}
|
|
|
|
// List are requests with a status (all, if ""), newest first; agent 0 for
|
|
// every agent's.
|
|
func List(d *db.DB, status string, agent int64, limit int) ([]Request, error) {
|
|
q := `SELECT ` + cols + ` FROM approvals WHERE 1 = 1`
|
|
var args []any
|
|
if status != "" {
|
|
q += ` AND status = ?`
|
|
args = append(args, status)
|
|
}
|
|
if agent != 0 {
|
|
q += ` AND agent_id = ?`
|
|
args = append(args, agent)
|
|
}
|
|
q += ` ORDER BY id DESC LIMIT ?`
|
|
args = append(args, limit)
|
|
rows, err := d.Query(q, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []Request
|
|
for rows.Next() {
|
|
r, err := scan(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, *r)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// Claim takes a waiting request for a decision, once: of two people
|
|
// deciding together, one gets ErrDecided.
|
|
func Claim(d *db.DB, id, by int64, status string, now time.Time) error {
|
|
res, err := d.Exec(`UPDATE approvals SET status = ?, decided_at = ?, decided_by = ? WHERE id = ? AND status = ?`,
|
|
status, ts(now), by, id, Waiting)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n, _ := res.RowsAffected(); n != 1 {
|
|
return ErrDecided
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Finish records how carrying out an approved request went.
|
|
func Finish(d *db.DB, id int64, failed error) error {
|
|
status, result := Done, ""
|
|
if failed != nil {
|
|
status, result = Failed, failed.Error()
|
|
}
|
|
_, err := d.Exec(`UPDATE approvals SET status = ?, result = ? WHERE id = ?`, status, result, id)
|
|
return err
|
|
}
|
|
|
|
// SetResult notes what a done request led to (a post's address).
|
|
func SetResult(d *db.DB, id int64, result string) error {
|
|
_, err := d.Exec(`UPDATE approvals SET result = ? WHERE id = ?`, result, id)
|
|
return err
|
|
}
|
|
|
|
// Pending says whether there's already a waiting request for the same
|
|
// class and target: asking twice doesn't make two.
|
|
func Pending(d *db.DB, class string, target int64) (*Request, error) {
|
|
r, err := scan(d.QueryRow(`SELECT `+cols+` FROM approvals WHERE class = ? AND target_id = ? AND status = ? ORDER BY id LIMIT 1`, class, target, Waiting))
|
|
if errors.Is(err, ErrNotFound) {
|
|
return nil, nil
|
|
}
|
|
return r, err
|
|
}
|
|
|
|
// Grants.
|
|
|
|
// Allow lets an agent take a class of action on its own (or changes its cap).
|
|
func Allow(d *db.DB, g Grant, now time.Time) error {
|
|
_, err := d.Exec(`INSERT INTO agent_autonomy (agent_id, class, label, module, daily_cap, granted_by, granted_at) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT (agent_id, class) DO UPDATE SET daily_cap = excluded.daily_cap, label = excluded.label, granted_by = excluded.granted_by, granted_at = excluded.granted_at`,
|
|
g.Agent, g.Class, g.Label, g.Module, g.DailyCap, g.GrantedBy, ts(now))
|
|
return err
|
|
}
|
|
|
|
// Withdraw takes a class back.
|
|
func Withdraw(d *db.DB, agent int64, class string) error {
|
|
_, err := d.Exec(`DELETE FROM agent_autonomy WHERE agent_id = ? AND class = ?`, agent, class)
|
|
return err
|
|
}
|
|
|
|
// WithdrawAll takes everything back from an agent (its key leaked).
|
|
func WithdrawAll(d *db.DB, agent int64) error {
|
|
_, err := d.Exec(`DELETE FROM agent_autonomy WHERE agent_id = ?`, agent)
|
|
return err
|
|
}
|
|
|
|
// Grants are what agents may do on their own: agent 0 for all.
|
|
func Grants(d *db.DB, agent int64) ([]Grant, error) {
|
|
q := `SELECT agent_id, class, label, module, daily_cap, granted_by, granted_at FROM agent_autonomy`
|
|
var args []any
|
|
if agent != 0 {
|
|
q += ` WHERE agent_id = ?`
|
|
args = append(args, agent)
|
|
}
|
|
rows, err := d.Query(q+` ORDER BY agent_id, class`, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []Grant
|
|
for rows.Next() {
|
|
var g Grant
|
|
var at string
|
|
if err := rows.Scan(&g.Agent, &g.Class, &g.Label, &g.Module, &g.DailyCap, &g.GrantedBy, &at); err != nil {
|
|
return nil, err
|
|
}
|
|
g.Granted = parseTS(at)
|
|
out = append(out, g)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// Allowed says whether an agent may take a class of action on its own
|
|
// now: it was granted, and today's count is under the cap.
|
|
func Allowed(d *db.DB, agent int64, class string, now time.Time) (bool, error) {
|
|
var cap int
|
|
err := d.QueryRow(`SELECT daily_cap FROM agent_autonomy WHERE agent_id = ? AND class = ?`, agent, class).Scan(&cap)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return false, nil
|
|
}
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if cap == 0 {
|
|
return true, nil
|
|
}
|
|
var n int
|
|
err = d.QueryRow(`SELECT count(*) FROM approvals WHERE agent_id = ? AND class = ? AND decided_by = 0 AND status IN (?, ?) AND decided_at >= ?`,
|
|
agent, class, Done, Failed, ts(now.Add(-24*time.Hour))).Scan(&n)
|
|
return n < cap, err
|
|
}
|