feat(judgement,approvals): link decisions and approval requests by action_type_id (#2130)

This commit is contained in:
sam committed 2026-11-24 06:23:19 +11:00
1 parent 1c10378a40
commit c5591d95da
14 files changed
+177 -108

No files matched your search

+3
View File
@@ -3067,6 +3067,8 @@ components:
properties: properties:
action: action:
$ref: "#/components/schemas/JudgementAction" $ref: "#/components/schemas/JudgementAction"
action_type_id:
type: string
at: at:
format: date-time format: date-time
type: string type: string
@@ -3106,6 +3108,7 @@ components:
- id - id
- run_id - run_id
- key - key
- action_type_id
- action - action
- level - level
- verdicts - verdicts
@@ -1,32 +1,6 @@
-- +goose Up -- +goose Up
CREATE SCHEMA judgement; CREATE SCHEMA judgement;
-- A decision is the judgement of one concrete action, with every verdict in
-- its body. key identifies the attempt to run the action, so a replayed step
-- reads the existing decision instead of judging the action again. connector, action, target_kind and environment
-- identify the action type the decision counts towards.
CREATE TABLE judgement.decisions (
id uuid PRIMARY KEY,
org_id text NOT NULL,
run_id uuid NOT NULL,
key text NOT NULL,
connector text NOT NULL,
-- installation_id and installation_scope name the installation the action
-- resolved to, so an audit can say which configuration acted and whose it was.
installation_id uuid NOT NULL,
installation_scope text NOT NULL CHECK (installation_scope IN ('instance', 'org', 'person')),
action text NOT NULL,
target_kind text NOT NULL,
environment text NOT NULL,
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
body json NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
dry boolean NOT NULL DEFAULT false,
UNIQUE (org_id, key)
);
CREATE INDEX decisions_by_run ON judgement.decisions (org_id, run_id, created_at);
CREATE INDEX decisions_by_class ON judgement.decisions (org_id, connector, action, target_kind, environment, created_at);
CREATE TABLE judgement.action_types ( CREATE TABLE judgement.action_types (
id uuid PRIMARY KEY, id uuid PRIMARY KEY,
org_id text NOT NULL, org_id text NOT NULL,
@@ -43,6 +17,35 @@ CREATE TABLE judgement.action_types (
UNIQUE (org_id, connector, action, target_kind, environment) UNIQUE (org_id, connector, action, target_kind, environment)
); );
-- A decision is the judgement of one concrete action, with every verdict in
-- its body. key identifies the attempt to run the action, so a replayed step
-- reads the existing decision instead of judging the action again.
-- action_type_id identifies the action type the decision counts towards;
-- connector, action, target_kind and environment are point-in-time snapshots
-- for the audit trail.
CREATE TABLE judgement.decisions (
id uuid PRIMARY KEY,
org_id text NOT NULL,
run_id uuid NOT NULL,
key text NOT NULL,
action_type_id uuid NOT NULL REFERENCES judgement.action_types (id),
connector text NOT NULL,
-- installation_id and installation_scope name the installation the action
-- resolved to, so an audit can say which configuration acted and whose it was.
installation_id uuid NOT NULL,
installation_scope text NOT NULL CHECK (installation_scope IN ('instance', 'org', 'person')),
action text NOT NULL,
target_kind text NOT NULL,
environment text NOT NULL,
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
body json NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
dry boolean NOT NULL DEFAULT false,
UNIQUE (org_id, key)
);
CREATE INDEX decisions_by_run ON judgement.decisions (org_id, run_id, created_at);
CREATE INDEX decisions_by_action_type ON judgement.decisions (org_id, action_type_id, created_at);
CREATE TABLE judgement.action_type_resets ( CREATE TABLE judgement.action_type_resets (
id uuid PRIMARY KEY, id uuid PRIMARY KEY,
org_id text NOT NULL, org_id text NOT NULL,
@@ -10,6 +10,9 @@ CREATE TABLE approvals.requests (
run_id uuid NOT NULL, run_id uuid NOT NULL,
key text NOT NULL, key text NOT NULL,
decision_id uuid NOT NULL, decision_id uuid NOT NULL,
-- action_type_id names the judgement.action_types row for both action and
-- autonomy requests, without a cross-module foreign key.
action_type_id uuid NOT NULL,
digest text NOT NULL, digest text NOT NULL,
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')), level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
summary text NOT NULL, summary text NOT NULL,
+30 -18
View File
@@ -71,15 +71,16 @@ type Request struct {
Kind string Kind string
RunID uuid.UUID RunID uuid.UUID
// Key identifies the run wait that receives the response. // Key identifies the run wait that receives the response.
Key string Key string
Decision judgement.Decision Decision judgement.Decision
DecisionID uuid.UUID DecisionID uuid.UUID
RequestedAt time.Time ActionTypeID uuid.UUID
Connector string RequestedAt time.Time
Action string Connector string
TargetKind string Action string
TargetID string TargetKind string
Level string TargetID string
Level string
// Irreversible is whether the action can't be undone. Approving it needs // Irreversible is whether the action can't be undone. Approving it needs
// a fresh passkey assertion from the dashboard. // a fresh passkey assertion from the dashboard.
Irreversible bool Irreversible bool
@@ -229,6 +230,9 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgeme
if len(path) == 0 { if len(path) == 0 {
return Request{}, ErrNoPath return Request{}, ErrNoPath
} }
if d.ActionTypeID == uuid.Nil {
return Request{}, errors.New("approval request needs an action type id")
}
changeRequest := d.ChangeRequest && m.changes != nil changeRequest := d.ChangeRequest && m.changes != nil
now := m.now().UTC() now := m.now().UTC()
var total time.Duration var total time.Duration
@@ -237,7 +241,7 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgeme
} }
row, err := m.store.Put(ctx, store.Request{ row, err := m.store.Put(ctx, store.Request{
ID: uuid.New(), OrgID: m.orgID, RunID: runID, Key: key, ID: uuid.New(), OrgID: m.orgID, RunID: runID, Key: key,
DecisionID: d.ID, Kind: KindAction, Digest: d.Action.Digest, Level: d.Level.String(), DecisionID: d.ID, ActionTypeID: d.ActionTypeID, Kind: KindAction, Digest: d.Action.Digest, Level: d.Level.String(),
Connector: d.Action.Connector, Action: d.Action.Name, Connector: d.Action.Connector, Action: d.Action.Name,
InstallationID: d.Action.Installation.ID, InstallationScope: d.Action.Installation.Scope, InstallationID: d.Action.Installation.ID, InstallationScope: d.Action.Installation.Scope,
TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID, Irreversible: irreversible(d.Action), TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID, Irreversible: irreversible(d.Action),
@@ -322,13 +326,21 @@ func (m *Module) learn(ctx context.Context, row store.Request, a Answer) error {
func (m *Module) askProposal(ctx context.Context, r *judgement.AutonomyProposal) error { func (m *Module) askProposal(ctx context.Context, r *judgement.AutonomyProposal) error {
actionType := r.ActionType actionType := r.ActionType
row, err := m.store.Put(ctx, store.Request{ var (
ID: uuid.New(), OrgID: m.orgID, Key: "autonomy:" + r.ID.String(), row store.Request
DecisionID: r.ID, Kind: KindAutonomy, Level: r.From.String(), err error
Connector: actionType.Connector, Action: actionType.Action, TargetKind: actionType.TargetKind, TargetID: actionType.Environment, )
InstallationScope: connectors.ScopeInstance, if r.ActionTypeID == uuid.Nil {
Summary: proposalSummary(r), State: StatePending, Deadline: r.Deadline, err = errors.New("autonomy approval request needs an action type id")
}) } else {
row, err = m.store.Put(ctx, store.Request{
ID: uuid.New(), OrgID: m.orgID, Key: "autonomy:" + r.ID.String(),
DecisionID: r.ID, ActionTypeID: r.ActionTypeID, Kind: KindAutonomy, Level: r.From.String(),
Connector: actionType.Connector, Action: actionType.Action, TargetKind: actionType.TargetKind, TargetID: actionType.Environment,
InstallationScope: connectors.ScopeInstance,
Summary: proposalSummary(r), State: StatePending, Deadline: r.Deadline,
})
}
if err == nil { if err == nil {
err = m.tell.Ask(ctx, deliveries.ApprovalRequest{ err = m.tell.Ask(ctx, deliveries.ApprovalRequest{
RequestID: row.ID, Key: row.Key + ":ask", RequestID: row.ID, Key: row.Key + ":ask",
@@ -645,7 +657,7 @@ func inputLine(input jsontext.Value) string {
func requestOf(row store.Request, d judgement.Decision) Request { func requestOf(row store.Request, d judgement.Decision) Request {
r := Request{ r := Request{
ID: row.ID, Kind: row.Kind, RunID: row.RunID, Key: row.Key, Decision: d, DecisionID: row.DecisionID, RequestedAt: row.CreatedAt, ID: row.ID, Kind: row.Kind, RunID: row.RunID, Key: row.Key, Decision: d, DecisionID: row.DecisionID, ActionTypeID: row.ActionTypeID, RequestedAt: row.CreatedAt,
Connector: row.Connector, Action: row.Action, TargetKind: row.TargetKind, TargetID: row.TargetID, Connector: row.Connector, Action: row.Action, TargetKind: row.TargetKind, TargetID: row.TargetID,
Level: row.Level, Irreversible: row.Irreversible, Summary: row.Summary, State: row.State, Deadline: row.Deadline, Level: row.Level, Irreversible: row.Irreversible, Summary: row.Summary, State: row.State, Deadline: row.Deadline,
Step: row.Step, ChangeRequest: row.ChangeRequest, Step: row.Step, ChangeRequest: row.ChangeRequest,
+10 -7
View File
@@ -19,10 +19,13 @@ type Request struct {
RunID uuid.UUID `db:"run_id"` RunID uuid.UUID `db:"run_id"`
Key string `db:"key"` Key string `db:"key"`
// DecisionID identifies the judgement decision or the autonomy proposal. // DecisionID identifies the judgement decision or the autonomy proposal.
DecisionID uuid.UUID `db:"decision_id"` DecisionID uuid.UUID `db:"decision_id"`
Kind string `db:"kind"` ActionTypeID uuid.UUID `db:"action_type_id"`
Digest string `db:"digest"` Kind string `db:"kind"`
Digest string `db:"digest"`
// Copy the action details so the request can be read without loading the decision. // Copy the action details so the request can be read without loading the decision.
// Connector holds the connector's immutable package identifier, never
// renamed and never given to a different package.
Connector string `db:"connector"` Connector string `db:"connector"`
// InstallationID and InstallationScope name the installation the action // InstallationID and InstallationScope name the installation the action
// resolved to. An autonomy proposal has none and records the nil ID at the // resolved to. An autonomy proposal has none and records the nil ID at the
@@ -62,7 +65,7 @@ type Store struct {
// New returns a store on db. // New returns a store on db.
func New(db *sqlx.DB) *Store { return &Store{db: db} } func New(db *sqlx.DB) *Store { return &Store{db: db} }
const requestColumns = `id, org_id, run_id, key, decision_id, kind, digest, connector, installation_id, installation_scope, action, target_kind, const requestColumns = `id, org_id, run_id, key, decision_id, action_type_id, kind, digest, connector, installation_id, installation_scope, action, target_kind,
target_id, level, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_by_id, answered_via, target_id, level, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_by_id, answered_via,
step, step_deadline, change_request, counted, discarded_because` step, step_deadline, change_request, counted, discarded_because`
@@ -71,12 +74,12 @@ const requestColumns = `id, org_id, run_id, key, decision_id, kind, digest, conn
func (s *Store) Put(ctx context.Context, r Request) (Request, error) { func (s *Store) Put(ctx context.Context, r Request) (Request, error) {
var out Request var out Request
err := s.db.GetContext(ctx, &out, ` err := s.db.GetContext(ctx, &out, `
INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, kind, digest, connector, installation_id, INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, action_type_id, kind, digest, connector, installation_id,
installation_scope, action, target_kind, target_id, level, irreversible, summary, state, deadline, step_deadline, change_request) installation_scope, action, target_kind, target_id, level, irreversible, summary, state, deadline, step_deadline, change_request)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)
ON CONFLICT (org_id, run_id, key) DO NOTHING ON CONFLICT (org_id, run_id, key) DO NOTHING
RETURNING `+requestColumns, RETURNING `+requestColumns,
r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.Kind, r.Digest, r.Connector, r.InstallationID, r.InstallationScope, r.Action, r.TargetKind, r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.ActionTypeID, r.Kind, r.Digest, r.Connector, r.InstallationID, r.InstallationScope, r.Action, r.TargetKind,
r.TargetID, r.Level, r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.ChangeRequest) r.TargetID, r.Level, r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.ChangeRequest)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
return s.Get(ctx, r.OrgID, r.RunID, r.Key) return s.Get(ctx, r.OrgID, r.RunID, r.Key)
+11 -7
View File
@@ -62,19 +62,23 @@ func NewActionTypes(db *sqlx.DB, log *slog.Logger, orgID string) *ActionTypes {
return &ActionTypes{orgID: orgID, store: store.New(db), log: log, now: time.Now} return &ActionTypes{orgID: orgID, store: store.New(db), log: log, now: time.Now}
} }
// Level returns the level of action type c, creating it at its default level // Level returns the level and id of actionType, creating it at its default
// on its first action. readOnly is the action's own declaration and is stored // level on its first action. readOnly is the action's own declaration and is
// with the action type, so a reset knows its default level. // stored with the action type, so a reset knows its default level.
func (c *ActionTypes) Level(ctx context.Context, actionType ActionType, readOnly bool) (Level, error) { func (c *ActionTypes) Level(ctx context.Context, actionType ActionType, readOnly bool) (Level, uuid.UUID, error) {
row, err := c.store.EnsureActionType(ctx, store.ActionType{ row, err := c.store.EnsureActionType(ctx, store.ActionType{
ID: uuid.New(), OrgID: c.orgID, Connector: actionType.Connector, Action: actionType.Action, ID: uuid.New(), OrgID: c.orgID, Connector: actionType.Connector, Action: actionType.Action,
TargetKind: actionType.TargetKind, Environment: actionType.Environment, TargetKind: actionType.TargetKind, Environment: actionType.Environment,
ReadOnly: readOnly, Level: DefaultLevel(readOnly).String(), ReadOnly: readOnly, Level: DefaultLevel(readOnly).String(),
}) })
if err != nil { if err != nil {
return 0, err return 0, uuid.Nil, err
} }
return parseLevel(row.Level) level, err := parseLevel(row.Level)
if err != nil {
return 0, uuid.Nil, err
}
return level, row.ID, nil
} }
func parseLevel(s string) (Level, error) { func parseLevel(s string) (Level, error) {
@@ -206,7 +210,7 @@ func (c *ActionTypes) Detail(ctx context.Context, id uuid.UUID, outcomes Outcome
if err != nil { if err != nil {
return ActionTypeDetail{}, err return ActionTypeDetail{}, err
} }
decisions, err := c.store.ActionTypeDecisions(ctx, row, historyLimit) decisions, err := c.store.ActionTypeDecisions(ctx, c.orgID, id, historyLimit)
if err != nil { if err != nil {
return ActionTypeDetail{}, err return ActionTypeDetail{}, err
} }
+7 -6
View File
@@ -80,11 +80,12 @@ func freezeCeiling(frozen, readOnly bool) Level {
// AutonomyProposal is Archie's proposal to loosen an action type by one level, with the // AutonomyProposal is Archie's proposal to loosen an action type by one level, with the
// approvals that earned it. // approvals that earned it.
type AutonomyProposal struct { type AutonomyProposal struct {
ID uuid.UUID ID uuid.UUID
ActionType ActionType ActionTypeID uuid.UUID
From, To Level ActionType ActionType
Evidence []ProposalEvidence From, To Level
Deadline time.Time Evidence []ProposalEvidence
Deadline time.Time
} }
// ProposalEvidence is one approval counted toward an autonomy proposal. // ProposalEvidence is one approval counted toward an autonomy proposal.
@@ -297,7 +298,7 @@ func (c *ActionTypes) propose(ctx context.Context, t *store.ActionTypeTx, from,
return nil, fmt.Errorf("encode evidence: %w", err) return nil, fmt.Errorf("encode evidence: %w", err)
} }
r := &AutonomyProposal{ r := &AutonomyProposal{
ID: uuid.New(), From: from, To: to, Evidence: shown, Deadline: deadline.UTC(), ID: uuid.New(), ActionTypeID: t.ActionType.ID, From: from, To: to, Evidence: shown, Deadline: deadline.UTC(),
ActionType: ActionType{ ActionType: ActionType{
Connector: t.ActionType.Connector, Action: t.ActionType.Action, Connector: t.ActionType.Connector, Action: t.ActionType.Action,
TargetKind: t.ActionType.TargetKind, Environment: t.ActionType.Environment, TargetKind: t.ActionType.TargetKind, Environment: t.ActionType.Environment,
+6 -4
View File
@@ -5,6 +5,8 @@ import (
"errors" "errors"
"fmt" "fmt"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/connectors"
) )
@@ -34,9 +36,9 @@ 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")
} }
// ActionTypeLevels reports the level of an action type. // ActionTypeLevels reports the level and id of an action type.
type ActionTypeLevels interface { type ActionTypeLevels interface {
Level(ctx context.Context, c ActionType, readOnly bool) (Level, error) Level(ctx context.Context, c ActionType, readOnly bool) (Level, uuid.UUID, error)
} }
// Precedent sets a ceiling from the action type's current level. An action type // Precedent sets a ceiling from the action type's current level. An action type
@@ -54,11 +56,11 @@ func (Precedent) Advisory() bool { return false }
// Judge returns the action type's level. // Judge returns the action type's level.
func (p Precedent) Judge(ctx context.Context, a Action) (Verdict, error) { func (p Precedent) Judge(ctx context.Context, a Action) (Verdict, error) {
level, err := p.ActionTypes.Level(ctx, a.ActionType(), a.Effect.ReadOnly) level, id, err := p.ActionTypes.Level(ctx, a.ActionType(), a.Effect.ReadOnly)
if err != nil { if err != nil {
return Verdict{}, fmt.Errorf("read action type level: %w", err) return Verdict{}, fmt.Errorf("read action type level: %w", err)
} }
return Verdict{Ceiling: level, Findings: []Finding{{Text: "this action type is at " + level.String()}}}, nil return Verdict{Ceiling: level, actionTypeID: id, Findings: []Finding{{Text: "this action type is at " + level.String()}}}, nil
} }
// Freezes says whether the organisation has frozen its actions. // Freezes says whether the organisation has frozen its actions.
+2 -2
View File
@@ -88,8 +88,8 @@ func TestGuardsReturnTheDemoVerdicts(t *testing.T) {
{"reversibility: reading", Reversibility{}, read, ActQuietly}, {"reversibility: reading", Reversibility{}, read, ActQuietly},
{"reversibility: undone automatically", Reversibility{}, func() Action { a := runner; a.Effect.Reversibility = connectors.UndoneAutomatically; return a }(), ActQuietly}, {"reversibility: undone automatically", Reversibility{}, func() Action { a := runner; a.Effect.Reversibility = connectors.UndoneAutomatically; return a }(), ActQuietly},
{"precedent: earned action type", Precedent{ActionTypes: actionTypeLevel{ActAndTell}}, runner, ActAndTell}, {"precedent: earned action type", Precedent{ActionTypes: actionTypeLevel{level: ActAndTell}}, runner, ActAndTell},
{"precedent: new action type", Precedent{ActionTypes: actionTypeLevel{ProposeAndWait}}, container, ProposeAndWait}, {"precedent: new action type", Precedent{ActionTypes: actionTypeLevel{level: ProposeAndWait}}, container, ProposeAndWait},
{"provenance: verified alert", Provenance{Events: fakeEvents{verified: true, untrusted: []string{prose}}}, runner, ActQuietly}, {"provenance: verified alert", Provenance{Events: fakeEvents{verified: true, untrusted: []string{prose}}}, runner, ActQuietly},
{"provenance: no verified source", Provenance{Events: fakeEvents{}}, runner, ProposeAndWait}, {"provenance: no verified source", Provenance{Events: fakeEvents{}}, runner, ProposeAndWait},
@@ -15,8 +15,10 @@ var ErrNoActionType = errors.New("no such action type")
// ActionType is one action type and the level it stands at. // ActionType is one action type and the level it stands at.
type ActionType struct { type ActionType struct {
ID uuid.UUID `db:"id"` ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"` OrgID string `db:"org_id"`
// Connector holds the connector's immutable package identifier, never
// renamed and never given to a different package.
Connector string `db:"connector"` Connector string `db:"connector"`
Action string `db:"action"` Action string `db:"action"`
TargetKind string `db:"target_kind"` TargetKind string `db:"target_kind"`
@@ -76,8 +78,7 @@ func (s *Store) ActionTypes(ctx context.Context, orgID string) ([]ActionTypeSumm
count(d.id) AS decisions, max(d.created_at) AS last_at, count(d.id) AS decisions, max(d.created_at) AS last_at,
(SELECT count(*) FROM judgement.action_type_approvals a WHERE a.action_type_id = c.id AND a.counted) AS streak (SELECT count(*) FROM judgement.action_type_approvals a WHERE a.action_type_id = c.id AND a.counted) AS streak
FROM judgement.action_types c FROM judgement.action_types c
LEFT JOIN judgement.decisions d ON d.org_id = c.org_id AND d.connector = c.connector LEFT JOIN judgement.decisions d ON d.org_id = c.org_id AND d.action_type_id = c.id AND NOT d.dry
AND d.action = c.action AND d.target_kind = c.target_kind AND d.environment = c.environment AND NOT d.dry
WHERE c.org_id = $1 WHERE c.org_id = $1
GROUP BY c.id GROUP BY c.id
ORDER BY coalesce(max(d.created_at), c.created_at) DESC, c.id`, orgID) ORDER BY coalesce(max(d.created_at), c.created_at) DESC, c.id`, orgID)
@@ -101,14 +102,14 @@ func (s *Store) ActionTypeByID(ctx context.Context, orgID string, id uuid.UUID)
} }
// ActionTypeDecisions returns an action type's newest decisions, newest first. // ActionTypeDecisions returns an action type's newest decisions, newest first.
func (s *Store) ActionTypeDecisions(ctx context.Context, c ActionType, limit int) ([]Decision, error) { func (s *Store) ActionTypeDecisions(ctx context.Context, orgID string, actionTypeID uuid.UUID, limit int) ([]Decision, error) {
var out []Decision var out []Decision
err := s.db.SelectContext(ctx, &out, ` err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body, created_at SELECT `+decisionColumns+`, created_at
FROM judgement.decisions FROM judgement.decisions
WHERE org_id = $1 AND connector = $2 AND action = $3 AND target_kind = $4 AND environment = $5 AND NOT dry WHERE org_id = $1 AND action_type_id = $2 AND NOT dry
ORDER BY created_at DESC, id LIMIT $6`, ORDER BY created_at DESC, id LIMIT $3`,
c.OrgID, c.Connector, c.Action, c.TargetKind, c.Environment, limit) orgID, actionTypeID, limit)
if err != nil { if err != nil {
return nil, fmt.Errorf("list action type decisions: %w", err) return nil, fmt.Errorf("list action type decisions: %w", err)
} }
+1 -2
View File
@@ -41,8 +41,7 @@ func (s *Store) ActionTypeOfDecision(ctx context.Context, orgID string, decision
SELECT c.id, c.org_id, c.connector, c.action, c.target_kind, c.environment, c.read_only, c.level, 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, c.tightened_at, c.tightened_because c.created_at, c.reset_at, c.tightened_at, c.tightened_because
FROM judgement.decisions d FROM judgement.decisions d
JOIN judgement.action_types c ON c.org_id = d.org_id AND c.connector = d.connector AND c.action = d.action JOIN judgement.action_types c ON c.id = d.action_type_id
AND c.target_kind = d.target_kind AND c.environment = d.environment
WHERE d.org_id = $1 AND d.id = $2`, orgID, decisionID) WHERE d.org_id = $1 AND d.id = $2`, orgID, decisionID)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
return ActionType{}, ErrNoActionType return ActionType{}, ErrNoActionType
+20 -15
View File
@@ -15,14 +15,17 @@ import (
// Decision is one recorded decision. Body is the whole decision as JSON. // Decision is one recorded decision. Body is the whole decision as JSON.
type Decision struct { type Decision struct {
ID uuid.UUID `db:"id"` ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"` OrgID string `db:"org_id"`
RunID uuid.UUID `db:"run_id"` RunID uuid.UUID `db:"run_id"`
Key string `db:"key"` Key string `db:"key"`
Connector string `db:"connector"` ActionTypeID uuid.UUID `db:"action_type_id"`
Action string `db:"action"` // Connector holds the connector's immutable package identifier, never
TargetKind string `db:"target_kind"` // renamed and never given to a different package.
Environment string `db:"environment"` Connector string `db:"connector"`
Action string `db:"action"`
TargetKind string `db:"target_kind"`
Environment string `db:"environment"`
// InstallationID and InstallationScope name the installation the action // InstallationID and InstallationScope name the installation the action
// resolved to. // resolved to.
InstallationID uuid.UUID `db:"installation_id"` InstallationID uuid.UUID `db:"installation_id"`
@@ -34,6 +37,8 @@ type Decision struct {
CreatedAt time.Time `db:"created_at"` CreatedAt time.Time `db:"created_at"`
} }
const decisionColumns = `id, org_id, run_id, key, action_type_id, connector, action, target_kind, environment, level, body`
// Store is the judgement module's Postgres store. // Store is the judgement module's Postgres store.
type Store struct { type Store struct {
db *sqlx.DB db *sqlx.DB
@@ -48,14 +53,14 @@ func (s *Store) Record(ctx context.Context, d Decision) (Decision, error) {
var kept Decision var kept Decision
err := s.db.GetContext(ctx, &kept, ` err := s.db.GetContext(ctx, &kept, `
INSERT INTO judgement.decisions INSERT INTO judgement.decisions
(id, org_id, run_id, key, connector, installation_id, installation_scope, action, target_kind, environment, level, dry, body) (id, org_id, run_id, key, action_type_id, connector, installation_id, installation_scope, action, target_kind, environment, level, dry, body)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
ON CONFLICT (org_id, key) DO NOTHING ON CONFLICT (org_id, key) DO NOTHING
RETURNING id, org_id, run_id, key, connector, action, target_kind, environment, level, body`, RETURNING `+decisionColumns,
d.ID, d.OrgID, d.RunID, d.Key, d.Connector, d.InstallationID, d.InstallationScope, d.Action, d.TargetKind, d.Environment, d.Level, d.Dry, d.Body) d.ID, d.OrgID, d.RunID, d.Key, d.ActionTypeID, d.Connector, d.InstallationID, d.InstallationScope, d.Action, d.TargetKind, d.Environment, d.Level, d.Dry, d.Body)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
err = s.db.GetContext(ctx, &kept, ` err = s.db.GetContext(ctx, &kept, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body SELECT `+decisionColumns+`
FROM judgement.decisions WHERE org_id = $1 AND key = $2`, d.OrgID, d.Key) FROM judgement.decisions WHERE org_id = $1 AND key = $2`, d.OrgID, d.Key)
} }
if err != nil { if err != nil {
@@ -84,7 +89,7 @@ func (s *Store) AppendCall(ctx context.Context, orgID string, id uuid.UUID, call
func (s *Store) RecentBodies(ctx context.Context, orgID string, limit int) ([]Decision, error) { func (s *Store) RecentBodies(ctx context.Context, orgID string, limit int) ([]Decision, error) {
var out []Decision var out []Decision
if err := s.db.SelectContext(ctx, &out, ` if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body, created_at SELECT `+decisionColumns+`, created_at
FROM judgement.decisions WHERE org_id = $1 FROM judgement.decisions WHERE org_id = $1
ORDER BY created_at DESC LIMIT $2`, orgID, limit); err != nil { ORDER BY created_at DESC LIMIT $2`, orgID, limit); err != nil {
return nil, fmt.Errorf("list recent decisions: %w", err) return nil, fmt.Errorf("list recent decisions: %w", err)
@@ -96,7 +101,7 @@ func (s *Store) RecentBodies(ctx context.Context, orgID string, limit int) ([]De
func (s *Store) ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]Decision, error) { func (s *Store) ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]Decision, error) {
var out []Decision var out []Decision
if err := s.db.SelectContext(ctx, &out, ` if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body SELECT `+decisionColumns+`
FROM judgement.decisions WHERE org_id = $1 AND run_id = $2 ORDER BY created_at, id`, orgID, runID); err != nil { FROM judgement.decisions WHERE org_id = $1 AND run_id = $2 ORDER BY created_at, id`, orgID, runID); err != nil {
return nil, fmt.Errorf("list decisions: %w", err) return nil, fmt.Errorf("list decisions: %w", err)
} }
+33 -9
View File
@@ -125,6 +125,9 @@ type Verdict struct {
// Owner is the id of the person the impact guard found answering for the // Owner is the id of the person the impact guard found answering for the
// target, empty when it found none. // target, empty when it found none.
Owner string `json:"owner,omitzero"` Owner string `json:"owner,omitzero"`
// actionTypeID carries the row id ensured by the precedent guard so record
// does not need to ensure the action type a second time.
actionTypeID uuid.UUID
} }
// Guard judges one concrete action. // Guard judges one concrete action.
@@ -145,12 +148,13 @@ type HardRule interface {
// Decision is the judgement of one action. // Decision is the judgement of one action.
type Decision struct { type Decision struct {
ID uuid.UUID `json:"id"` ID uuid.UUID `json:"id"`
RunID uuid.UUID `json:"run_id"` RunID uuid.UUID `json:"run_id"`
Key string `json:"key"` Key string `json:"key"`
Action Action `json:"action"` ActionTypeID uuid.UUID `json:"action_type_id"`
Level Level `json:"level"` Action Action `json:"action"`
Verdicts []Verdict `json:"verdicts"` Level Level `json:"level"`
Verdicts []Verdict `json:"verdicts"`
// RefusedBy names the hard rule that refused the action, if one did. // RefusedBy names the hard rule that refused the action, if one did.
RefusedBy string `json:"refused_by,omitzero"` RefusedBy string `json:"refused_by,omitzero"`
// Workflow is the workflow the decision was made for. Execution checks it // Workflow is the workflow the decision was made for. Execution checks it
@@ -222,6 +226,7 @@ type FailureRecorder interface {
} }
type recorder interface { type recorder interface {
EnsureActionType(ctx context.Context, c store.ActionType) (store.ActionType, error)
Record(ctx context.Context, d store.Decision) (store.Decision, error) Record(ctx context.Context, d store.Decision) (store.Decision, error)
ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]store.Decision, error) ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]store.Decision, error)
AppendCall(ctx context.Context, orgID string, id uuid.UUID, call string) error AppendCall(ctx context.Context, orgID string, id uuid.UUID, call string) error
@@ -332,7 +337,11 @@ func (m *Module) decide(ctx context.Context, a Action) Decision {
} }
wg.Wait() wg.Wait()
ceilings := []Level{} ceilings := []Level{}
var actionTypeID uuid.UUID
for _, v := range verdicts { for _, v := range verdicts {
if v.actionTypeID != uuid.Nil {
actionTypeID = v.actionTypeID
}
if !v.Advisory { if !v.Advisory {
ceilings = append(ceilings, v.Ceiling) ceilings = append(ceilings, v.Ceiling)
} }
@@ -341,7 +350,7 @@ func (m *Module) decide(ctx context.Context, a Action) Decision {
if len(ceilings) > 0 { if len(ceilings) > 0 {
level = lowest(ceilings...) level = lowest(ceilings...)
} }
d := Decision{Action: a, Level: level, Verdicts: verdicts} d := Decision{ActionTypeID: actionTypeID, Action: a, Level: level, Verdicts: verdicts}
// A change request is a way to approve, so only a held action has one. // A change request is a way to approve, so only a held action has one.
if m.changeRules != nil && level > ActAndTell && level < Never { if m.changeRules != nil && level > ActAndTell && level < Never {
d.ChangeRequestRule, d.ChangeRequest = m.changeRules.Requires(ctx, a, level, verdicts) d.ChangeRequestRule, d.ChangeRequest = m.changeRules.Requires(ctx, a, level, verdicts)
@@ -495,19 +504,33 @@ func (m *Module) ForRun(ctx context.Context, runID uuid.UUID) ([]Decision, error
if err := json.Unmarshal(r.Body, &d); err != nil { if err := json.Unmarshal(r.Body, &d); err != nil {
return nil, fmt.Errorf("decision %s: %w", r.ID, err) return nil, fmt.Errorf("decision %s: %w", r.ID, err)
} }
d.ActionTypeID = r.ActionTypeID
out = append(out, d) out = append(out, d)
} }
return out, nil return out, nil
} }
func (m *Module) record(ctx context.Context, d Decision) (Decision, error) { func (m *Module) record(ctx context.Context, d Decision) (Decision, error) {
c := d.Action.ActionType()
// Ensure the action type row exists even when the precedent guard did not
// run (for instance a hard-rule refusal or a test module without precedent).
if d.ActionTypeID == uuid.Nil {
actionType, err := m.store.EnsureActionType(ctx, store.ActionType{
ID: uuid.New(), OrgID: m.orgID, Connector: c.Connector, Action: c.Action,
TargetKind: c.TargetKind, Environment: c.Environment,
ReadOnly: d.Action.Effect.ReadOnly, Level: DefaultLevel(d.Action.Effect.ReadOnly).String(),
})
if err != nil {
return Decision{}, err
}
d.ActionTypeID = actionType.ID
}
body, err := json.Marshal(d) body, err := json.Marshal(d)
if err != nil { if err != nil {
return Decision{}, fmt.Errorf("encode decision: %w", err) return Decision{}, fmt.Errorf("encode decision: %w", err)
} }
c := d.Action.ActionType()
row, err := m.store.Record(ctx, store.Decision{ row, err := m.store.Record(ctx, store.Decision{
ID: d.ID, OrgID: m.orgID, RunID: d.RunID, Key: d.Key, ID: d.ID, OrgID: m.orgID, RunID: d.RunID, Key: d.Key, ActionTypeID: d.ActionTypeID,
Connector: c.Connector, Action: c.Action, TargetKind: c.TargetKind, Environment: c.Environment, Connector: c.Connector, Action: c.Action, TargetKind: c.TargetKind, Environment: c.Environment,
InstallationID: d.Action.Installation.ID, InstallationScope: d.Action.Installation.Scope, InstallationID: d.Action.Installation.ID, InstallationScope: d.Action.Installation.Scope,
Level: d.Level.String(), Dry: d.Dry, Body: body, Level: d.Level.String(), Dry: d.Dry, Body: body,
@@ -522,5 +545,6 @@ func (m *Module) record(ctx context.Context, d Decision) (Decision, error) {
if err := json.Unmarshal(row.Body, &kept); err != nil { if err := json.Unmarshal(row.Body, &kept); err != nil {
return Decision{}, fmt.Errorf("decision %s: %w", row.ID, err) return Decision{}, fmt.Errorf("decision %s: %w", row.ID, err)
} }
kept.ActionTypeID = row.ActionTypeID
return kept, nil return kept, nil
} }
+12 -3
View File
@@ -284,9 +284,14 @@ func TestExecuteApprovedRunsOnlyWhatThePersonSaw(t *testing.T) {
} }
} }
type actionTypeLevel struct{ level Level } type actionTypeLevel struct {
level Level
id uuid.UUID
}
func (c actionTypeLevel) Level(context.Context, ActionType, bool) (Level, error) { return c.level, nil } func (c actionTypeLevel) Level(context.Context, ActionType, bool) (Level, uuid.UUID, error) {
return c.level, c.id, nil
}
// TestPrecedentCeilingIsTheClassLevel guards the earned-autonomy seam: the // TestPrecedentCeilingIsTheClassLevel guards the earned-autonomy seam: the
// precedent guard's ceiling is the level its action type stands at, not a // precedent guard's ceiling is the level its action type stands at, not a
@@ -303,15 +308,19 @@ func TestPrecedentCeilingIsTheClassLevel(t *testing.T) {
{name: "a read-only action type lowered to escalate", level: Escalate, read: true}, {name: "a read-only action type lowered to escalate", level: Escalate, read: true},
{name: "an action type that never runs", level: Never}, {name: "an action type that never runs", level: Never},
} }
wantID := uuid.New()
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
v, err := Precedent{ActionTypes: actionTypeLevel{tt.level}}.Judge(t.Context(), Action{Effect: connectors.Effect{ReadOnly: tt.read}}) v, err := Precedent{ActionTypes: actionTypeLevel{tt.level, wantID}}.Judge(t.Context(), Action{Effect: connectors.Effect{ReadOnly: tt.read}})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if v.Ceiling != tt.level { if v.Ceiling != tt.level {
t.Fatalf("ceiling = %s, want the action type level %s", v.Ceiling, tt.level) t.Fatalf("ceiling = %s, want the action type level %s", v.Ceiling, tt.level)
} }
if v.actionTypeID != wantID {
t.Fatalf("actionTypeID = %s, want %s", v.actionTypeID, wantID)
}
}) })
} }
} }