Files
archie/modules/judgement/judgement.go
T
sam 0238f247e5 feat(approvals): a held action is asked of a person, and the run waits for the answer (archie #1985, #1999)
An action judgement holds at propose and wait is no longer a dead end. The
new approvals module owns the request: it binds to the decision and the
action's digest, so an answer covers the action the person was shown and
nothing else, and it settles once. The answer wakes the run, which judges the
action again and runs it only as the approval allows: a refusal still refuses,
an altered input runs nothing, and a judgement that came back worse runs
nothing on that approval.

The composer carries the request as a message with the request id and its
deadline, and its answer is a message too, so the trail shows what was asked
and what was answered. A request nobody answers inside its deadline is settled
as expired and nothing runs.

How long a request waits is an organisation setting, edited in the dashboard
and stored in milliseconds, because a Postgres interval scans as text. A run
pins the deadline it started with, like its model.

An agent that proposes the same action twice is asked about it once, and the
notification says when the investigation proposed nothing at all.
2026-11-16 02:21:06 +11:00

313 lines
10 KiB
Go

// Package judgement decides whether a concrete action runs, and runs only the
// action it judged. Hard rules refuse first; every guard then sets a ceiling,
// and the action runs at the lowest one. Each decision is recorded with every
// verdict, so the run's trail and the action class's history can read it.
package judgement
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
"sync"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/judgement/internal/store"
)
// guardTimeout bounds one guard, so a slow guard holds an action no longer.
const guardTimeout = 10 * time.Second
var (
// ErrRefused means a hard rule refused the action.
ErrRefused = errors.New("refused by a hard rule")
// ErrHeld means the action's level needs someone's approval first.
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.
type Action struct {
Connector string `json:"connector"`
Name string `json:"name"`
Input jsontext.Value `json:"input"`
Digest string `json:"digest"`
Target connectors.Target `json:"target"`
Effect connectors.Effect `json:"effect"`
}
// Class is what an action's earned autonomy belongs to.
type Class struct {
Connector string `json:"connector"`
Action string `json:"action"`
TargetKind string `json:"target_kind"`
Environment string `json:"environment"`
}
// Class returns the action's class.
func (a Action) Class() Class {
return Class{Connector: a.Connector, Action: a.Name, TargetKind: a.Target.Kind, Environment: a.Target.Environment}
}
// Finding is one thing a guard noticed, with what it rests on.
type Finding struct {
Text string `json:"text"`
Evidence string `json:"evidence,omitzero"`
}
// Verdict is one guard's judgement of one action.
type Verdict struct {
Guard string `json:"guard"`
Ceiling Level `json:"ceiling"`
Findings []Finding `json:"findings,omitzero"`
BlindSpots []string `json:"blind_spots,omitzero"`
// Advisory verdicts are recorded and set no ceiling.
Advisory bool `json:"advisory,omitzero"`
// Failed says why the guard couldn't answer; its ceiling is then
// propose and wait.
Failed string `json:"failed,omitzero"`
}
// Guard judges one concrete action.
type Guard interface {
Name() string
// Advisory guards are recorded but set no ceiling.
Advisory() bool
// Judge returns the guard's verdict. An error, a timeout or a verdict
// with no ceiling holds the action at propose and wait.
Judge(ctx context.Context, a Action) (Verdict, error)
}
// HardRule refuses actions outright. Hard rules run before any guard.
type HardRule interface {
Name() string
// Refuses reports whether the rule forbids the action, and why.
Refuses(a Action) (reason string, refused bool)
}
// Decision is the judgement of one action.
type Decision struct {
ID uuid.UUID `json:"id"`
RunID uuid.UUID `json:"run_id"`
Key string `json:"key"`
Action Action `json:"action"`
Level Level `json:"level"`
Verdicts []Verdict `json:"verdicts"`
// RefusedBy names the hard rule that refused the action, if one did.
RefusedBy string `json:"refused_by,omitzero"`
Reason string `json:"reason,omitzero"`
At time.Time `json:"at"`
}
// Request asks for one action to be judged. Key identifies the attempt to run
// it: the same key is the same decision, so a replayed step never judges
// twice.
type Request struct {
RunID uuid.UUID
Key string
Connector string
Action string
Input jsontext.Value
}
// Tools finds the tool that resolves and runs an action.
type Tools interface {
Tool(name string) (connectors.Tool, bool)
}
type recorder interface {
Record(ctx context.Context, d store.Decision) (store.Decision, error)
ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]store.Decision, error)
}
// Module judges one organisation's actions.
type Module struct {
orgID string
tools Tools
rules []HardRule
guards []Guard
store recorder
log *slog.Logger
now func() time.Time
}
// NewModule returns the judgement module for orgID, with its hard rules and
// guards.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tools Tools, rules []HardRule, guards []Guard) *Module {
return &Module{orgID: orgID, tools: tools, rules: rules, guards: guards, store: store.New(db), log: log, now: time.Now}
}
// Assess judges one action and records the decision. Judging the same key
// again returns the recorded decision.
func (m *Module) Assess(ctx context.Context, req Request) (Decision, error) {
tool, ok := m.tools.Tool(req.Connector)
if !ok {
return Decision{}, fmt.Errorf("%q isn't running", req.Connector)
}
res, err := tool.Resolve(ctx, req.Action, req.Input)
if err != nil {
return Decision{}, fmt.Errorf("resolve %s %s: %w", req.Connector, req.Action, err)
}
a := Action{
Connector: req.Connector, Name: req.Action, Input: req.Input,
Digest: connectors.Digest(req.Action, req.Input), Target: res.Target, Effect: res.Effect,
}
d := m.decide(ctx, a)
d.ID, d.RunID, d.Key, d.At = uuid.New(), req.RunID, req.Key, m.now().UTC()
return m.record(ctx, d)
}
// decide runs the hard rules, then every guard in parallel, and folds their
// ceilings: the action runs at the lowest.
func (m *Module) decide(ctx context.Context, a Action) Decision {
for _, r := range m.rules {
if reason, refused := r.Refuses(a); refused {
return Decision{Action: a, Level: Never, RefusedBy: r.Name(), Reason: reason, Verdicts: []Verdict{}}
}
}
verdicts := make([]Verdict, len(m.guards))
var wg sync.WaitGroup
for i, g := range m.guards {
wg.Go(func() { verdicts[i] = judge(ctx, g, a) })
}
wg.Wait()
ceilings := []Level{}
for _, v := range verdicts {
if !v.Advisory {
ceilings = append(ceilings, v.Ceiling)
}
}
level := ProposeAndWait
if len(ceilings) > 0 {
level = lowest(ceilings...)
}
return Decision{Action: a, Level: level, Verdicts: verdicts}
}
// judge asks one guard, turning a failure, a timeout or a missing ceiling
// into propose and wait. A panic is a failure too.
func judge(ctx context.Context, g Guard, a Action) (v Verdict) {
ctx, cancel := context.WithTimeout(ctx, guardTimeout)
defer cancel()
failed := func(why string) Verdict {
return Verdict{Guard: g.Name(), Ceiling: ProposeAndWait, Advisory: g.Advisory(), Failed: why}
}
defer func() {
if r := recover(); r != nil {
v = failed(fmt.Sprintf("panicked: %v", r))
}
}()
got, err := g.Judge(ctx, a)
switch {
case err != nil:
return failed(err.Error())
case got.Ceiling < ActQuietly || got.Ceiling > Never:
return failed("returned no ceiling")
}
got.Guard, got.Advisory = g.Name(), g.Advisory()
return got
}
// Execute runs a decided action if its level lets it run and the input is
// exactly the one judged. key is the idempotency key the connector honours.
func (m *Module) Execute(ctx context.Context, d Decision, input jsontext.Value, key string) (string, error) {
switch {
case d.Level == Never:
return "", fmt.Errorf("%w: %s: %s", ErrRefused, d.RefusedBy, d.Reason)
case !d.Level.Runs():
return "", fmt.Errorf("%w at %s", ErrHeld, d.Level)
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})
}
// 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)
if err != nil {
return nil, err
}
out := make([]Decision, 0, len(rows))
for _, r := range rows {
var d Decision
if err := json.Unmarshal(r.Body, &d); err != nil {
return nil, fmt.Errorf("decision %s: %w", r.ID, err)
}
out = append(out, d)
}
return out, nil
}
func (m *Module) record(ctx context.Context, d Decision) (Decision, error) {
body, err := json.Marshal(d)
if err != nil {
return Decision{}, fmt.Errorf("encode decision: %w", err)
}
c := d.Action.Class()
row, err := m.store.Record(ctx, store.Decision{
ID: d.ID, OrgID: m.orgID, RunID: d.RunID, Key: d.Key,
Connector: c.Connector, Action: c.Action, TargetKind: c.TargetKind, Environment: c.Environment,
Level: d.Level.String(), Body: body,
})
if err != nil {
return Decision{}, err
}
if row.ID == d.ID {
return d, nil
}
var kept Decision
if err := json.Unmarshal(row.Body, &kept); err != nil {
return Decision{}, fmt.Errorf("decision %s: %w", row.ID, err)
}
return kept, nil
}