// 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) } // FailureRecorder is told when an action of a class failed, so the class loses // the autonomy it had. type FailureRecorder interface { Failed(ctx context.Context, c Class) error } 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 failed FailureRecorder log *slog.Logger now func() time.Time } // NewModule returns the judgement module for orgID, with its hard rules and // guards. An action of a class that fails is reported to failed. func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tools Tools, rules []HardRule, guards []Guard, failed FailureRecorder) *Module { return &Module{orgID: orgID, tools: tools, rules: rules, guards: guards, store: store.New(db), failed: failed, 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 } return m.invoke(ctx, d, input, key) } // invoke runs the judged action. A failure, or an outcome nobody can confirm, // drops the action's class to propose and wait at once, whatever level it ran at. func (m *Module) invoke(ctx context.Context, d Decision, input jsontext.Value, key string) (string, error) { tool, ok := m.tools.Tool(d.Action.Connector) if !ok { return "", fmt.Errorf("%q isn't running", d.Action.Connector) } out, err := tool.Invoke(ctx, connectors.Invocation{Action: d.Action.Name, Input: input, IdempotencyKey: key}) // A shutdown cancels the call without the action having gone wrong. if err != nil && m.failed != nil && !errors.Is(err, context.Canceled) { if ferr := m.failed.Failed(ctx, d.Action.Class()); ferr != nil { return out, errors.Join(err, fmt.Errorf("tighten class: %w", ferr)) } } return out, err } // 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 } return m.invoke(ctx, d, input, 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 }