From 0ad4374a2a02e86657d7c4ff4a2691bdb9ba64c5 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 23 Nov 2026 23:43:45 +1100 Subject: [PATCH] refactor(judgement): rename action classes to action types and raises to autonomy proposals - tables judgement.action_types, action_type_resets, action_type_approvals and autonomy_proposals (migration 00063) - governance setting propose_autonomy_after, approval request kind autonomy, policy resource kind action_type - /api/action-types replaces /api/classes; the detail lists autonomy_proposals - an autonomy proposal stores the identity ID of the account that answered it --- api/openapi.yaml | 254 +++++++++--------- internal/app/archie/api.go | 32 +-- internal/app/archie/run.go | 16 +- .../contracts/connector/v1/connector.pb.go | 4 +- .../00063_judgement_action_types.sql | 90 +++++++ internal/platform/prompts/product_guide.md | 2 +- modules/approvals/approvals.go | 112 ++++---- modules/approvals/approvals_test.go | 6 +- modules/approvals/escalation.go | 2 +- modules/approvals/internal/store/store.go | 6 +- modules/chat/tools.go | 4 +- modules/chat/tools_test.go | 2 +- modules/connectors/connector.go | 4 +- modules/governance/access.go | 2 +- modules/governance/governance.go | 74 ++--- modules/governance/internal/store/store.go | 14 +- .../judgement/{classes.go => action_types.go} | 214 +++++++-------- modules/judgement/autonomy.go | 220 ++++++++------- modules/judgement/autonomy_test.go | 32 +-- modules/judgement/guards.go | 24 +- modules/judgement/guards_test.go | 6 +- .../judgement/internal/store/action_types.go | 166 ++++++++++++ modules/judgement/internal/store/autonomy.go | 194 ++++++------- modules/judgement/internal/store/classes.go | 166 ------------ modules/judgement/internal/store/store.go | 4 +- modules/judgement/judgement.go | 31 +-- modules/judgement/judgement_test.go | 22 +- proto/connector/v1/connector.proto | 4 +- ui/pages/pages.json | 2 +- ...onClassDetail.vue => ActionTypeDetail.vue} | 12 +- ui/src/controls/ControlsPage.vue | 30 +-- ui/src/lib/api.ts | 22 +- ui/src/router/routes.ts | 2 +- 33 files changed, 951 insertions(+), 824 deletions(-) create mode 100644 internal/platform/pg/migrations/00063_judgement_action_types.sql rename modules/judgement/{classes.go => action_types.go} (51%) create mode 100644 modules/judgement/internal/store/action_types.go delete mode 100644 modules/judgement/internal/store/classes.go rename ui/src/controls/{ActionClassDetail.vue => ActionTypeDetail.vue} (71%) diff --git a/api/openapi.yaml b/api/openapi.yaml index 6ca8a3136..e821ca022 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -2437,7 +2437,7 @@ components: - "null" frozen: type: boolean - raise_after: + propose_autonomy_after: format: int64 type: integer recurrence_threshold: @@ -2447,7 +2447,7 @@ components: $ref: "#/components/schemas/GovernanceTiming" required: - approval_deadline - - raise_after + - propose_autonomy_after - frozen - recurrence_threshold - attempts_per_run @@ -2581,11 +2581,17 @@ components: - target - effect type: object - JudgementClassDetail: + JudgementActionTypeDetail: additionalProperties: false properties: action: type: string + autonomy_proposals: + items: + $ref: "#/components/schemas/JudgementAutonomyProposalView" + type: + - array + - "null" connector: type: string count: @@ -2613,12 +2619,6 @@ components: - "null" level: type: string - raises: - items: - $ref: "#/components/schemas/JudgementRaiseView" - type: - - array - - "null" reset_at: format: date-time type: @@ -2642,7 +2642,7 @@ components: required: - history - resets - - raises + - autonomy_proposals - id - connector - action @@ -2653,7 +2653,7 @@ components: - decisions - count type: object - JudgementClassView: + JudgementActionTypeView: additionalProperties: false properties: action: @@ -2704,6 +2704,47 @@ components: - decisions - count type: object + JudgementAutonomyProposalView: + additionalProperties: false + properties: + answered_at: + format: date-time + type: + - string + - "null" + answered_by: + type: string + answered_by_id: + type: string + deadline: + format: date-time + type: string + evidence: + items: + $ref: "#/components/schemas/JudgementProposalEvidence" + type: + - array + - "null" + from: + type: string + id: + type: string + proposed_at: + format: date-time + type: string + state: + type: string + to: + type: string + required: + - id + - from + - to + - state + - deadline + - proposed_at + - evidence + type: object JudgementDecision: additionalProperties: false properties: @@ -2903,7 +2944,7 @@ components: - created_at - versions type: object - JudgementRaiseEvidence: + JudgementProposalEvidence: additionalProperties: false properties: at: @@ -2918,45 +2959,6 @@ components: - by - at type: object - JudgementRaiseView: - additionalProperties: false - properties: - answered_at: - format: date-time - type: - - string - - "null" - answered_by: - type: string - deadline: - format: date-time - type: string - evidence: - items: - $ref: "#/components/schemas/JudgementRaiseEvidence" - type: - - array - - "null" - from: - type: string - id: - type: string - proposed_at: - format: date-time - type: string - state: - type: string - to: - type: string - required: - - id - - from - - to - - state - - deadline - - proposed_at - - evidence - type: object JudgementResetView: additionalProperties: false properties: @@ -4649,6 +4651,81 @@ paths: summary: Create an account tags: - Accounts + /api/action-types: + get: + operationId: list-action-types + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/JudgementActionTypeView" + type: + - array + - "null" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: List action types with their earned levels + tags: + - Controls + /api/action-types/{id}: + get: + operationId: get-action-type + parameters: + - in: path + name: id + required: true + schema: + format: uuid + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/JudgementActionTypeDetail" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Get an action type with its history and outcomes + tags: + - Controls + /api/action-types/{id}/reset: + post: + operationId: reset-action-type + parameters: + - in: path + name: id + required: true + schema: + format: uuid + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/JudgementActionTypeView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Reset an action type to its default level + tags: + - Controls /api/admin/token: post: operationId: rotate-admin-token @@ -5328,81 +5405,6 @@ paths: summary: Stream what a turn records, from a cursor, until it ends tags: - Chat - /api/classes: - get: - operationId: list-classes - responses: - "200": - content: - application/json: - schema: - items: - $ref: "#/components/schemas/JudgementClassView" - type: - - array - - "null" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: List action classes with their earned levels - tags: - - Controls - /api/classes/{id}: - get: - operationId: get-class - parameters: - - in: path - name: id - required: true - schema: - format: uuid - type: string - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/JudgementClassDetail" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Get an action class with its history and outcomes - tags: - - Controls - /api/classes/{id}/reset: - post: - operationId: reset-class - parameters: - - in: path - name: id - required: true - schema: - format: uuid - type: string - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/JudgementClassView" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Reset an action class to its default level - tags: - - Controls /api/composer/messages: get: operationId: list-composer-messages diff --git a/internal/app/archie/api.go b/internal/app/archie/api.go index e0ad52a4f..7754473a1 100644 --- a/internal/app/archie/api.go +++ b/internal/app/archie/api.go @@ -24,20 +24,20 @@ import ( // apiModules are the modules that serve the HTTP API. type apiModules struct { - settings *governance.Module - conns *connectors.Module - system *system.Module - tell *deliveries.Module - allow *approvals.Module - classes *judgement.Classes - policies *judgement.Policies - hear *events.Module - judge *judgement.Module - engine *runs.Engine - chat *chat.Module - drafts *drafts.Module - notes *memory.Module - live *hub.Hub + settings *governance.Module + conns *connectors.Module + system *system.Module + tell *deliveries.Module + allow *approvals.Module + actionTypes *judgement.ActionTypes + policies *judgement.Policies + hear *events.Module + judge *judgement.Module + engine *runs.Engine + chat *chat.Module + drafts *drafts.Module + notes *memory.Module + live *hub.Hub } func (m apiModules) register(api huma.API) { @@ -49,7 +49,7 @@ func (m apiModules) register(api huma.API) { m.system.Register(api) m.tell.Register(api) m.allow.Register(api) - m.classes.Register(api, m.allow) + m.actionTypes.Register(api, m.allow) m.policies.Register(api) m.hear.Register(api) m.judge.Register(api) @@ -80,7 +80,7 @@ func emptyAPI(auth httpapi.Authenticator, authz httpapi.Authorizer) (*http.Serve api := httpapi.New(mux, buildinfo.Version, auth, authz) apiModules{ settings: settings, conns: &connectors.Module{}, system: &system.Module{}, - tell: &deliveries.Module{}, allow: &approvals.Module{}, classes: &judgement.Classes{}, + tell: &deliveries.Module{}, allow: &approvals.Module{}, actionTypes: &judgement.ActionTypes{}, policies: &judgement.Policies{}, hear: &events.Module{}, judge: &judgement.Module{}, engine: &runs.Engine{}, chat: &chat.Module{}, drafts: &drafts.Module{}, notes: &memory.Module{}, live: hub.New(), diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index a4ec1a91a..e64201df4 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -180,10 +180,10 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary talk := chat.NewModule(db, log.With("module", "chat"), orgID, live) // A workflow takes its context from the run handle, as a handler takes it // from the request. - classes := judgement.NewClasses(db, log.With("module", "judgement"), orgID) + actionTypes := judgement.NewActionTypes(db, log.With("module", "judgement"), orgID) // An approval request is carried by deliveries, and its answer wakes the run // that is waiting on it. - allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, answers{chat: talk, runs: engine}, classes, settings, settings) + allow := approvals.NewModule(db, log.With("module", "approvals"), orgID, tell, answers{chat: talk, runs: engine}, actionTypes, settings, settings) // Approving an action that can't be undone needs a fresh passkey assertion. allow.UseConfirmer(settings) policies := judgement.NewPolicies(db, log.With("module", "judgement"), orgID) @@ -195,7 +195,7 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary hear := events.NewModule(db, log.With("module", "events"), orgID, sealer, conns, engine, allow, settings, tell) hear.Routes(mux) engine.UseReferrers(hear) - judge := newJudgement(db, log, conns, classes, policies, settings, hear) + judge := newJudgement(db, log, conns, actionTypes, policies, settings, hear) // The record of deletions outlives this process and its database, so the // log exists before anything can be deleted: an instance that has run this // release and lost its log is a different case from one that never deleted. @@ -212,7 +212,7 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary }) sys.UseHealth(healthSources(checks, conns, engine, allow)) apiModules{ - settings: settings, conns: conns, system: sys, tell: tell, allow: allow, classes: classes, policies: policies, + settings: settings, conns: conns, system: sys, tell: tell, allow: allow, actionTypes: actionTypes, policies: policies, hear: hear, judge: judge, engine: engine, chat: talk, drafts: drafts.NewModule(db, log.With("module", "drafts"), orgID, hear, engine, policies), notes: remember, live: live, }.register(api) @@ -252,18 +252,18 @@ func (a answers) Signal(ctx context.Context, id uuid.UUID, key string, payload j } // newJudgement returns the judgement module with its hard rules, data guards -// and change-request rules. A failed action tightens its class. -func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, classes *judgement.Classes, policies *judgement.Policies, settings *governance.Module, heard judgement.Events) *judgement.Module { +// and change-request rules. A failed action tightens its action type. +func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, actionTypes *judgement.ActionTypes, policies *judgement.Policies, settings *governance.Module, heard judgement.Events) *judgement.Module { guards := []judgement.Guard{ judgement.Impact{Lookup: judgement.RecordedFacts{Source: conns, Accounts: settings}, Defaults: settings}, judgement.Reversibility{}, - judgement.Precedent{Classes: classes}, + judgement.Precedent{ActionTypes: actionTypes}, judgement.Provenance{Events: heard}, judgement.Timing{Calendar: settings}, judgement.Cost{Budgets: settings, Counts: judgement.NewSpend(db, orgID)}, judgement.Freeze{Freezes: settings}, } - judge := judgement.NewModule(db, log.With("module", "judgement"), orgID, conns, []judgement.HardRule{policies}, guards, classes) + judge := judgement.NewModule(db, log.With("module", "judgement"), orgID, conns, []judgement.HardRule{policies}, guards, actionTypes) judge.UseExtensions(conns) judge.UseChangeRules(policies) return judge diff --git a/internal/contracts/connector/v1/connector.pb.go b/internal/contracts/connector/v1/connector.pb.go index 35ad7e24b..773ecbd73 100644 --- a/internal/contracts/connector/v1/connector.pb.go +++ b/internal/contracts/connector/v1/connector.pb.go @@ -852,7 +852,7 @@ func (x *Effect) GetSecretAccess() bool { } // Target is what an action acts on. Connector, action, kind and environment -// together are the action class. +// together are the action type. type Target struct { state protoimpl.MessageState `protogen:"open.v1"` Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"` @@ -1274,7 +1274,7 @@ type InvokeResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Output []byte `protobuf:"bytes,1,opt,name=output,proto3" json:"output,omitempty"` // executed_digest is the connector's digest of what it ran. A mismatch is a - // finding and tightens the action class. + // finding and tightens the action type. ExecutedDigest string `protobuf:"bytes,2,opt,name=executed_digest,json=executedDigest,proto3" json:"executed_digest,omitempty"` // outcome_unknown says the connector can't confirm what its effect did. OutcomeUnknown bool `protobuf:"varint,3,opt,name=outcome_unknown,json=outcomeUnknown,proto3" json:"outcome_unknown,omitempty"` diff --git a/internal/platform/pg/migrations/00063_judgement_action_types.sql b/internal/platform/pg/migrations/00063_judgement_action_types.sql new file mode 100644 index 000000000..4f1ab0507 --- /dev/null +++ b/internal/platform/pg/migrations/00063_judgement_action_types.sql @@ -0,0 +1,90 @@ +-- +goose Up +-- An action class is now an action type, and a proposal to loosen one is an +-- autonomy proposal. The account that answers a proposal is stored by its +-- identity ID; answered_by keeps the display name it had at the time. +ALTER TABLE judgement.classes RENAME TO action_types; +ALTER TABLE judgement.action_types RENAME CONSTRAINT classes_pkey TO action_types_pkey; +ALTER TABLE judgement.action_types RENAME CONSTRAINT classes_level_check TO action_types_level_check; +ALTER TABLE judgement.action_types + RENAME CONSTRAINT classes_org_id_connector_action_target_kind_environment_key + TO action_types_natural_key; + +ALTER TABLE judgement.class_resets RENAME TO action_type_resets; +ALTER TABLE judgement.action_type_resets RENAME COLUMN class_id TO action_type_id; +ALTER TABLE judgement.action_type_resets RENAME CONSTRAINT class_resets_pkey TO action_type_resets_pkey; +ALTER TABLE judgement.action_type_resets + RENAME CONSTRAINT class_resets_class_id_fkey TO action_type_resets_action_type_id_fkey; +ALTER INDEX judgement.class_resets_by_class RENAME TO action_type_resets_by_action_type; + +ALTER TABLE judgement.class_approvals RENAME TO action_type_approvals; +ALTER TABLE judgement.action_type_approvals RENAME COLUMN class_id TO action_type_id; +ALTER TABLE judgement.action_type_approvals RENAME CONSTRAINT class_approvals_pkey TO action_type_approvals_pkey; +ALTER TABLE judgement.action_type_approvals + RENAME CONSTRAINT class_approvals_class_id_fkey TO action_type_approvals_action_type_id_fkey; +ALTER TABLE judgement.action_type_approvals + RENAME CONSTRAINT class_approvals_decision_id_key TO action_type_approvals_decision_id_key; +ALTER INDEX judgement.class_approvals_counted RENAME TO action_type_approvals_counted; + +ALTER TABLE judgement.class_raises RENAME TO autonomy_proposals; +ALTER TABLE judgement.autonomy_proposals RENAME COLUMN class_id TO action_type_id; +ALTER TABLE judgement.autonomy_proposals RENAME CONSTRAINT class_raises_pkey TO autonomy_proposals_pkey; +ALTER TABLE judgement.autonomy_proposals + RENAME CONSTRAINT class_raises_class_id_fkey TO autonomy_proposals_action_type_id_fkey; +ALTER TABLE judgement.autonomy_proposals RENAME CONSTRAINT class_raises_state_check TO autonomy_proposals_state_check; +ALTER INDEX judgement.class_raises_one_pending RENAME TO autonomy_proposals_one_pending; +ALTER INDEX judgement.class_raises_by_class RENAME TO autonomy_proposals_by_action_type; +ALTER TABLE judgement.autonomy_proposals ADD COLUMN answered_by_id text; + +ALTER TABLE approvals.requests DROP CONSTRAINT requests_kind_check; +UPDATE approvals.requests SET kind = 'autonomy' WHERE kind = 'raise'; +ALTER TABLE approvals.requests ADD CONSTRAINT requests_kind_check CHECK (kind IN ('action', 'autonomy')); + +ALTER TABLE governance.settings RENAME COLUMN raise_after TO propose_autonomy_after; +ALTER TABLE governance.settings + RENAME CONSTRAINT settings_raise_after_check TO settings_propose_autonomy_after_check; + +UPDATE governance.access_policies SET object_kind = 'action_type' WHERE object_kind = 'class'; + +-- +goose Down +UPDATE governance.access_policies SET object_kind = 'class' WHERE object_kind = 'action_type'; + +ALTER TABLE governance.settings + RENAME CONSTRAINT settings_propose_autonomy_after_check TO settings_raise_after_check; +ALTER TABLE governance.settings RENAME COLUMN propose_autonomy_after TO raise_after; + +ALTER TABLE approvals.requests DROP CONSTRAINT requests_kind_check; +UPDATE approvals.requests SET kind = 'raise' WHERE kind = 'autonomy'; +ALTER TABLE approvals.requests ADD CONSTRAINT requests_kind_check CHECK (kind IN ('action', 'raise')); + +ALTER TABLE judgement.autonomy_proposals DROP COLUMN answered_by_id; +ALTER INDEX judgement.autonomy_proposals_by_action_type RENAME TO class_raises_by_class; +ALTER INDEX judgement.autonomy_proposals_one_pending RENAME TO class_raises_one_pending; +ALTER TABLE judgement.autonomy_proposals RENAME CONSTRAINT autonomy_proposals_state_check TO class_raises_state_check; +ALTER TABLE judgement.autonomy_proposals + RENAME CONSTRAINT autonomy_proposals_action_type_id_fkey TO class_raises_class_id_fkey; +ALTER TABLE judgement.autonomy_proposals RENAME CONSTRAINT autonomy_proposals_pkey TO class_raises_pkey; +ALTER TABLE judgement.autonomy_proposals RENAME COLUMN action_type_id TO class_id; +ALTER TABLE judgement.autonomy_proposals RENAME TO class_raises; + +ALTER INDEX judgement.action_type_approvals_counted RENAME TO class_approvals_counted; +ALTER TABLE judgement.action_type_approvals + RENAME CONSTRAINT action_type_approvals_decision_id_key TO class_approvals_decision_id_key; +ALTER TABLE judgement.action_type_approvals + RENAME CONSTRAINT action_type_approvals_action_type_id_fkey TO class_approvals_class_id_fkey; +ALTER TABLE judgement.action_type_approvals RENAME CONSTRAINT action_type_approvals_pkey TO class_approvals_pkey; +ALTER TABLE judgement.action_type_approvals RENAME COLUMN action_type_id TO class_id; +ALTER TABLE judgement.action_type_approvals RENAME TO class_approvals; + +ALTER INDEX judgement.action_type_resets_by_action_type RENAME TO class_resets_by_class; +ALTER TABLE judgement.action_type_resets + RENAME CONSTRAINT action_type_resets_action_type_id_fkey TO class_resets_class_id_fkey; +ALTER TABLE judgement.action_type_resets RENAME CONSTRAINT action_type_resets_pkey TO class_resets_pkey; +ALTER TABLE judgement.action_type_resets RENAME COLUMN action_type_id TO class_id; +ALTER TABLE judgement.action_type_resets RENAME TO class_resets; + +ALTER TABLE judgement.action_types + RENAME CONSTRAINT action_types_natural_key + TO classes_org_id_connector_action_target_kind_environment_key; +ALTER TABLE judgement.action_types RENAME CONSTRAINT action_types_level_check TO classes_level_check; +ALTER TABLE judgement.action_types RENAME CONSTRAINT action_types_pkey TO classes_pkey; +ALTER TABLE judgement.action_types RENAME TO classes; diff --git a/internal/platform/prompts/product_guide.md b/internal/platform/prompts/product_guide.md index 62819987c..aaa11a44a 100644 --- a/internal/platform/prompts/product_guide.md +++ b/internal/platform/prompts/product_guide.md @@ -5,7 +5,7 @@ Dashboard pages: - Runs (/runs, /runs/ID): every workflow run, and each run's trail: what started it, every model and tool step, each action's judgement and the approval it was put to. - Unmatched (/unmatched): event groups no trigger matched; a draft workflow can be made from one, dry-run, and published. - Events (/events): the events sources delivered, with the run each started. -- Classes (/classes, /classes/ID): action classes and the autonomy each has earned; approvals count towards a raise a person must approve, and a denial or failure lowers it. +- Action types (/controls, Action types tab): the autonomy each action type has earned. Approvals in a row lead Archie to propose more autonomy, which a person must approve, and a denial or failure lowers it. - Account (/account): passkeys, tokens and the channel accounts (such as Telegram) linked to the signed-in account. Any member whose role allows approve can answer an approval, from the dashboard or from a linked channel account. - Controls (/controls): hard rules and change-request policy, and the judges that weigh actions. - Extensions (/extensions): connectors, secret engines, guards and MCP servers, each accepted before it runs. diff --git a/modules/approvals/approvals.go b/modules/approvals/approvals.go index e4d6a26d1..46c08aa5e 100644 --- a/modules/approvals/approvals.go +++ b/modules/approvals/approvals.go @@ -57,11 +57,11 @@ var ( ErrNotSignedIn = errors.New("only a signed-in person can answer an approval") ) -// The kinds of request. A raise asks whether an action class may act with one +// The kinds of request. An autonomy proposal asks whether an action type may act with one // level more autonomy; no run waits on it. const ( - KindAction = "action" - KindRaise = "raise" + KindAction = "action" + KindAutonomy = "autonomy" ) // Request tracks approval of an action or a proposed increase in autonomy. @@ -138,7 +138,7 @@ type View struct { // Step and StepDeadline describe the current escalation step. Step int `json:"step"` StepDeadline time.Time `json:"step_deadline,omitzero"` - // DecisionID identifies the judgement decision or, for a raise request, the proposed raise. + // DecisionID identifies the judgement decision or, for an autonomy request, the autonomy proposal. DecisionID uuid.UUID `json:"decision_id"` RequestedAt time.Time `json:"requested_at"` // AnsweredBy is the answering account's display name. @@ -172,19 +172,19 @@ type Delivery interface { Notify(ctx context.Context, n deliveries.Notification) error } -// Classes updates action-class autonomy. Denials reduce autonomy; approvals +// Action types updates action-type autonomy. Denials reduce autonomy; approvals // count towards an increase that a person must approve separately. -type Classes interface { - Approved(ctx context.Context, decisionID uuid.UUID, by string, need int, deadline time.Time) (*judgement.Raise, error) +type ActionTypes interface { + Approved(ctx context.Context, decisionID uuid.UUID, by string, need int, deadline time.Time) (*judgement.AutonomyProposal, error) Denied(ctx context.Context, decisionID uuid.UUID) error - AnswerRaise(ctx context.Context, id uuid.UUID, by string, approve bool) (bool, error) - CancelRaise(ctx context.Context, id uuid.UUID) error + AnswerProposal(ctx context.Context, id uuid.UUID, who judgement.Answerer, approve bool) (bool, error) + CancelProposal(ctx context.Context, id uuid.UUID) error } -// Policy provides the organisation's deadline and approval threshold for raises. +// Policy provides the organisation's deadline and approval threshold for autonomy proposals. type Policy interface { ApprovalDeadline(ctx context.Context) (time.Duration, error) - RaiseAfter(ctx context.Context) (int, error) + ProposeAutonomyAfter(ctx context.Context) (int, error) } // Accounts resolves who answered: the account a channel credential is linked @@ -197,24 +197,24 @@ type Accounts interface { // Module owns one organisation's approval requests. type Module struct { - orgID string - store *store.Store - tell Delivery - wake Signaller - classes Classes - policy Policy - accounts Accounts - authz governance.Authorizer - confirm Confirmer - changes ChangeRequests - log *slog.Logger - now func() time.Time + orgID string + store *store.Store + tell Delivery + wake Signaller + actionTypes ActionTypes + policy Policy + accounts Accounts + authz governance.Authorizer + confirm Confirmer + changes ChangeRequests + log *slog.Logger + now func() time.Time } // NewModule creates the approvals module for orgID. -func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake Signaller, classes Classes, policy Policy, accounts Accounts) *Module { +func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake Signaller, actionTypes ActionTypes, policy Policy, accounts Accounts) *Module { return &Module{ - orgID: orgID, store: store.New(db), tell: tell, wake: wake, classes: classes, policy: policy, accounts: accounts, + orgID: orgID, store: store.New(db), tell: tell, wake: wake, actionTypes: actionTypes, policy: policy, accounts: accounts, log: log, now: time.Now, } } @@ -282,8 +282,8 @@ func (m *Module) answerAs(ctx context.Context, id uuid.UUID, who Answerer, via s return Request{}, fmt.Errorf("%w: %s", ErrAnswered, row.State) } answer := Answer{RequestID: row.ID, Approved: approved, By: who.Name, ByID: who.ID, Via: via, At: now} - if row.Kind == KindRaise { - if err := m.answerRaise(ctx, row, answer); err != nil { + if row.Kind == KindAutonomy { + if err := m.answerProposal(ctx, row, answer); err != nil { return Request{}, err } return requestOf(row, judgement.Decision{}), nil @@ -294,7 +294,7 @@ func (m *Module) answerAs(ctx context.Context, id uuid.UUID, who Answerer, via s // Count denials immediately. Defer counting approvals until execution // is imminent so discarded approvals do not increase autonomy. if !answer.Approved { - if err := m.classes.Denied(ctx, row.DecisionID); err != nil { + if err := m.actionTypes.Denied(ctx, row.DecisionID); err != nil { return Request{}, err } } @@ -302,63 +302,63 @@ func (m *Module) answerAs(ctx context.Context, id uuid.UUID, who Answerer, via s } func (m *Module) learn(ctx context.Context, row store.Request, a Answer) error { - need, err := m.policy.RaiseAfter(ctx) + need, err := m.policy.ProposeAutonomyAfter(ctx) if err != nil { - return fmt.Errorf("read raise count: %w", err) + return fmt.Errorf("read autonomy proposal count: %w", err) } wait, err := m.policy.ApprovalDeadline(ctx) if err != nil { return fmt.Errorf("read approval deadline: %w", err) } - raise, err := m.classes.Approved(ctx, row.DecisionID, a.By, need, a.At.Add(wait)) - if err != nil || raise == nil { + proposal, err := m.actionTypes.Approved(ctx, row.DecisionID, a.By, need, a.At.Add(wait)) + if err != nil || proposal == nil { return err } - return m.askRaise(ctx, raise) + return m.askProposal(ctx, proposal) } -func (m *Module) askRaise(ctx context.Context, r *judgement.Raise) error { - class := r.Class +func (m *Module) askProposal(ctx context.Context, r *judgement.AutonomyProposal) error { + actionType := r.ActionType row, err := m.store.Put(ctx, store.Request{ - ID: uuid.New(), OrgID: m.orgID, Key: "raise:" + r.ID.String(), - DecisionID: r.ID, Kind: KindRaise, Level: r.From.String(), - Connector: class.Connector, Action: class.Action, TargetKind: class.TargetKind, TargetID: class.Environment, - Summary: raiseSummary(r), State: StatePending, Deadline: r.Deadline, + ID: uuid.New(), OrgID: m.orgID, Key: "autonomy:" + r.ID.String(), + DecisionID: r.ID, Kind: KindAutonomy, Level: r.From.String(), + Connector: actionType.Connector, Action: actionType.Action, TargetKind: actionType.TargetKind, TargetID: actionType.Environment, + Summary: proposalSummary(r), State: StatePending, Deadline: r.Deadline, }) if err == nil { err = m.tell.Ask(ctx, deliveries.ApprovalRequest{ RequestID: row.ID, Key: row.Key + ":ask", - Title: "Raise autonomy: " + class.Connector + " " + class.Action, + Title: "Autonomy proposal: " + actionType.Connector + " " + actionType.Action, Body: row.Summary, ExpiresAt: row.Deadline, }) } if err != nil { - // Cancel the raise so a later approval can trigger another proposal. - if cerr := m.classes.CancelRaise(ctx, r.ID); cerr != nil { + // Cancel the autonomy proposal so a later approval can trigger another proposal. + if cerr := m.actionTypes.CancelProposal(ctx, r.ID); cerr != nil { err = errors.Join(err, cerr) } - return fmt.Errorf("ask to raise a class: %w", err) + return fmt.Errorf("ask for more autonomy: %w", err) } return nil } -// answerRaise applies a person's answer to a raise. No run waits on it. -func (m *Module) answerRaise(ctx context.Context, row store.Request, a Answer) error { - raised, err := m.classes.AnswerRaise(ctx, row.DecisionID, a.By, a.Approved) +// answerProposal applies a person's answer to an autonomy proposal. No run waits on it. +func (m *Module) answerProposal(ctx context.Context, row store.Request, a Answer) error { + loosened, err := m.actionTypes.AnswerProposal(ctx, row.DecisionID, judgement.Answerer{ID: a.ByID, Name: a.By}, a.Approved) if err != nil { - return fmt.Errorf("answer raise: %w", err) + return fmt.Errorf("answer autonomy proposal: %w", err) } text := answerText(a) - if a.Approved && !raised { - text += " This approval did not increase the action class's autonomy level." + if a.Approved && !loosened { + text += " This approval did not increase the action type's autonomy level." } return m.tell.Told(ctx, deliveries.ApprovalRequest{ - RequestID: row.ID, Key: row.Key + ":ask", Title: "Raise answered", + RequestID: row.ID, Key: row.Key + ":ask", Title: "Autonomy proposal answered", }, text) } -func raiseSummary(r *judgement.Raise) string { - c := r.Class +func proposalSummary(r *judgement.AutonomyProposal) string { + c := r.ActionType var s strings.Builder fmt.Fprintf(&s, "%s: %s on %s in %s. Proposed autonomy increase: %s to %s.\nConsecutive approvals (%d):", c.Connector, c.Action, c.TargetKind, c.Environment, r.From, r.To, len(r.Evidence)) @@ -434,7 +434,7 @@ func (m *Module) channelAnswerer(ctx context.Context, who governance.Subject, ro } // mayAnswer applies the access policies to an answer, as to any other -// permission: approving needs the approve action on the request, and a raise +// permission: approving needs the approve action on the request, and an autonomy proposal // or an escalated action, which change what the organisation lets Archie do, // also need the policy-management action. func (m *Module) mayAnswer(ctx context.Context, p governance.Principal, row store.Request) error { @@ -442,7 +442,7 @@ func (m *Module) mayAnswer(ctx context.Context, p governance.Principal, row stor return ErrNotApprover } actions := []governance.Action{governance.ActionApprove} - if row.Kind == KindRaise || row.Level == judgement.Escalate.String() { + if row.Kind == KindAutonomy || row.Level == judgement.Escalate.String() { actions = append(actions, governance.ActionManagePolicies) } res := governance.Resource{Kind: governance.KindApproval, ID: row.ID.String(), Org: governance.DefaultOrgID, State: row.State} @@ -464,7 +464,7 @@ func refusal(err error) bool { errors.Is(err, ErrNeedsFreshAuthentication) || errors.Is(err, ErrNotSignedIn) } -// Expire records a timeout without reducing the action class's autonomy: +// Expire records a timeout without reducing the action type's autonomy: // receiving no response is not a denial. func (m *Module) Expire(ctx context.Context, id uuid.UUID) error { row, err := m.store.Answer(ctx, m.orgID, id, StateExpired, "deadline", "", "clock", m.now().UTC()) @@ -526,7 +526,7 @@ func (m *Module) ForRun(ctx context.Context, runID uuid.UUID) ([]Request, error) return out, nil } -// Outcomes returns approval outcomes by decision ID for the action class history. +// Outcomes returns approval outcomes by decision ID for the action type history. 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 { diff --git a/modules/approvals/approvals_test.go b/modules/approvals/approvals_test.go index 2cc6a57bd..700161ada 100644 --- a/modules/approvals/approvals_test.go +++ b/modules/approvals/approvals_test.go @@ -104,17 +104,17 @@ func TestChannelAnswerComesFromALinkedAccountWhoseRoleMayApprove(t *testing.T) { {name: "an admin may approve", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: action(propose), wantName: "admin"}, {name: "an owner may approve", accounts: newAccounts(), authz: shipped(), who: "tg-owner", row: action(propose), wantName: "owner"}, {name: "an admin may answer an escalated action", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: action(escalate), wantName: "admin"}, - {name: "an admin may answer a raise", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: store.Request{ID: uuid.New(), Kind: KindRaise}, wantName: "admin"}, + {name: "an admin may answer an autonomy proposal", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: store.Request{ID: uuid.New(), Kind: KindAutonomy}, wantName: "admin"}, {name: "a developer may not approve", accounts: newAccounts(), authz: shipped(), who: "tg-developer", row: action(propose), wantErr: ErrNotApprover}, {name: "a viewer may not approve", accounts: newAccounts(), authz: shipped(), who: "tg-viewer", row: action(propose), wantErr: ErrNotApprover}, {name: "a channel account no account has linked is refused", accounts: newAccounts(), authz: shipped(), who: "tg-stranger", row: action(propose), wantErr: ErrUnlinked}, - {name: "an unlinked channel account can't answer a raise", accounts: newAccounts(), authz: shipped(), who: "tg-stranger", row: store.Request{Kind: KindRaise}, wantErr: ErrUnlinked}, + {name: "an unlinked channel account can't answer an autonomy proposal", accounts: newAccounts(), authz: shipped(), who: "tg-stranger", row: store.Request{Kind: KindAutonomy}, wantErr: ErrUnlinked}, {name: "a suspended account is refused", accounts: suspended, authz: shipped(), who: "tg-admin", row: action(propose), wantErr: ErrNotApprover}, {name: "a bot is refused", accounts: bot, authz: shipped(), who: "tg-admin", row: action(propose), wantErr: ErrNotApprover}, {name: "nobody may approve before access policies are attached", accounts: newAccounts(), who: "tg-admin", row: action(propose), wantErr: ErrNotApprover}, {name: "a policy can grant approve to a role", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: action(propose), wantName: "developer"}, {name: "approve alone does not answer an escalated action", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: action(escalate), wantErr: ErrNotApprover}, - {name: "approve alone does not answer a raise", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: store.Request{ID: uuid.New(), Kind: KindRaise}, wantErr: ErrNotApprover}, + {name: "approve alone does not answer an autonomy proposal", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: store.Request{ID: uuid.New(), Kind: KindAutonomy}, wantErr: ErrNotApprover}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/modules/approvals/escalation.go b/modules/approvals/escalation.go index dc64e49f1..2a3e766e6 100644 --- a/modules/approvals/escalation.go +++ b/modules/approvals/escalation.go @@ -68,7 +68,7 @@ func (m *Module) Accept(ctx context.Context, id uuid.UUID) error { } // Discard records why an approval is no longer valid and notifies the approval -// channels. A discarded approval cannot count towards a raise. +// channels. A discarded approval cannot count towards an autonomy proposal. func (m *Module) Discard(ctx context.Context, id uuid.UUID, because string) error { row, discarded, err := m.store.Discard(ctx, m.orgID, id, because) if err != nil || !discarded { diff --git a/modules/approvals/internal/store/store.go b/modules/approvals/internal/store/store.go index 3ae79b2c3..04cdbc5f3 100644 --- a/modules/approvals/internal/store/store.go +++ b/modules/approvals/internal/store/store.go @@ -12,13 +12,13 @@ import ( "github.com/jmoiron/sqlx" ) -// Request is the stored record of an action or raise approval request. +// Request is the stored record of an action or autonomy proposal approval request. type Request struct { ID uuid.UUID `db:"id"` OrgID string `db:"org_id"` RunID uuid.UUID `db:"run_id"` Key string `db:"key"` - // DecisionID identifies the judgement decision or the proposed raise. + // DecisionID identifies the judgement decision or the autonomy proposal. DecisionID uuid.UUID `db:"decision_id"` Kind string `db:"kind"` Digest string `db:"digest"` @@ -44,7 +44,7 @@ type Request struct { // ChangeRequest is whether the request went through a change request // rather than the approvers' channels. ChangeRequest bool `db:"change_request"` - // Counted is whether the approval was counted toward raising its class. + // Counted is whether the approval was counted toward loosening its action type. Counted bool `db:"counted"` DiscardedBecause sql.NullString `db:"discarded_because"` } diff --git a/modules/chat/tools.go b/modules/chat/tools.go index f9b8f649c..5a61f5f52 100644 --- a/modules/chat/tools.go +++ b/modules/chat/tools.go @@ -456,7 +456,7 @@ func (m *Module) builtins(d Deps, t store.Turn) []dashboardTool { } return views, err })), - {tool: typedTool("dashboard_navigate", "Offer the operator a link to a dashboard page, such as /runs/ID or /classes.", + {tool: typedTool("dashboard_navigate", "Offer the operator a link to a dashboard page, such as /runs/ID or /controls.", `{"type":"object","properties":{"path":{"type":"string"},"label":{"type":"string"}},"required":["path"]}`, func(ctx context.Context, in Navigation) (any, error) { if !dashboardPath(in.Path) { @@ -496,7 +496,7 @@ func typedTool[In any](name, description, schema string, run func(context.Contex // dashboardPages are the dashboard's top-level pages. var dashboardPages = []string{ - "composer", "runs", "unmatched", "events", "classes", "people", "controls", + "composer", "runs", "unmatched", "events", "people", "controls", "extensions", "sources", "triggers", "credentials", "settings", } diff --git a/modules/chat/tools_test.go b/modules/chat/tools_test.go index 57cc8615b..b4246a6cf 100644 --- a/modules/chat/tools_test.go +++ b/modules/chat/tools_test.go @@ -8,7 +8,7 @@ func TestDashboardPathStaysInTheDashboard(t *testing.T) { cases := map[string]bool{ "/runs": true, "/runs/0b8f6c1e-4a7e-4f6d": true, - "/classes/github:merge_pr": true, + "/controls/github:merge_pr": true, "//evil.example/runs": false, "https://evil.example/runs": false, "javascript:alert(1)": false, diff --git a/modules/connectors/connector.go b/modules/connectors/connector.go index 0dfd4da32..3891229e8 100644 --- a/modules/connectors/connector.go +++ b/modules/connectors/connector.go @@ -21,7 +21,7 @@ import ( var ( // ErrDigestMismatch means the connector ran something other than the - // judged action. It is a finding and tightens the action class. + // judged action. It is a finding and tightens the action type. ErrDigestMismatch = errors.New("connector executed a different action than the one judged") // ErrOutcomeUnknown means the connector can't confirm what its effect did. ErrOutcomeUnknown = errors.New("connector can't confirm the outcome") @@ -76,7 +76,7 @@ type Effect struct { } // Target is what an action acts on. Connector, action, kind and environment -// together are the action class. +// together are the action type. type Target struct { Kind string ID string diff --git a/modules/governance/access.go b/modules/governance/access.go index 8c3c8341c..3b90282d4 100644 --- a/modules/governance/access.go +++ b/modules/governance/access.go @@ -100,7 +100,7 @@ const ( KindGroup ResourceKind = "group" KindRun ResourceKind = "run" KindApproval ResourceKind = "approval" - KindClass ResourceKind = "class" + KindActionType ResourceKind = "action_type" KindDraft ResourceKind = "draft" KindDelivery ResourceKind = "delivery" KindIncident ResourceKind = "incident" diff --git a/modules/governance/governance.go b/modules/governance/governance.go index 98021ebf2..b51de49ac 100644 --- a/modules/governance/governance.go +++ b/modules/governance/governance.go @@ -61,12 +61,13 @@ func agentModelRole(alias string) string { // when the organisation hasn't said. const DefaultApprovalDeadline = 24 * time.Hour -// DefaultRaiseAfter is how many approvals in a row earn a proposal to raise an -// action class when the organisation hasn't said. -const DefaultRaiseAfter = 3 +// DefaultProposeAutonomyAfter is how many approvals in a row earn a proposal to +// loosen an action type when the organisation hasn't said. +const DefaultProposeAutonomyAfter = 3 -// maxRaiseAfter bounds the count: past it a class could never earn a raise. -const maxRaiseAfter = 100 +// maxProposeAutonomyAfter bounds the count: past it an action type could never +// earn an autonomy proposal. +const maxProposeAutonomyAfter = 100 // DefaultRecurrenceThreshold is how many incidents with one cause on one target // it takes to propose a root-cause fix when the organisation hasn't said. @@ -109,9 +110,9 @@ type Settings struct { // ApprovalDeadline is how long an approval request waits for an answer // before the run gives up on it. ApprovalDeadline time.Duration - // RaiseAfter is how many approvals in a row, since an action class was last - // tightened, earn a proposal to raise it one level. - RaiseAfter int + // ProposeAutonomyAfter is how many approvals in a row, since an action type + // was last tightened, earn a proposal to loosen it by one level. + ProposeAutonomyAfter int // Frozen holds every action that changes something at propose and wait, // without changing any class's level. Frozen bool @@ -159,21 +160,21 @@ type stepRequest struct { // travels as a Go duration string ("24h"), the same form every other duration // in the config takes. type settingsRequest struct { - ApprovalDeadline string `json:"approval_deadline"` - RaiseAfter int `json:"raise_after"` - Frozen bool `json:"frozen"` - RecurrenceThreshold int `json:"recurrence_threshold"` - AttemptsPerRun int `json:"attempts_per_run"` - DefaultOwner string `json:"default_owner"` - Escalation []stepRequest `json:"escalation"` - Timing Timing `json:"timing"` - ActionsPerRun int `json:"actions_per_run"` - ActionsPerDay int `json:"actions_per_day"` + ApprovalDeadline string `json:"approval_deadline"` + ProposeAutonomyAfter int `json:"propose_autonomy_after"` + Frozen bool `json:"frozen"` + RecurrenceThreshold int `json:"recurrence_threshold"` + AttemptsPerRun int `json:"attempts_per_run"` + DefaultOwner string `json:"default_owner"` + Escalation []stepRequest `json:"escalation"` + Timing Timing `json:"timing"` + ActionsPerRun int `json:"actions_per_run"` + ActionsPerDay int `json:"actions_per_day"` } func (s Settings) request() settingsRequest { return settingsRequest{ - ApprovalDeadline: s.ApprovalDeadline.String(), RaiseAfter: s.RaiseAfter, Frozen: s.Frozen, + ApprovalDeadline: s.ApprovalDeadline.String(), ProposeAutonomyAfter: s.ProposeAutonomyAfter, Frozen: s.Frozen, RecurrenceThreshold: s.RecurrenceThreshold, AttemptsPerRun: s.AttemptsPerRun, DefaultOwner: s.DefaultOwner, Escalation: stepRequests(s.Escalation), Timing: s.Timing, ActionsPerRun: s.ActionsPerRun, ActionsPerDay: s.ActionsPerDay, @@ -326,7 +327,7 @@ func (m *Module) Settings(ctx context.Context) (Settings, error) { } if !ok { return Settings{ - ApprovalDeadline: DefaultApprovalDeadline, RaiseAfter: DefaultRaiseAfter, + ApprovalDeadline: DefaultApprovalDeadline, ProposeAutonomyAfter: DefaultProposeAutonomyAfter, RecurrenceThreshold: DefaultRecurrenceThreshold, AttemptsPerRun: DefaultAttemptsPerRun, Escalation: []Step{}, Timing: Timing{}.normalised(), ActionsPerRun: DefaultActionsPerRun, ActionsPerDay: DefaultActionsPerDay, @@ -346,24 +347,24 @@ func (m *Module) Settings(ctx context.Context) (Settings, error) { } return Settings{ Timing: timing.normalised(), ActionsPerRun: row.ActionsPerRun, ActionsPerDay: row.ActionsPerDay, - ApprovalDeadline: time.Duration(row.ApprovalDeadlineMS) * time.Millisecond, - RaiseAfter: row.RaiseAfter, - Frozen: row.Frozen, - RecurrenceThreshold: row.RecurrenceThreshold, - AttemptsPerRun: row.AttemptsPerRun, - DefaultOwner: row.DefaultOwner, - Escalation: escalation, + ApprovalDeadline: time.Duration(row.ApprovalDeadlineMS) * time.Millisecond, + ProposeAutonomyAfter: row.ProposeAutonomyAfter, + Frozen: row.Frozen, + RecurrenceThreshold: row.RecurrenceThreshold, + AttemptsPerRun: row.AttemptsPerRun, + DefaultOwner: row.DefaultOwner, + Escalation: escalation, }, nil } -// RaiseAfter is how many approvals in a row earn a proposal to raise an action -// class. -func (m *Module) RaiseAfter(ctx context.Context) (int, error) { +// ProposeAutonomyAfter is how many approvals in a row earn a proposal to loosen +// an action type. +func (m *Module) ProposeAutonomyAfter(ctx context.Context) (int, error) { set, err := m.Settings(ctx) if err != nil { return 0, err } - return set.RaiseAfter, nil + return set.ProposeAutonomyAfter, nil } // Frozen reports whether the organisation has frozen its actions. @@ -458,7 +459,7 @@ func (m *Module) putSettings(ctx context.Context, in *struct{ Body settingsReque return nil, huma.NewError(http.StatusBadRequest, err.Error()) } set := Settings{ - ApprovalDeadline: deadline, RaiseAfter: req.RaiseAfter, Frozen: req.Frozen, + ApprovalDeadline: deadline, ProposeAutonomyAfter: req.ProposeAutonomyAfter, Frozen: req.Frozen, RecurrenceThreshold: req.RecurrenceThreshold, AttemptsPerRun: req.AttemptsPerRun, DefaultOwner: req.DefaultOwner, Escalation: steps, Timing: req.Timing.normalised(), ActionsPerRun: req.ActionsPerRun, ActionsPerDay: req.ActionsPerDay, @@ -488,7 +489,7 @@ func (m *Module) putSettings(ctx context.Context, in *struct{ Body settingsReque } if err := m.store.PutSettings(ctx, store.Settings{ OrgID: m.orgID, ApprovalDeadlineMS: set.ApprovalDeadline.Milliseconds(), - RaiseAfter: set.RaiseAfter, Frozen: set.Frozen, RecurrenceThreshold: set.RecurrenceThreshold, + ProposeAutonomyAfter: set.ProposeAutonomyAfter, Frozen: set.Frozen, RecurrenceThreshold: set.RecurrenceThreshold, AttemptsPerRun: set.AttemptsPerRun, DefaultOwner: set.DefaultOwner, Escalation: string(escalation), Timing: string(timing), ActionsPerRun: set.ActionsPerRun, ActionsPerDay: set.ActionsPerDay, }); err != nil { @@ -499,7 +500,8 @@ func (m *Module) putSettings(ctx context.Context, in *struct{ Body settingsReque } // validate keeps a deadline inside the range an answer can be given in, the -// count of approvals a raise needs inside the range a class can earn, and the +// count of approvals an autonomy proposal needs inside the range an action +// type can earn, and the // recurrence threshold inside the range that means a pattern. func (s Settings) validate() error { if s.RecurrenceThreshold < minRecurrenceThreshold || s.RecurrenceThreshold > maxRecurrenceThreshold { @@ -508,8 +510,8 @@ func (s Settings) validate() error { if s.ApprovalDeadline < minApprovalDeadline || s.ApprovalDeadline > maxApprovalDeadline { return fmt.Errorf("approval deadline must be between %s and %s", minApprovalDeadline, maxApprovalDeadline) } - if s.RaiseAfter < 1 || s.RaiseAfter > maxRaiseAfter { - return fmt.Errorf("raise after must be between 1 and %d approvals", maxRaiseAfter) + if s.ProposeAutonomyAfter < 1 || s.ProposeAutonomyAfter > maxProposeAutonomyAfter { + return fmt.Errorf("propose autonomy after must be between 1 and %d approvals", maxProposeAutonomyAfter) } if s.AttemptsPerRun < minAttemptsPerRun || s.AttemptsPerRun > maxAttemptsPerRun { return fmt.Errorf("attempts per run must be between %d and %d", minAttemptsPerRun, maxAttemptsPerRun) diff --git a/modules/governance/internal/store/store.go b/modules/governance/internal/store/store.go index 8ac042920..f947589c8 100644 --- a/modules/governance/internal/store/store.go +++ b/modules/governance/internal/store/store.go @@ -223,9 +223,9 @@ type Settings struct { OrgID string `db:"org_id"` // ApprovalDeadlineMS is how long an approval request waits for an answer. ApprovalDeadlineMS int64 `db:"approval_deadline_ms"` - // RaiseAfter is how many approvals in a row earn a proposal to raise an - // action class. - RaiseAfter int `db:"raise_after"` + // ProposeAutonomyAfter is how many approvals in a row earn a proposal to loosen an + // action type. + ProposeAutonomyAfter int `db:"propose_autonomy_after"` // Frozen holds every action that changes something at propose and wait. Frozen bool `db:"frozen"` // RecurrenceThreshold is how many incidents with one cause on one target @@ -251,7 +251,7 @@ type Settings struct { func (s *Store) Settings(ctx context.Context, orgID string) (Settings, bool, error) { var out Settings err := s.db.GetContext(ctx, &out, ` - SELECT org_id, approval_deadline_ms, raise_after, frozen, recurrence_threshold, + SELECT org_id, approval_deadline_ms, propose_autonomy_after, frozen, recurrence_threshold, default_owner, escalation::text AS escalation, attempts_per_run, timing::text AS timing, actions_per_run, actions_per_day FROM governance.settings WHERE org_id = $1`, orgID) @@ -267,13 +267,13 @@ func (s *Store) Settings(ctx context.Context, orgID string) (Settings, bool, err // PutSettings records the organisation's settings. func (s *Store) PutSettings(ctx context.Context, set Settings) error { if _, err := s.db.NamedExecContext(ctx, ` - INSERT INTO governance.settings (org_id, approval_deadline_ms, raise_after, frozen, recurrence_threshold, + INSERT INTO governance.settings (org_id, approval_deadline_ms, propose_autonomy_after, frozen, recurrence_threshold, default_owner, escalation, attempts_per_run, timing, actions_per_run, actions_per_day) - VALUES (:org_id, :approval_deadline_ms, :raise_after, :frozen, :recurrence_threshold, + VALUES (:org_id, :approval_deadline_ms, :propose_autonomy_after, :frozen, :recurrence_threshold, :default_owner, CAST(:escalation AS jsonb), :attempts_per_run, CAST(:timing AS jsonb), :actions_per_run, :actions_per_day) ON CONFLICT (org_id) DO UPDATE - SET approval_deadline_ms = EXCLUDED.approval_deadline_ms, raise_after = EXCLUDED.raise_after, + SET approval_deadline_ms = EXCLUDED.approval_deadline_ms, propose_autonomy_after = EXCLUDED.propose_autonomy_after, frozen = EXCLUDED.frozen, recurrence_threshold = EXCLUDED.recurrence_threshold, default_owner = EXCLUDED.default_owner, escalation = EXCLUDED.escalation, attempts_per_run = EXCLUDED.attempts_per_run, timing = EXCLUDED.timing, diff --git a/modules/judgement/classes.go b/modules/judgement/action_types.go similarity index 51% rename from modules/judgement/classes.go rename to modules/judgement/action_types.go index 96a629ce1..bb3d35463 100644 --- a/modules/judgement/classes.go +++ b/modules/judgement/action_types.go @@ -18,13 +18,13 @@ import ( "github.com/samcharles93/archie-core/modules/judgement/internal/store" ) -// historyLimit bounds the decisions one class's history returns. +// historyLimit bounds the decisions one action type's history returns. const historyLimit = 100 -// ErrNoClass means no action class has that id. -var ErrNoClass = store.ErrNoClass +// ErrNoActionType means no action type has that id. +var ErrNoActionType = store.ErrNoActionType -// DefaultLevel is the level a class starts at, and returns to on a reset: +// DefaultLevel is the level an action type 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 { @@ -41,32 +41,32 @@ type Outcome struct { } // 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. +// the approvals module's to answer, so an action type'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 +// ActionTypes owns one organisation's action types: the level each stands at and // the history behind it. -type Classes struct { +type ActionTypes 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} +// NewActionTypes returns the action types of orgID. +func NewActionTypes(db *sqlx.DB, log *slog.Logger, orgID string) *ActionTypes { + return &ActionTypes{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 +// Level returns the level c stands at, making the action type 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, +// kept with the action type, so a reset knows what its default is. +func (c *ActionTypes) Level(ctx context.Context, actionType ActionType, readOnly bool) (Level, error) { + row, err := c.store.EnsureActionType(ctx, store.ActionType{ + ID: uuid.New(), OrgID: c.orgID, Connector: actionType.Connector, Action: actionType.Action, + TargetKind: actionType.TargetKind, Environment: actionType.Environment, ReadOnly: readOnly, Level: DefaultLevel(readOnly).String(), }) if err != nil { @@ -83,8 +83,8 @@ func parseLevel(s string) (Level, error) { return l, nil } -// ClassView is an action class as the API lists it. -type ClassView struct { +// ActionTypeView is an action type as the API lists it. +type ActionTypeView struct { ID uuid.UUID `json:"id"` Connector string `json:"connector"` Action string `json:"action"` @@ -95,16 +95,16 @@ type ClassView struct { Decisions int `json:"decisions"` LastDecidedAt *time.Time `json:"last_decided_at,omitzero"` ResetAt *time.Time `json:"reset_at,omitzero"` - // Count is the approvals in a row since the class was last tightened or + // Count is the approvals in a row since the action type was last tightened or // raised. Count int `json:"count"` - // TightenedAt and TightenedBecause say when and why the class last lost + // TightenedAt and TightenedBecause say when and why the action type last lost // autonomy. TightenedAt *time.Time `json:"tightened_at,omitzero"` TightenedBecause string `json:"tightened_because,omitzero"` } -// HistoryEntry is one decision in a class's history, with what became of its +// HistoryEntry is one decision in an action type's history, with what became of its // request for approval. type HistoryEntry struct { DecisionID uuid.UUID `json:"decision_id"` @@ -119,7 +119,7 @@ type HistoryEntry struct { At time.Time `json:"at"` } -// ResetView is one return of a class to its default. +// ResetView is one return of an action type to its default. type ResetView struct { From Level `json:"from"` To Level `json:"to"` @@ -127,39 +127,41 @@ type ResetView struct { At time.Time `json:"at"` } -// RaiseView is one proposal to loosen a class by one level. -type RaiseView struct { - ID uuid.UUID `json:"id"` - From Level `json:"from"` - To Level `json:"to"` - State string `json:"state"` - Deadline time.Time `json:"deadline"` - ProposedAt time.Time `json:"proposed_at"` - AnsweredBy string `json:"answered_by,omitzero"` - AnsweredAt *time.Time `json:"answered_at,omitzero"` +// AutonomyProposalView is one proposal to loosen an action type by one level. +type AutonomyProposalView struct { + ID uuid.UUID `json:"id"` + From Level `json:"from"` + To Level `json:"to"` + State string `json:"state"` + Deadline time.Time `json:"deadline"` + ProposedAt time.Time `json:"proposed_at"` + AnsweredBy string `json:"answered_by,omitzero"` + // AnsweredByID is the identity ID of the account that answered. + AnsweredByID string `json:"answered_by_id,omitzero"` + AnsweredAt *time.Time `json:"answered_at,omitzero"` // Evidence is the approvals that earned the proposal. - Evidence []RaiseEvidence `json:"evidence"` + Evidence []ProposalEvidence `json:"evidence"` } -// ClassDetail is a class with its history, newest first. -type ClassDetail struct { - ClassView +// ActionTypeDetail is an action type with its history, newest first. +type ActionTypeDetail struct { + ActionTypeView History []HistoryEntry `json:"history"` Resets []ResetView `json:"resets"` - // Raises are the proposals to loosen the class, newest first. One whose + // Autonomy proposals are the proposals to loosen the action type, newest first. One whose // state is pending waits for an answer. - Raises []RaiseView `json:"raises"` + AutonomyProposals []AutonomyProposalView `json:"autonomy_proposals"` } -// 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) +// List returns every action type, most recently decided first. +func (c *ActionTypes) List(ctx context.Context) ([]ActionTypeView, error) { + rows, err := c.store.ActionTypes(ctx, c.orgID) if err != nil { return nil, err } - out := make([]ClassView, 0, len(rows)) + out := make([]ActionTypeView, 0, len(rows)) for _, r := range rows { - v, err := viewOf(r.Class) + v, err := viewOf(r.ActionType) if err != nil { return nil, err } @@ -172,12 +174,12 @@ func (c *Classes) List(ctx context.Context) ([]ClassView, error) { return out, nil } -func viewOf(r store.Class) (ClassView, error) { +func viewOf(r store.ActionType) (ActionTypeView, error) { level, err := parseLevel(r.Level) if err != nil { - return ClassView{}, fmt.Errorf("class %s: %w", r.ID, err) + return ActionTypeView{}, fmt.Errorf("action type %s: %w", r.ID, err) } - v := ClassView{ + v := ActionTypeView{ ID: r.ID, Connector: r.Connector, Action: r.Action, TargetKind: r.TargetKind, Environment: r.Environment, Level: level, Default: DefaultLevel(r.ReadOnly), } @@ -190,31 +192,31 @@ func viewOf(r store.Class) (ClassView, error) { return v, nil } -// Detail returns one class with its newest decisions and resets. The approval +// Detail returns one action type 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) +func (c *ActionTypes) Detail(ctx context.Context, id uuid.UUID, outcomes Outcomes) (ActionTypeDetail, error) { + row, err := c.store.ActionTypeByID(ctx, c.orgID, id) if err != nil { - return ClassDetail{}, err + return ActionTypeDetail{}, err } view, err := viewOf(row) if err != nil { - return ClassDetail{}, err + return ActionTypeDetail{}, err } - decisions, err := c.store.ClassDecisions(ctx, row, historyLimit) + decisions, err := c.store.ActionTypeDecisions(ctx, row, historyLimit) if err != nil { - return ClassDetail{}, err + return ActionTypeDetail{}, err } - resets, err := c.store.ClassResets(ctx, id) + resets, err := c.store.ActionTypeResets(ctx, id) if err != nil { - return ClassDetail{}, err + return ActionTypeDetail{}, err } - if view.Count, err = c.store.ClassCount(ctx, id); err != nil { - return ClassDetail{}, err + if view.Count, err = c.store.ActionTypeCount(ctx, id); err != nil { + return ActionTypeDetail{}, err } - raises, err := c.store.ClassRaises(ctx, id) + proposals, err := c.store.ActionTypeProposals(ctx, id) if err != nil { - return ClassDetail{}, err + return ActionTypeDetail{}, err } ids := make([]uuid.UUID, len(decisions)) for i, d := range decisions { @@ -222,21 +224,21 @@ func (c *Classes) Detail(ctx context.Context, id uuid.UUID, outcomes Outcomes) ( } got, err := outcomes.Outcomes(ctx, ids) if err != nil { - return ClassDetail{}, err + return ActionTypeDetail{}, err } - detail := ClassDetail{ClassView: view, Raises: make([]RaiseView, 0, len(raises))} + detail := ActionTypeDetail{ActionTypeView: view, AutonomyProposals: make([]AutonomyProposalView, 0, len(proposals))} if detail.History, err = historyOf(decisions, got); err != nil { - return ClassDetail{}, err + return ActionTypeDetail{}, err } if detail.Resets, err = resetViews(resets); err != nil { - return ClassDetail{}, err + return ActionTypeDetail{}, err } - for _, r := range raises { - v, err := c.raiseView(r) + for _, r := range proposals { + v, err := c.proposalView(r) if err != nil { - return ClassDetail{}, err + return ActionTypeDetail{}, err } - detail.Raises = append(detail.Raises, v) + detail.AutonomyProposals = append(detail.AutonomyProposals, v) } return detail, nil } @@ -277,18 +279,18 @@ func resetViews(resets []store.Reset) ([]ResetView, error) { return out, nil } -func (c *Classes) raiseView(r store.Raise) (RaiseView, error) { +func (c *ActionTypes) proposalView(r store.AutonomyProposal) (AutonomyProposalView, error) { from, err := parseLevel(r.FromLevel) if err != nil { - return RaiseView{}, err + return AutonomyProposalView{}, err } to, err := parseLevel(r.ToLevel) if err != nil { - return RaiseView{}, err + return AutonomyProposalView{}, err } - v := RaiseView{ + v := AutonomyProposalView{ ID: r.ID, From: from, To: to, State: r.State, Deadline: r.Deadline, ProposedAt: r.ProposedAt, - AnsweredBy: r.AnsweredBy.String, Evidence: []RaiseEvidence{}, + AnsweredBy: r.AnsweredBy.String, AnsweredByID: r.AnsweredByID.String, Evidence: []ProposalEvidence{}, } if v.State == "pending" && !c.now().Before(r.Deadline) { v.State = "expired" @@ -297,21 +299,21 @@ func (c *Classes) raiseView(r store.Raise) (RaiseView, error) { v.AnsweredAt = &r.AnsweredAt.Time } if err := json.Unmarshal(r.Evidence, &v.Evidence); err != nil { - return RaiseView{}, fmt.Errorf("raise %s: %w", r.ID, err) + return AutonomyProposalView{}, fmt.Errorf("autonomy proposal %s: %w", r.ID, err) } return v, nil } -// Reset returns a class to its default level. Its decisions and earlier resets +// Reset returns an action type 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) +func (c *ActionTypes) Reset(ctx context.Context, id uuid.UUID, by string) (ActionTypeView, error) { + row, err := c.store.ActionTypeByID(ctx, c.orgID, id) if err != nil { - return ClassView{}, err + return ActionTypeView{}, err } - row, err = c.store.ResetClass(ctx, c.orgID, id, DefaultLevel(row.ReadOnly).String(), by, c.now().UTC()) + row, err = c.store.ResetActionType(ctx, c.orgID, id, DefaultLevel(row.ReadOnly).String(), by, c.now().UTC()) if err != nil { - return ClassView{}, err + return ActionTypeView{}, err } return viewOf(row) } @@ -319,35 +321,35 @@ func (c *Classes) Reset(ctx context.Context, id uuid.UUID, by string) (ClassView // bootstrapAdmin names the identity the bootstrap admin token stands for. const bootstrapAdmin = "admin" -// Register adds the action classes API. -func (c *Classes) Register(api huma.API, outcomes Outcomes) { +// Register adds the action types API. +func (c *ActionTypes) Register(api huma.API, outcomes Outcomes) { tags := []string{"Controls"} - httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindClass), huma.Operation{ - OperationID: "list-classes", Method: http.MethodGet, Path: "/api/classes", - Summary: "List action classes with their earned levels", Tags: tags, + httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindActionType), huma.Operation{ + OperationID: "list-action-types", Method: http.MethodGet, Path: "/api/action-types", + Summary: "List action types with their earned levels", Tags: tags, }, c.list) - httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindClass), huma.Operation{ - OperationID: "get-class", Method: http.MethodGet, Path: "/api/classes/{id}", - Summary: "Get an action class with its history and outcomes", Tags: tags, + httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindActionType), huma.Operation{ + OperationID: "get-action-type", Method: http.MethodGet, Path: "/api/action-types/{id}", + Summary: "Get an action type with its history and outcomes", Tags: tags, }, c.detail(outcomes)) - httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindClass), huma.Operation{ - OperationID: "reset-class", Method: http.MethodPost, Path: "/api/classes/{id}/reset", - Summary: "Reset an action class to its default level", Tags: tags, + httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindActionType), huma.Operation{ + OperationID: "reset-action-type", Method: http.MethodPost, Path: "/api/action-types/{id}/reset", + Summary: "Reset an action type to its default level", Tags: tags, }, c.reset) } -func (c *Classes) list(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]ClassView], error) { +func (c *ActionTypes) list(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]ActionTypeView], error) { out, err := c.List(ctx) if err != nil { - c.log.ErrorContext(ctx, "list classes", "error", err) - return nil, huma.Error500InternalServerError("couldn't list action classes") + c.log.ErrorContext(ctx, "list action types", "error", err) + return nil, huma.Error500InternalServerError("couldn't list action types") } return httpapi.OK(out), nil } -func (c *Classes) detail(outcomes Outcomes) func(context.Context, *classInput) (*httpapi.Reply[ClassDetail], error) { - return func(ctx context.Context, in *classInput) (*httpapi.Reply[ClassDetail], error) { - id, err := classID(in.ID) +func (c *ActionTypes) detail(outcomes Outcomes) func(context.Context, *actionTypeInput) (*httpapi.Reply[ActionTypeDetail], error) { + return func(ctx context.Context, in *actionTypeInput) (*httpapi.Reply[ActionTypeDetail], error) { + id, err := actionTypeID(in.ID) if err != nil { return nil, err } @@ -359,12 +361,12 @@ func (c *Classes) detail(outcomes Outcomes) func(context.Context, *classInput) ( } } -type classInput struct { +type actionTypeInput struct { ID string `path:"id" format:"uuid"` } -func (c *Classes) reset(ctx context.Context, in *classInput) (*httpapi.Reply[ClassView], error) { - id, err := classID(in.ID) +func (c *ActionTypes) reset(ctx context.Context, in *actionTypeInput) (*httpapi.Reply[ActionTypeView], error) { + id, err := actionTypeID(in.ID) if err != nil { return nil, err } @@ -375,19 +377,19 @@ func (c *Classes) reset(ctx context.Context, in *classInput) (*httpapi.Reply[Cla return httpapi.OK(out), nil } -func classID(raw string) (uuid.UUID, error) { +func actionTypeID(raw string) (uuid.UUID, error) { id, err := uuid.Parse(raw) if err != nil { - return uuid.Nil, huma.Error400BadRequest("id is a class id") + return uuid.Nil, huma.Error400BadRequest("id is an action type id") } return id, nil } // found writes the error response for err and reports whether there was none. -func (c *Classes) notFound(ctx context.Context, err error) error { - if errors.Is(err, ErrNoClass) { - return huma.Error404NotFound("no such action class") +func (c *ActionTypes) notFound(ctx context.Context, err error) error { + if errors.Is(err, ErrNoActionType) { + return huma.Error404NotFound("no such action type") } - c.log.ErrorContext(ctx, "action class", "error", err) - return huma.Error500InternalServerError("couldn't read the action class") + c.log.ErrorContext(ctx, "action type", "error", err) + return huma.Error500InternalServerError("couldn't read the action type") } diff --git a/modules/judgement/autonomy.go b/modules/judgement/autonomy.go index ffde1ef23..01d52ffdd 100644 --- a/modules/judgement/autonomy.go +++ b/modules/judgement/autonomy.go @@ -12,64 +12,64 @@ import ( "github.com/samcharles93/archie-core/modules/judgement/internal/store" ) -// event is something that happened to an action class that bears on how much +// event is something that happened to an action type that bears on how much // autonomy it has. type event int const ( - // approved: a person allowed one of the class's held actions. + // approved: a person allowed one of the action type's held actions. approved event = iota + 1 - // denied: a person refused one of the class's held actions. + // denied: a person refused one of the action type's held actions. denied - // failed: an action of the class failed, or its outcome is unknown. + // failed: an action of the action type failed, or its outcome is unknown. failed - // raiseApproved: a person approved the proposal to loosen the class. - raiseApproved - // raiseRefused: a person refused the proposal to loosen the class. - raiseRefused + // proposalApproved: a person approved the proposal to loosen the action type. + proposalApproved + // proposalRefused: a person refused the proposal to loosen the action type. + proposalRefused ) -// standing is what a class has earned: its level, the approvals counted since -// it was last tightened or raised, and the level a raise waiting for an +// standing is what an action type has earned: its level, the approvals counted since +// it was last tightened or raised, and the level an autonomy proposal waiting for an // answer would take it to (zero when none waits). type standing struct { - level Level - count int - raiseTo Level + level Level + count int + proposedLevel Level } // after returns the standing the event leaves, and whether it earns a new -// proposal to raise the class by one level once need approvals in a row have +// autonomy proposal for the action type by one level once need approvals in a row have // counted. Autonomy is lost at once and earned only through a person: a -// denial or failure never loosens a class, and approvals never loosen it +// denial or failure never loosens an action type, and approvals never loosen it // themselves. func (s standing) after(e event, need int) (next standing, propose bool) { next = s switch e { case approved: next.count++ - if s.raiseTo == 0 && next.count >= need && s.level > ActQuietly && s.level < Never { - next.raiseTo = s.level - 1 + if s.proposedLevel == 0 && next.count >= need && s.level > ActQuietly && s.level < Never { + next.proposedLevel = s.level - 1 propose = true } case denied, failed: - next.level, next.count, next.raiseTo = max(s.level, ProposeAndWait), 0, 0 - case raiseApproved: - // A raise answers the level it was proposed from. A class that moved + next.level, next.count, next.proposedLevel = max(s.level, ProposeAndWait), 0, 0 + case proposalApproved: + // An autonomy proposal answers the level it was proposed from. An action type that moved // since stays where it is. - if s.raiseTo != 0 && s.level == s.raiseTo+1 { - next.level, next.count = s.raiseTo, 0 + if s.proposedLevel != 0 && s.level == s.proposedLevel+1 { + next.level, next.count = s.proposedLevel, 0 } - next.raiseTo = 0 - case raiseRefused: - next.count, next.raiseTo = 0, 0 + next.proposedLevel = 0 + case proposalRefused: + next.count, next.proposedLevel = 0, 0 } return next, propose } // freezeCeiling is the ceiling a freeze sets: a frozen organisation holds // every action that changes something at propose and wait, and leaves reading -// alone. The class levels aren't touched, so lifting the freeze restores them. +// alone. The action type levels aren't touched, so lifting the freeze restores them. func freezeCeiling(frozen, readOnly bool) Level { if frozen && !readOnly { return ProposeAndWait @@ -77,50 +77,50 @@ func freezeCeiling(frozen, readOnly bool) Level { return ActQuietly } -// Raise is Archie's proposal to loosen a class by one level, with the +// AutonomyProposal is Archie's proposal to loosen an action type by one level, with the // approvals that earned it. -type Raise struct { - ID uuid.UUID - Class Class - From, To Level - Evidence []RaiseEvidence - Deadline time.Time +type AutonomyProposal struct { + ID uuid.UUID + ActionType ActionType + From, To Level + Evidence []ProposalEvidence + Deadline time.Time } -// RaiseEvidence is one approval counted toward a raise. -type RaiseEvidence struct { +// ProposalEvidence is one approval counted toward an autonomy proposal. +type ProposalEvidence struct { DecisionID uuid.UUID `json:"decision_id"` By string `json:"by"` At time.Time `json:"at"` } // Approved counts a person's approval of the held action decisionID, and -// returns the raise it earns, if it does: need approvals in a row since the -// class was last tightened. The raise waits until deadline for an answer. -func (c *Classes) Approved(ctx context.Context, decisionID uuid.UUID, by string, need int, deadline time.Time) (*Raise, error) { - row, err := c.store.ClassOfDecision(ctx, c.orgID, decisionID) - if errors.Is(err, store.ErrNoClass) { +// returns the autonomy proposal it earns, if it does: need approvals in a row since the +// action type was last tightened. The autonomy proposal waits until deadline for an answer. +func (c *ActionTypes) Approved(ctx context.Context, decisionID uuid.UUID, by string, need int, deadline time.Time) (*AutonomyProposal, error) { + row, err := c.store.ActionTypeOfDecision(ctx, c.orgID, decisionID) + if errors.Is(err, store.ErrNoActionType) { return nil, nil } if err != nil { return nil, err } - var out *Raise - err = c.store.InClass(ctx, c.orgID, row.ID, c.now().UTC(), func(t *store.ClassTx) error { + var out *AutonomyProposal + err = c.store.InActionType(ctx, c.orgID, row.ID, c.now().UTC(), func(t *store.ActionTypeTx) error { if err := t.AddApproval(ctx, decisionID, by); err != nil { return err } - out, err = c.apply(ctx, t, approved, need, deadline, "") + out, err = c.apply(ctx, t, approved, need, deadline, cause{}) return err }) return out, err } -// Denied tightens the class of the held action decisionID that a person +// Denied tightens the action type of the held action decisionID that a person // refused. -func (c *Classes) Denied(ctx context.Context, decisionID uuid.UUID) error { - row, err := c.store.ClassOfDecision(ctx, c.orgID, decisionID) - if errors.Is(err, store.ErrNoClass) { +func (c *ActionTypes) Denied(ctx context.Context, decisionID uuid.UUID) error { + row, err := c.store.ActionTypeOfDecision(ctx, c.orgID, decisionID) + if errors.Is(err, store.ErrNoActionType) { return nil } if err != nil { @@ -129,14 +129,14 @@ func (c *Classes) Denied(ctx context.Context, decisionID uuid.UUID) error { return c.tighten(ctx, row.ID, "denied") } -// Failed tightens the class of an action that failed or whose outcome is +// Failed tightens the action type of an action that failed or whose outcome is // unknown. -func (c *Classes) Failed(ctx context.Context, class Class) error { - row, err := c.store.ClassByKey(ctx, store.Class{ - OrgID: c.orgID, Connector: class.Connector, Action: class.Action, - TargetKind: class.TargetKind, Environment: class.Environment, +func (c *ActionTypes) Failed(ctx context.Context, actionType ActionType) error { + row, err := c.store.ActionTypeByKey(ctx, store.ActionType{ + OrgID: c.orgID, Connector: actionType.Connector, Action: actionType.Action, + TargetKind: actionType.TargetKind, Environment: actionType.Environment, }) - if errors.Is(err, store.ErrNoClass) { + if errors.Is(err, store.ErrNoActionType) { return nil } if err != nil { @@ -145,69 +145,82 @@ func (c *Classes) Failed(ctx context.Context, class Class) error { return c.tighten(ctx, row.ID, "failed") } -func (c *Classes) tighten(ctx context.Context, id uuid.UUID, because string) error { - return c.store.InClass(ctx, c.orgID, id, c.now().UTC(), func(t *store.ClassTx) error { - _, err := c.apply(ctx, t, denied, 0, time.Time{}, because) +func (c *ActionTypes) tighten(ctx context.Context, id uuid.UUID, because string) error { + return c.store.InActionType(ctx, c.orgID, id, c.now().UTC(), func(t *store.ActionTypeTx) error { + _, err := c.apply(ctx, t, denied, 0, time.Time{}, cause{because: because}) return err }) } -// AnswerRaise settles raise id with a person's answer, and raises the class -// when it was approved and the class still stands where the proposal was made -// from. It reports whether the class was raised. An answer to a raise that is +// AnswerProposal settles autonomy proposal id with a person's answer, and loosens the action type +// when it was approved and the action type still stands where the proposal was made +// from. It reports whether the action type was loosened. An answer to an autonomy proposal that is // no longer waiting changes nothing. -func (c *Classes) AnswerRaise(ctx context.Context, id uuid.UUID, answeredBy string, approve bool) (bool, error) { - raise, err := c.store.RaiseByID(ctx, c.orgID, id) +func (c *ActionTypes) AnswerProposal(ctx context.Context, id uuid.UUID, who Answerer, approve bool) (bool, error) { + proposal, err := c.store.ProposalByID(ctx, c.orgID, id) if err != nil { return false, err } - var raised bool - err = c.store.InClass(ctx, c.orgID, raise.ClassID, c.now().UTC(), func(t *store.ClassTx) error { + var loosened bool + err = c.store.InActionType(ctx, c.orgID, proposal.ActionTypeID, c.now().UTC(), func(t *store.ActionTypeTx) error { _, pending, err := t.Count(ctx) if err != nil || pending == nil || pending.ID != id { return err } - e := raiseRefused + e := proposalRefused if approve { - e = raiseApproved + e = proposalApproved } - before := t.Class.Level - if _, err := c.apply(ctx, t, e, 0, time.Time{}, answeredBy); err != nil { + before := t.ActionType.Level + if _, err := c.apply(ctx, t, e, 0, time.Time{}, cause{answerer: who}); err != nil { return err } - raised = approve && before == pending.FromLevel + loosened = approve && before == pending.FromLevel return nil }) - return raised, err + return loosened, err } -// CancelRaise withdraws a raise whose request couldn't be asked, so the class +// CancelProposal withdraws an autonomy proposal whose request couldn't be asked, so the action type // proposes it again at its next approval. -func (c *Classes) CancelRaise(ctx context.Context, id uuid.UUID) error { - return c.store.CancelRaise(ctx, c.orgID, id) +func (c *ActionTypes) CancelProposal(ctx context.Context, id uuid.UUID) error { + return c.store.CancelProposal(ctx, c.orgID, id) } -// apply moves the locked class through e and stores what changed. by is who -// answered a raise, or why the class was tightened. -func (c *Classes) apply(ctx context.Context, t *store.ClassTx, e event, need int, deadline time.Time, by string) (*Raise, error) { +// Answerer is the account that answered an autonomy proposal: its identity ID, +// and its display name at the time of the answer. +type Answerer struct { + ID string + Name string +} + +// cause is why apply moves an action type: who answered an autonomy proposal, +// or why the action type was tightened. +type cause struct { + answerer Answerer + because string +} + +// apply moves the locked action type through e and stores what changed. +func (c *ActionTypes) apply(ctx context.Context, t *store.ActionTypeTx, e event, need int, deadline time.Time, why cause) (*AutonomyProposal, error) { cur, pending, err := standingOf(ctx, t) if err != nil { return nil, err } next, propose := cur.after(e, need) - if err := write(ctx, t, e, cur, next, pending, by); err != nil { + if err := write(ctx, t, e, cur, next, pending, why); err != nil { return nil, err } if !propose { return nil, nil } - return c.propose(ctx, t, cur.level, next.raiseTo, deadline) + return c.propose(ctx, t, cur.level, next.proposedLevel, deadline) } -// standingOf reads the locked class's standing, and the raise waiting for an +// standingOf reads the locked action type's standing, and the autonomy proposal waiting for an // answer if one is. -func standingOf(ctx context.Context, t *store.ClassTx) (standing, *store.Raise, error) { - level, err := parseLevel(t.Class.Level) +func standingOf(ctx context.Context, t *store.ActionTypeTx) (standing, *store.AutonomyProposal, error) { + level, err := parseLevel(t.ActionType.Level) if err != nil { return standing{}, nil, err } @@ -217,7 +230,7 @@ func standingOf(ctx context.Context, t *store.ClassTx) (standing, *store.Raise, } s := standing{level: level, count: count} if pending != nil { - if s.raiseTo, err = parseLevel(pending.ToLevel); err != nil { + if s.proposedLevel, err = parseLevel(pending.ToLevel); err != nil { return standing{}, nil, err } } @@ -225,10 +238,10 @@ func standingOf(ctx context.Context, t *store.ClassTx) (standing, *store.Raise, } // write stores the difference between two standings. -func write(ctx context.Context, t *store.ClassTx, e event, cur, next standing, pending *store.Raise, by string) error { +func write(ctx context.Context, t *store.ActionTypeTx, e event, cur, next standing, pending *store.AutonomyProposal, why cause) error { switch { case e == denied || e == failed: - if err := t.Tighten(ctx, next.level.String(), by); err != nil { + if err := t.Tighten(ctx, next.level.String(), why.because); err != nil { return err } case next.level != cur.level: @@ -241,52 +254,55 @@ func write(ctx context.Context, t *store.ClassTx, e event, cur, next standing, p return err } } - if pending != nil && next.raiseTo == 0 { - return t.CloseRaise(ctx, closedRaiseState(e, next.level != cur.level), closedBy(e, by)) + if pending != nil && next.proposedLevel == 0 { + who := closedBy(e, why.answerer) + return t.CloseProposal(ctx, closedProposalState(e, next.level != cur.level), who.Name, who.ID) } return nil } -// closedRaiseState is how a raise ended. An approval that changed nothing, -// because the class had moved since, doesn't count as approved. -func closedRaiseState(e event, raised bool) string { +// closedProposalState is how an autonomy proposal ended. An approval that changed nothing, +// because the action type had moved since, doesn't count as approved. +func closedProposalState(e event, loosened bool) string { switch { - case e == raiseApproved && raised: + case e == proposalApproved && loosened: return "approved" - case e == raiseRefused: + case e == proposalRefused: return "denied" } return "superseded" } -func closedBy(e event, by string) string { - if e == raiseApproved || e == raiseRefused { - return by +// closedBy is who closed a proposal: the answerer when a person answered it, +// and nobody when it was withdrawn. +func closedBy(e event, who Answerer) Answerer { + if e == proposalApproved || e == proposalRefused { + return who } - return "" + return Answerer{} } -func (c *Classes) propose(ctx context.Context, t *store.ClassTx, from, to Level, deadline time.Time) (*Raise, error) { +func (c *ActionTypes) propose(ctx context.Context, t *store.ActionTypeTx, from, to Level, deadline time.Time) (*AutonomyProposal, error) { evidence, err := t.Approvals(ctx) if err != nil { return nil, err } - shown := make([]RaiseEvidence, len(evidence)) + shown := make([]ProposalEvidence, len(evidence)) for i, a := range evidence { - shown[i] = RaiseEvidence{DecisionID: a.DecisionID, By: a.By, At: a.At} + shown[i] = ProposalEvidence{DecisionID: a.DecisionID, By: a.By, At: a.At} } body, err := json.Marshal(shown) if err != nil { return nil, fmt.Errorf("encode evidence: %w", err) } - r := &Raise{ + r := &AutonomyProposal{ ID: uuid.New(), From: from, To: to, Evidence: shown, Deadline: deadline.UTC(), - Class: Class{ - Connector: t.Class.Connector, Action: t.Class.Action, - TargetKind: t.Class.TargetKind, Environment: t.Class.Environment, + ActionType: ActionType{ + Connector: t.ActionType.Connector, Action: t.ActionType.Action, + TargetKind: t.ActionType.TargetKind, Environment: t.ActionType.Environment, }, } - if err := t.InsertRaise(ctx, store.Raise{ + if err := t.InsertProposal(ctx, store.AutonomyProposal{ ID: r.ID, FromLevel: from.String(), ToLevel: to.String(), Evidence: body, Deadline: r.Deadline, }); err != nil { return nil, err diff --git a/modules/judgement/autonomy_test.go b/modules/judgement/autonomy_test.go index 972bd8e25..40df97606 100644 --- a/modules/judgement/autonomy_test.go +++ b/modules/judgement/autonomy_test.go @@ -3,10 +3,10 @@ package judgement import "testing" // TestAutonomyIsEarnedSlowlyAndLostAtOnce guards the earned-autonomy seam: a -// class earns a proposal to loosen only after N approvals in a row since it was +// action type earns a proposal to loosen only after N approvals in a row since it was // last tightened, loosens only when that proposal is approved, drops to propose // and wait at once on a denial or a failure (and never loosens by doing so), -// and a freeze holds changing actions without touching the class level. +// and a freeze holds changing actions without touching the action type level. func TestAutonomyIsEarnedSlowlyAndLostAtOnce(t *testing.T) { const need = 3 tests := []struct { @@ -27,24 +27,24 @@ func TestAutonomyIsEarnedSlowlyAndLostAtOnce(t *testing.T) { { name: "the Nth approval proposes one level up", start: standing{level: ProposeAndWait}, events: []event{approved, approved, approved}, - want: standing{level: ProposeAndWait, count: 3, raiseTo: ActAndTell}, wantPropose: 1, + want: standing{level: ProposeAndWait, count: 3, proposedLevel: ActAndTell}, wantPropose: 1, wantHeld: ProposeAndWait, }, { name: "approvals while a proposal waits propose nothing more", start: standing{level: ProposeAndWait}, events: []event{approved, approved, approved, approved, approved}, - want: standing{level: ProposeAndWait, count: 5, raiseTo: ActAndTell}, wantPropose: 1, + want: standing{level: ProposeAndWait, count: 5, proposedLevel: ActAndTell}, wantPropose: 1, wantHeld: ProposeAndWait, }, { - name: "an approved proposal raises the class and restarts the count", start: standing{level: ProposeAndWait}, - events: []event{approved, approved, approved, raiseApproved}, + name: "an approved proposal autonomy proposals the action type and restarts the count", start: standing{level: ProposeAndWait}, + events: []event{approved, approved, approved, proposalApproved}, want: standing{level: ActAndTell}, wantPropose: 1, wantHeld: ActAndTell, }, { name: "a refused proposal leaves the level and restarts the count", start: standing{level: ProposeAndWait}, - events: []event{approved, approved, approved, raiseRefused}, + events: []event{approved, approved, approved, proposalRefused}, want: standing{level: ProposeAndWait}, wantPropose: 1, wantHeld: ProposeAndWait, }, @@ -55,37 +55,37 @@ func TestAutonomyIsEarnedSlowlyAndLostAtOnce(t *testing.T) { wantHeld: ProposeAndWait, }, { - name: "a denial drops a raised class to propose and wait", start: standing{level: ActAndTell}, + name: "a denial drops a raised action type to propose and wait", start: standing{level: ActAndTell}, events: []event{denied}, want: standing{level: ProposeAndWait}, wantHeld: ProposeAndWait, }, { - name: "a failure drops a raised class and withdraws the proposal", start: standing{level: ActAndTell, count: 3, raiseTo: ActQuietly}, + name: "a failure drops a raised action type and withdraws the proposal", start: standing{level: ActAndTell, count: 3, proposedLevel: ActQuietly}, events: []event{failed}, want: standing{level: ProposeAndWait}, wantHeld: ProposeAndWait, }, { - name: "a failure never loosens a class that escalates", start: standing{level: Escalate}, + name: "a failure never loosens an action type that escalates", start: standing{level: Escalate}, events: []event{failed}, want: standing{level: Escalate}, wantHeld: Escalate, }, { - name: "a proposal answered after the class dropped changes nothing", start: standing{level: ProposeAndWait, count: 3, raiseTo: ActQuietly}, - events: []event{raiseApproved}, want: standing{level: ProposeAndWait, count: 3}, + name: "a proposal answered after the action type dropped changes nothing", start: standing{level: ProposeAndWait, count: 3, proposedLevel: ActQuietly}, + events: []event{proposalApproved}, want: standing{level: ProposeAndWait, count: 3}, wantHeld: ProposeAndWait, }, { - name: "a class that acts quietly proposes nothing", start: standing{level: ActQuietly}, + name: "an action type that acts quietly proposes nothing", start: standing{level: ActQuietly}, events: []event{approved, approved, approved}, want: standing{level: ActQuietly, count: 3}, wantHeld: ActQuietly, }, { - name: "a class that never runs proposes nothing", start: standing{level: Never}, + name: "an action type that never runs proposes nothing", start: standing{level: Never}, events: []event{approved, approved, approved}, want: standing{level: Never, count: 3}, wantHeld: Never, }, { - name: "a freeze holds a raised class and keeps its level", start: standing{level: ActAndTell}, + name: "a freeze holds a raised action type and keeps its level", start: standing{level: ActAndTell}, want: standing{level: ActAndTell}, frozen: true, wantHeld: ProposeAndWait, }, @@ -95,7 +95,7 @@ func TestAutonomyIsEarnedSlowlyAndLostAtOnce(t *testing.T) { wantHeld: ActQuietly, }, { - name: "a freeze never loosens a class that escalates", start: standing{level: Escalate}, + name: "a freeze never loosens an action type that escalates", start: standing{level: Escalate}, want: standing{level: Escalate}, frozen: true, wantHeld: Escalate, }, diff --git a/modules/judgement/guards.go b/modules/judgement/guards.go index 9cef57551..308928f41 100644 --- a/modules/judgement/guards.go +++ b/modules/judgement/guards.go @@ -34,16 +34,16 @@ func (Reversibility) Judge(_ context.Context, a Action) (Verdict, error) { return Verdict{}, errors.New("the connector declares no reversibility for this action") } -// ClassLevels says what level an action class stands at. -type ClassLevels interface { - Level(ctx context.Context, c Class, readOnly bool) (Level, error) +// ActionTypeLevels says what level an action type stands at. +type ActionTypeLevels interface { + Level(ctx context.Context, c ActionType, readOnly bool) (Level, error) } -// 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 +// Precedent sets a ceiling from the action type's current level. An action type +// starts at its default (read-only action types act quietly, every other action type // proposes and waits) and stays wherever its history has put it. type Precedent struct { - Classes ClassLevels + ActionTypes ActionTypeLevels } // Name is the guard's name in verdicts. @@ -52,13 +52,13 @@ func (Precedent) Name() string { return "precedent" } // Advisory is false. func (Precedent) Advisory() bool { return false } -// Judge returns the class's level. +// Judge returns the action type's level. func (p Precedent) Judge(ctx context.Context, a Action) (Verdict, error) { - level, err := p.Classes.Level(ctx, a.Class(), a.Effect.ReadOnly) + level, err := p.ActionTypes.Level(ctx, a.ActionType(), a.Effect.ReadOnly) if err != nil { - return Verdict{}, fmt.Errorf("read class level: %w", err) + return Verdict{}, fmt.Errorf("read action type level: %w", err) } - return Verdict{Ceiling: level, Findings: []Finding{{Text: "this action class is at " + level.String()}}}, nil + return Verdict{Ceiling: level, Findings: []Finding{{Text: "this action type is at " + level.String()}}}, nil } // Freezes says whether the organisation has frozen its actions. @@ -67,8 +67,8 @@ type Freezes interface { } // Freeze holds every action that changes something at propose and wait while -// the organisation is frozen. It never changes a class's level, so lifting the -// freeze puts every class back where it stood. +// the organisation is frozen. It never changes an action type's level, so lifting the +// freeze puts every action type back where it stood. type Freeze struct { Freezes Freezes } diff --git a/modules/judgement/guards_test.go b/modules/judgement/guards_test.go index ab3a94a34..fc57fde9e 100644 --- a/modules/judgement/guards_test.go +++ b/modules/judgement/guards_test.go @@ -46,7 +46,7 @@ func (f fakeCounts) Actions(context.Context, uuid.UUID, string, time.Time) (int, // the specification's demo guard table gives for deleting old runner // directories (a non-production host, disposable temp data, a verified alert, // inside budget and schedule) and for deleting a container's cache (no data -// known about the container, a class that is new), and the cases that hold +// known about the container, an action type that is new), and the cases that hold // either one. func TestGuardsReturnTheDemoVerdicts(t *testing.T) { known := TargetFacts{Count: 1, DataClass: "temp", Owner: "platform"} @@ -88,8 +88,8 @@ func TestGuardsReturnTheDemoVerdicts(t *testing.T) { {"reversibility: reading", Reversibility{}, read, ActQuietly}, {"reversibility: undone automatically", Reversibility{}, func() Action { a := runner; a.Effect.Reversibility = connectors.UndoneAutomatically; return a }(), ActQuietly}, - {"precedent: earned class", Precedent{Classes: classLevel{ActAndTell}}, runner, ActAndTell}, - {"precedent: new class", Precedent{Classes: classLevel{ProposeAndWait}}, container, ProposeAndWait}, + {"precedent: earned action type", Precedent{ActionTypes: actionTypeLevel{ActAndTell}}, runner, ActAndTell}, + {"precedent: new action type", Precedent{ActionTypes: actionTypeLevel{ProposeAndWait}}, container, ProposeAndWait}, {"provenance: verified alert", Provenance{Events: fakeEvents{verified: true, untrusted: []string{prose}}}, runner, ActQuietly}, {"provenance: no verified source", Provenance{Events: fakeEvents{}}, runner, ProposeAndWait}, diff --git a/modules/judgement/internal/store/action_types.go b/modules/judgement/internal/store/action_types.go new file mode 100644 index 000000000..6c77d4889 --- /dev/null +++ b/modules/judgement/internal/store/action_types.go @@ -0,0 +1,166 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" + + "github.com/google/uuid" +) + +// ErrNoActionType means no action type has that id. +var ErrNoActionType = errors.New("no such action type") + +// ActionType is one action type and the level it stands at. +type ActionType 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"` + // TightenedAt and TightenedBecause say when and why the action type last lost + // autonomy; the count of approvals restarts there. + TightenedAt sql.NullTime `db:"tightened_at"` + TightenedBecause sql.NullString `db:"tightened_because"` +} + +// ActionTypeSummary is an action type with how many decisions it holds. +type ActionTypeSummary struct { + ActionType + Decisions int `db:"decisions"` + LastAt sql.NullTime `db:"last_at"` + Streak int `db:"streak"` +} + +// Reset is one return of an action type 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 actionTypeColumns = `id, org_id, connector, action, target_kind, environment, read_only, level, created_at, reset_at, tightened_at, tightened_because` + +// EnsureActionType returns the action type c names, creating it at c.Level when it is +// new. An existing action type keeps its level. +func (s *Store) EnsureActionType(ctx context.Context, c ActionType) (ActionType, error) { + var out ActionType + err := s.db.GetContext(ctx, &out, ` + INSERT INTO judgement.action_types (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.action_types.read_only + RETURNING `+actionTypeColumns, + c.ID, c.OrgID, c.Connector, c.Action, c.TargetKind, c.Environment, c.ReadOnly, c.Level) + if err != nil { + return ActionType{}, fmt.Errorf("ensure action type: %w", err) + } + return out, nil +} + +// Action types returns every action type, most recently decided first. +func (s *Store) ActionTypes(ctx context.Context, orgID string) ([]ActionTypeSummary, error) { + var out []ActionTypeSummary + 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, c.tightened_at, c.tightened_because, + 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 + FROM judgement.action_types 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 AND NOT d.dry + 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 action types: %w", err) + } + return out, nil +} + +// ActionTypeByID returns one action type. +func (s *Store) ActionTypeByID(ctx context.Context, orgID string, id uuid.UUID) (ActionType, error) { + var out ActionType + err := s.db.GetContext(ctx, &out, `SELECT `+actionTypeColumns+` FROM judgement.action_types WHERE org_id = $1 AND id = $2`, orgID, id) + if errors.Is(err, sql.ErrNoRows) { + return ActionType{}, ErrNoActionType + } + if err != nil { + return ActionType{}, fmt.Errorf("read action type: %w", err) + } + return out, nil +} + +// ActionTypeDecisions returns an action type's newest decisions, newest first. +func (s *Store) ActionTypeDecisions(ctx context.Context, c ActionType, 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 AND NOT dry + 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 action type decisions: %w", err) + } + return out, nil +} + +// ActionTypeResets returns an action type's resets, newest first. +func (s *Store) ActionTypeResets(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.action_type_resets + WHERE action_type_id = $1 ORDER BY at DESC, id`, id) + if err != nil { + return nil, fmt.Errorf("list action type resets: %w", err) + } + return out, nil +} + +// ResetActionType sets an action type to level and records the reset, in one transaction. +func (s *Store) ResetActionType(ctx context.Context, orgID string, id uuid.UUID, level, by string, at time.Time) (ActionType, error) { + tx, err := s.db.BeginTxx(ctx, nil) + if err != nil { + return ActionType{}, fmt.Errorf("reset action type: %w", err) + } + defer func() { _ = tx.Rollback() }() + var before ActionType + err = tx.GetContext(ctx, &before, `SELECT `+actionTypeColumns+` FROM judgement.action_types WHERE org_id = $1 AND id = $2 FOR UPDATE`, orgID, id) + if errors.Is(err, sql.ErrNoRows) { + return ActionType{}, ErrNoActionType + } + if err != nil { + return ActionType{}, fmt.Errorf("reset action type: %w", err) + } + var out ActionType + if err := tx.GetContext(ctx, &out, ` + UPDATE judgement.action_types SET level = $2, reset_at = $3 WHERE id = $1 RETURNING `+actionTypeColumns, id, level, at); err != nil { + return ActionType{}, fmt.Errorf("reset action type: %w", err) + } + // A reset starts the count again and withdraws an autonomy proposal that was waiting. + if _, err := tx.ExecContext(ctx, `UPDATE judgement.action_type_approvals SET counted = false WHERE action_type_id = $1 AND counted`, id); err != nil { + return ActionType{}, fmt.Errorf("reset action type: %w", err) + } + if _, err := tx.ExecContext(ctx, `UPDATE judgement.autonomy_proposals SET state = 'superseded' WHERE action_type_id = $1 AND state = 'pending'`, id); err != nil { + return ActionType{}, fmt.Errorf("reset action type: %w", err) + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO judgement.action_type_resets (id, org_id, action_type_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 ActionType{}, fmt.Errorf("record reset: %w", err) + } + if err := tx.Commit(); err != nil { + return ActionType{}, fmt.Errorf("reset action type: %w", err) + } + return out, nil +} diff --git a/modules/judgement/internal/store/autonomy.go b/modules/judgement/internal/store/autonomy.go index 423c73cd6..29f7fc8ed 100644 --- a/modules/judgement/internal/store/autonomy.go +++ b/modules/judgement/internal/store/autonomy.go @@ -11,124 +11,127 @@ import ( "github.com/jmoiron/sqlx" ) -// ErrNoRaise means no raise has that id. -var ErrNoRaise = errors.New("no such raise") +// ErrNoProposal means no autonomy proposal has that id. +var ErrNoProposal = errors.New("no such autonomy proposal") -// Raise is a proposal to loosen a class by one level. -type Raise struct { - ID uuid.UUID `db:"id"` - OrgID string `db:"org_id"` - ClassID uuid.UUID `db:"class_id"` - FromLevel string `db:"from_level"` - ToLevel string `db:"to_level"` - Evidence []byte `db:"evidence"` - State string `db:"state"` - Deadline time.Time `db:"deadline"` - ProposedAt time.Time `db:"proposed_at"` - AnsweredBy sql.NullString `db:"answered_by"` - AnsweredAt sql.NullTime `db:"answered_at"` +// AutonomyProposal is a proposal to loosen an action type by one level. +type AutonomyProposal struct { + ID uuid.UUID `db:"id"` + OrgID string `db:"org_id"` + ActionTypeID uuid.UUID `db:"action_type_id"` + FromLevel string `db:"from_level"` + ToLevel string `db:"to_level"` + Evidence []byte `db:"evidence"` + State string `db:"state"` + Deadline time.Time `db:"deadline"` + ProposedAt time.Time `db:"proposed_at"` + AnsweredBy sql.NullString `db:"answered_by"` + // AnsweredByID is the identity ID of the account that answered; AnsweredBy + // is its display name at the time. + AnsweredByID sql.NullString `db:"answered_by_id"` + AnsweredAt sql.NullTime `db:"answered_at"` } -const raiseColumns = `id, org_id, class_id, from_level, to_level, evidence, state, deadline, proposed_at, answered_by, answered_at` +const proposalColumns = `id, org_id, action_type_id, from_level, to_level, evidence, state, deadline, proposed_at, answered_by, answered_by_id, answered_at` -// ClassOfDecision returns the class a decision belongs to. -func (s *Store) ClassOfDecision(ctx context.Context, orgID string, decisionID uuid.UUID) (Class, error) { - var out Class +// ActionTypeOfDecision returns the action type a decision belongs to. +func (s *Store) ActionTypeOfDecision(ctx context.Context, orgID string, decisionID uuid.UUID) (ActionType, error) { + var out ActionType err := s.db.GetContext(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, c.tightened_at, c.tightened_because FROM judgement.decisions d - JOIN judgement.classes 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.org_id = d.org_id AND c.connector = d.connector AND c.action = d.action AND c.target_kind = d.target_kind AND c.environment = d.environment WHERE d.org_id = $1 AND d.id = $2`, orgID, decisionID) if errors.Is(err, sql.ErrNoRows) { - return Class{}, ErrNoClass + return ActionType{}, ErrNoActionType } if err != nil { - return Class{}, fmt.Errorf("read class of decision: %w", err) + return ActionType{}, fmt.Errorf("read action type of decision: %w", err) } return out, nil } -// ClassByKey returns the class named by its four names. -func (s *Store) ClassByKey(ctx context.Context, c Class) (Class, error) { - var out Class +// ActionTypeByKey returns the action type named by its four names. +func (s *Store) ActionTypeByKey(ctx context.Context, c ActionType) (ActionType, error) { + var out ActionType err := s.db.GetContext(ctx, &out, ` - SELECT `+classColumns+` FROM judgement.classes + SELECT `+actionTypeColumns+` FROM judgement.action_types WHERE org_id = $1 AND connector = $2 AND action = $3 AND target_kind = $4 AND environment = $5`, c.OrgID, c.Connector, c.Action, c.TargetKind, c.Environment) if errors.Is(err, sql.ErrNoRows) { - return Class{}, ErrNoClass + return ActionType{}, ErrNoActionType } if err != nil { - return Class{}, fmt.Errorf("read class: %w", err) + return ActionType{}, fmt.Errorf("read action type: %w", err) } return out, nil } -// RaiseByID returns one raise. -func (s *Store) RaiseByID(ctx context.Context, orgID string, id uuid.UUID) (Raise, error) { - var out Raise - err := s.db.GetContext(ctx, &out, `SELECT `+raiseColumns+` FROM judgement.class_raises WHERE org_id = $1 AND id = $2`, orgID, id) +// ProposalByID returns one autonomy proposal. +func (s *Store) ProposalByID(ctx context.Context, orgID string, id uuid.UUID) (AutonomyProposal, error) { + var out AutonomyProposal + err := s.db.GetContext(ctx, &out, `SELECT `+proposalColumns+` FROM judgement.autonomy_proposals WHERE org_id = $1 AND id = $2`, orgID, id) if errors.Is(err, sql.ErrNoRows) { - return Raise{}, ErrNoRaise + return AutonomyProposal{}, ErrNoProposal } if err != nil { - return Raise{}, fmt.Errorf("read raise: %w", err) + return AutonomyProposal{}, fmt.Errorf("read autonomy proposal: %w", err) } return out, nil } -// ClassRaises returns a class's raises, newest first. -func (s *Store) ClassRaises(ctx context.Context, id uuid.UUID) ([]Raise, error) { - var out []Raise +// ActionTypeProposals returns an action type's autonomy proposals, newest first. +func (s *Store) ActionTypeProposals(ctx context.Context, id uuid.UUID) ([]AutonomyProposal, error) { + var out []AutonomyProposal if err := s.db.SelectContext(ctx, &out, ` - SELECT `+raiseColumns+` FROM judgement.class_raises WHERE class_id = $1 ORDER BY proposed_at DESC, id`, id); err != nil { - return nil, fmt.Errorf("list class raises: %w", err) + SELECT `+proposalColumns+` FROM judgement.autonomy_proposals WHERE action_type_id = $1 ORDER BY proposed_at DESC, id`, id); err != nil { + return nil, fmt.Errorf("list action type autonomy proposals: %w", err) } return out, nil } -// ClassCount returns how many approvals a class has counted, for the class +// ActionTypeCount returns how many approvals an action type has counted, for the action type // view. -func (s *Store) ClassCount(ctx context.Context, id uuid.UUID) (int, error) { +func (s *Store) ActionTypeCount(ctx context.Context, id uuid.UUID) (int, error) { var n int - if err := s.db.GetContext(ctx, &n, `SELECT count(*) FROM judgement.class_approvals WHERE class_id = $1 AND counted`, id); err != nil { + if err := s.db.GetContext(ctx, &n, `SELECT count(*) FROM judgement.action_type_approvals WHERE action_type_id = $1 AND counted`, id); err != nil { return 0, fmt.Errorf("count approvals: %w", err) } return n, nil } -// ClassTx is one class held for update. Everything done through it commits +// ActionTypeTx is one action type held for update. Everything done through it commits // together, so two answers arriving at once see each other's count. -type ClassTx struct { - tx *sqlx.Tx - now time.Time - Class Class +type ActionTypeTx struct { + tx *sqlx.Tx + now time.Time + ActionType ActionType } -// InClass runs fn with the class locked. A raise nobody answered by its -// deadline is expired first, and its count restarts, so a class that wasn't +// InActionType runs fn with the action type locked. An autonomy proposal nobody answered by its +// deadline is expired first, and its count restarts, so an action type that wasn't // raised is asked again only after earning it again. -func (s *Store) InClass(ctx context.Context, orgID string, id uuid.UUID, now time.Time, fn func(*ClassTx) error) error { +func (s *Store) InActionType(ctx context.Context, orgID string, id uuid.UUID, now time.Time, fn func(*ActionTypeTx) error) error { tx, err := s.db.BeginTxx(ctx, nil) if err != nil { - return fmt.Errorf("class: %w", err) + return fmt.Errorf("action type: %w", err) } defer func() { _ = tx.Rollback() }() - t := &ClassTx{tx: tx, now: now} - err = tx.GetContext(ctx, &t.Class, `SELECT `+classColumns+` FROM judgement.classes WHERE org_id = $1 AND id = $2 FOR UPDATE`, orgID, id) + t := &ActionTypeTx{tx: tx, now: now} + err = tx.GetContext(ctx, &t.ActionType, `SELECT `+actionTypeColumns+` FROM judgement.action_types WHERE org_id = $1 AND id = $2 FOR UPDATE`, orgID, id) if errors.Is(err, sql.ErrNoRows) { - return ErrNoClass + return ErrNoActionType } if err != nil { - return fmt.Errorf("lock class: %w", err) + return fmt.Errorf("lock action type: %w", err) } res, err := tx.ExecContext(ctx, ` - UPDATE judgement.class_raises SET state = 'expired', answered_at = $2 - WHERE class_id = $1 AND state = 'pending' AND deadline <= $2`, id, now) + UPDATE judgement.autonomy_proposals SET state = 'expired', answered_at = $2 + WHERE action_type_id = $1 AND state = 'pending' AND deadline <= $2`, id, now) if err != nil { - return fmt.Errorf("expire raise: %w", err) + return fmt.Errorf("expire autonomy proposal: %w", err) } if n, _ := res.RowsAffected(); n > 0 { if err := t.ClearCount(ctx); err != nil { @@ -139,41 +142,41 @@ func (s *Store) InClass(ctx context.Context, orgID string, id uuid.UUID, now tim return err } if err := tx.Commit(); err != nil { - return fmt.Errorf("class: %w", err) + return fmt.Errorf("action type: %w", err) } return nil } -// Count returns how many approvals count toward a raise, and the raise waiting +// Count returns how many approvals count toward an autonomy proposal, and the autonomy proposal waiting // for an answer, if one is. -func (t *ClassTx) Count(ctx context.Context) (int, *Raise, error) { +func (t *ActionTypeTx) Count(ctx context.Context) (int, *AutonomyProposal, error) { var n int - if err := t.tx.GetContext(ctx, &n, `SELECT count(*) FROM judgement.class_approvals WHERE class_id = $1 AND counted`, t.Class.ID); err != nil { + if err := t.tx.GetContext(ctx, &n, `SELECT count(*) FROM judgement.action_type_approvals WHERE action_type_id = $1 AND counted`, t.ActionType.ID); err != nil { return 0, nil, fmt.Errorf("count approvals: %w", err) } - var r Raise - err := t.tx.GetContext(ctx, &r, `SELECT `+raiseColumns+` FROM judgement.class_raises WHERE class_id = $1 AND state = 'pending'`, t.Class.ID) + var r AutonomyProposal + err := t.tx.GetContext(ctx, &r, `SELECT `+proposalColumns+` FROM judgement.autonomy_proposals WHERE action_type_id = $1 AND state = 'pending'`, t.ActionType.ID) if errors.Is(err, sql.ErrNoRows) { return n, nil, nil } if err != nil { - return 0, nil, fmt.Errorf("read pending raise: %w", err) + return 0, nil, fmt.Errorf("read pending autonomy proposal: %w", err) } return n, &r, nil } // AddApproval counts one approved decision. A decision counts once. -func (t *ClassTx) AddApproval(ctx context.Context, decisionID uuid.UUID, by string) error { +func (t *ActionTypeTx) AddApproval(ctx context.Context, decisionID uuid.UUID, by string) error { if _, err := t.tx.ExecContext(ctx, ` - INSERT INTO judgement.class_approvals (id, org_id, class_id, decision_id, by, at) + INSERT INTO judgement.action_type_approvals (id, org_id, action_type_id, decision_id, by, at) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (decision_id) DO NOTHING`, - uuid.New(), t.Class.OrgID, t.Class.ID, decisionID, by, t.now); err != nil { + uuid.New(), t.ActionType.OrgID, t.ActionType.ID, decisionID, by, t.now); err != nil { return fmt.Errorf("record approval: %w", err) } return nil } -// Approval is one counted approval, the evidence for a raise. +// Approval is one counted approval, the evidence for an autonomy proposal. type Approval struct { DecisionID uuid.UUID `db:"decision_id" json:"decision_id"` By string `db:"by" json:"by"` @@ -181,67 +184,68 @@ type Approval struct { } // Approvals returns the approvals that count, oldest first. -func (t *ClassTx) Approvals(ctx context.Context) ([]Approval, error) { +func (t *ActionTypeTx) Approvals(ctx context.Context) ([]Approval, error) { var out []Approval if err := t.tx.SelectContext(ctx, &out, ` - SELECT decision_id, by, at FROM judgement.class_approvals WHERE class_id = $1 AND counted ORDER BY at, id`, t.Class.ID); err != nil { + SELECT decision_id, by, at FROM judgement.action_type_approvals WHERE action_type_id = $1 AND counted ORDER BY at, id`, t.ActionType.ID); err != nil { return nil, fmt.Errorf("list approvals: %w", err) } return out, nil } // ClearCount stops every approval counting. -func (t *ClassTx) ClearCount(ctx context.Context) error { - if _, err := t.tx.ExecContext(ctx, `UPDATE judgement.class_approvals SET counted = false WHERE class_id = $1 AND counted`, t.Class.ID); err != nil { +func (t *ActionTypeTx) ClearCount(ctx context.Context) error { + if _, err := t.tx.ExecContext(ctx, `UPDATE judgement.action_type_approvals SET counted = false WHERE action_type_id = $1 AND counted`, t.ActionType.ID); err != nil { return fmt.Errorf("clear approvals: %w", err) } return nil } -// SetLevel sets the class's level. -func (t *ClassTx) SetLevel(ctx context.Context, level string) error { - if _, err := t.tx.ExecContext(ctx, `UPDATE judgement.classes SET level = $2 WHERE id = $1`, t.Class.ID, level); err != nil { +// SetLevel sets the action type's level. +func (t *ActionTypeTx) SetLevel(ctx context.Context, level string) error { + if _, err := t.tx.ExecContext(ctx, `UPDATE judgement.action_types SET level = $2 WHERE id = $1`, t.ActionType.ID, level); err != nil { return fmt.Errorf("set level: %w", err) } return nil } -// Tighten records that the class lost autonomy, and why. -func (t *ClassTx) Tighten(ctx context.Context, level, because string) error { +// Tighten records that the action type lost autonomy, and why. +func (t *ActionTypeTx) Tighten(ctx context.Context, level, because string) error { if _, err := t.tx.ExecContext(ctx, ` - UPDATE judgement.classes SET level = $2, tightened_at = $3, tightened_because = $4 WHERE id = $1`, - t.Class.ID, level, t.now, because); err != nil { - return fmt.Errorf("tighten class: %w", err) + UPDATE judgement.action_types SET level = $2, tightened_at = $3, tightened_because = $4 WHERE id = $1`, + t.ActionType.ID, level, t.now, because); err != nil { + return fmt.Errorf("tighten action type: %w", err) } return nil } -// CloseRaise settles the class's pending raise. -func (t *ClassTx) CloseRaise(ctx context.Context, state, by string) error { +// CloseProposal settles the action type's pending autonomy proposal. +func (t *ActionTypeTx) CloseProposal(ctx context.Context, state, byName, byID string) error { if _, err := t.tx.ExecContext(ctx, ` - UPDATE judgement.class_raises SET state = $2, answered_by = nullif($3, ''), answered_at = $4 - WHERE class_id = $1 AND state = 'pending'`, t.Class.ID, state, by, t.now); err != nil { - return fmt.Errorf("close raise: %w", err) + UPDATE judgement.autonomy_proposals + SET state = $2, answered_by = nullif($3, ''), answered_by_id = nullif($4, ''), answered_at = $5 + WHERE action_type_id = $1 AND state = 'pending'`, t.ActionType.ID, state, byName, byID, t.now); err != nil { + return fmt.Errorf("close autonomy proposal: %w", err) } return nil } -// InsertRaise records a proposal. -func (t *ClassTx) InsertRaise(ctx context.Context, r Raise) error { +// InsertProposal records a proposal. +func (t *ActionTypeTx) InsertProposal(ctx context.Context, r AutonomyProposal) error { if _, err := t.tx.ExecContext(ctx, ` - INSERT INTO judgement.class_raises (id, org_id, class_id, from_level, to_level, evidence, state, deadline, proposed_at) + INSERT INTO judgement.autonomy_proposals (id, org_id, action_type_id, from_level, to_level, evidence, state, deadline, proposed_at) VALUES ($1, $2, $3, $4, $5, $6, 'pending', $7, $8)`, - r.ID, t.Class.OrgID, t.Class.ID, r.FromLevel, r.ToLevel, r.Evidence, r.Deadline, t.now); err != nil { - return fmt.Errorf("record raise: %w", err) + r.ID, t.ActionType.OrgID, t.ActionType.ID, r.FromLevel, r.ToLevel, r.Evidence, r.Deadline, t.now); err != nil { + return fmt.Errorf("record autonomy proposal: %w", err) } return nil } -// CancelRaise withdraws a pending raise whose request couldn't be asked. -func (s *Store) CancelRaise(ctx context.Context, orgID string, id uuid.UUID) error { +// CancelProposal withdraws a pending autonomy proposal whose request couldn't be asked. +func (s *Store) CancelProposal(ctx context.Context, orgID string, id uuid.UUID) error { if _, err := s.db.ExecContext(ctx, ` - UPDATE judgement.class_raises SET state = 'superseded' WHERE org_id = $1 AND id = $2 AND state = 'pending'`, orgID, id); err != nil { - return fmt.Errorf("cancel raise: %w", err) + UPDATE judgement.autonomy_proposals SET state = 'superseded' WHERE org_id = $1 AND id = $2 AND state = 'pending'`, orgID, id); err != nil { + return fmt.Errorf("cancel autonomy proposal: %w", err) } return nil } diff --git a/modules/judgement/internal/store/classes.go b/modules/judgement/internal/store/classes.go deleted file mode 100644 index 13cf519fa..000000000 --- a/modules/judgement/internal/store/classes.go +++ /dev/null @@ -1,166 +0,0 @@ -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"` - // TightenedAt and TightenedBecause say when and why the class last lost - // autonomy; the count of approvals restarts there. - TightenedAt sql.NullTime `db:"tightened_at"` - TightenedBecause sql.NullString `db:"tightened_because"` -} - -// ClassSummary is a class with how many decisions it holds. -type ClassSummary struct { - Class - Decisions int `db:"decisions"` - LastAt sql.NullTime `db:"last_at"` - Streak int `db:"streak"` -} - -// 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, tightened_at, tightened_because` - -// 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, c.tightened_at, c.tightened_because, - count(d.id) AS decisions, max(d.created_at) AS last_at, - (SELECT count(*) FROM judgement.class_approvals a WHERE a.class_id = c.id AND a.counted) AS streak - 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 AND NOT d.dry - 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 AND NOT dry - 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) - } - // A reset starts the count again and withdraws a raise that was waiting. - if _, err := tx.ExecContext(ctx, `UPDATE judgement.class_approvals SET counted = false WHERE class_id = $1 AND counted`, id); err != nil { - return Class{}, fmt.Errorf("reset class: %w", err) - } - if _, err := tx.ExecContext(ctx, `UPDATE judgement.class_raises SET state = 'superseded' WHERE class_id = $1 AND state = 'pending'`, id); 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 -} diff --git a/modules/judgement/internal/store/store.go b/modules/judgement/internal/store/store.go index b4782291e..7c1f1ec56 100644 --- a/modules/judgement/internal/store/store.go +++ b/modules/judgement/internal/store/store.go @@ -1,5 +1,5 @@ // Package store holds the judgement module's SQL: every decision, with the -// action class it belongs to. +// action type it belongs to. package store import ( @@ -26,7 +26,7 @@ type Decision struct { Level string `db:"level"` Dry bool `db:"dry"` Body []byte `db:"body"` - // CreatedAt is set by the database and read only by the class history. + // CreatedAt is set by the database and read only by the action type history. CreatedAt time.Time `db:"created_at"` } diff --git a/modules/judgement/judgement.go b/modules/judgement/judgement.go index f9acdc203..a8c36703b 100644 --- a/modules/judgement/judgement.go +++ b/modules/judgement/judgement.go @@ -1,7 +1,7 @@ // 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. +// verdict, so the run's trail and the action type's history can read it. package judgement import ( @@ -50,17 +50,18 @@ type Action struct { Effect connectors.Effect `json:"effect"` } -// Class is what an action's earned autonomy belongs to. -type Class struct { +// ActionType is what an action's earned autonomy belongs to: one connector's +// action on one kind of target in one environment. +type ActionType 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} +// ActionType returns the type of the action. +func (a Action) ActionType() ActionType { + return ActionType{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. @@ -158,7 +159,7 @@ type Decision struct { Reason string `json:"reason,omitzero"` At time.Time `json:"at"` // Dry marks a decision made for a dry run. It is recorded for the run's - // trail and counts toward nothing: not spend, not a class's history. + // trail and counts toward nothing: not spend, not an action type's history. Dry bool `json:"dry,omitzero"` // Calls are the calls to the connector behind this decision: the resolve // that placed its target, the target facts it was judged on, and the @@ -207,10 +208,10 @@ type Tools interface { Tool(name string) (connectors.Tool, bool) } -// FailureRecorder is told when an action of a class failed, so the class loses +// FailureRecorder is told when an action failed, so the action type loses // the autonomy it had. type FailureRecorder interface { - Failed(ctx context.Context, c Class) error + Failed(ctx context.Context, c ActionType) error } type recorder interface { @@ -270,7 +271,7 @@ func (m *Module) UseChangeRules(r ChangeRules) { m.changeRules = r } func (m *Module) UseExtensions(e GuardExtensions) { m.extensions = e } // NewModule returns the judgement module for orgID, with its hard rules and -// guards. An action of a class that fails is reported to failed. +// guards. An action 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 { s := store.New(db) return &Module{orgID: orgID, tools: tools, rules: rules, guards: guards, store: s, queries: s, failed: failed, log: log, now: time.Now} @@ -399,7 +400,7 @@ func (m *Module) Execute(ctx context.Context, d Decision, input jsontext.Value, } // 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. +// drops the action type 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 { @@ -410,10 +411,10 @@ func (m *Module) invoke(ctx context.Context, d Decision, input jsontext.Value, k out, err := tool.Invoke(ctx, connectors.Invocation{Action: d.Action.Name, Input: input, IdempotencyKey: key}) m.keepCalls(ctx, d.ID, calls.take()) // A shutdown cancels the call without the action having gone wrong, and a - // dry run's failure is not evidence about the class. + // dry run's failure is not evidence about the action type. if err != nil && m.failed != nil && !d.Dry && !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)) + if ferr := m.failed.Failed(ctx, d.Action.ActionType()); ferr != nil { + return out, errors.Join(err, fmt.Errorf("tighten action type: %w", ferr)) } } return out, err @@ -497,7 +498,7 @@ func (m *Module) record(ctx context.Context, d Decision) (Decision, error) { if err != nil { return Decision{}, fmt.Errorf("encode decision: %w", err) } - c := d.Action.Class() + c := d.Action.ActionType() 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, diff --git a/modules/judgement/judgement_test.go b/modules/judgement/judgement_test.go index 258df784d..f113fdb3e 100644 --- a/modules/judgement/judgement_test.go +++ b/modules/judgement/judgement_test.go @@ -280,33 +280,33 @@ func TestExecuteApprovedRunsOnlyWhatThePersonSaw(t *testing.T) { } } -type classLevel struct{ level Level } +type actionTypeLevel struct{ level Level } -func (c classLevel) Level(context.Context, Class, bool) (Level, error) { return c.level, nil } +func (c actionTypeLevel) Level(context.Context, ActionType, 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. +// precedent guard's ceiling is the level its action type stands at, not a +// default, so an action type 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}, + {name: "a read-only action type at its default", level: ActQuietly, read: true}, + {name: "a changing action type raised to act and tell", level: ActAndTell}, + {name: "a changing action type at its default", level: ProposeAndWait}, + {name: "a read-only action type lowered to escalate", level: Escalate, read: true}, + {name: "an action type 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}}) + v, err := Precedent{ActionTypes: actionTypeLevel{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) + t.Fatalf("ceiling = %s, want the action type level %s", v.Ceiling, tt.level) } }) } diff --git a/proto/connector/v1/connector.proto b/proto/connector/v1/connector.proto index e0b980a90..4d7dd44eb 100644 --- a/proto/connector/v1/connector.proto +++ b/proto/connector/v1/connector.proto @@ -170,7 +170,7 @@ message Effect { } // Target is what an action acts on. Connector, action, kind and environment -// together are the action class. +// together are the action type. message Target { string kind = 1; string id = 2; @@ -217,7 +217,7 @@ message InvokeRequest { message InvokeResponse { bytes output = 1; // executed_digest is the connector's digest of what it ran. A mismatch is a - // finding and tightens the action class. + // finding and tightens the action type. string executed_digest = 2; // outcome_unknown says the connector can't confirm what its effect did. bool outcome_unknown = 3; diff --git a/ui/pages/pages.json b/ui/pages/pages.json index 596dd7fb5..7cc58aa34 100644 --- a/ui/pages/pages.json +++ b/ui/pages/pages.json @@ -22,7 +22,7 @@ { "path": "/controls", "label": "Controls", - "description": "Hard rules, change-request rules, guards and action classes." + "description": "Hard rules, change-request rules, guards and action types." }, { "path": "/workflows", diff --git a/ui/src/controls/ActionClassDetail.vue b/ui/src/controls/ActionTypeDetail.vue similarity index 71% rename from ui/src/controls/ActionClassDetail.vue rename to ui/src/controls/ActionTypeDetail.vue index 09670ae24..85df82758 100644 --- a/ui/src/controls/ActionClassDetail.vue +++ b/ui/src/controls/ActionTypeDetail.vue @@ -8,9 +8,9 @@ import { Timestamp } from "@/components/ui/timestamp"; import { api } from "@/lib/api"; import { useRead } from "@/lib/use-read"; -/** A class's recent decisions, level raises and resets. */ +/** An action type's recent decisions, autonomy proposals and resets. */ const props = defineProps<{ id: string }>(); -const { data, error, reload } = useRead(() => api.actionClass(props.id)); +const { data, error, reload } = useRead(() => api.actionType(props.id)); onMounted(reload); @@ -19,8 +19,10 @@ onMounted(reload);

Tightened : {{ data.tightened_because }}

-
    -
  • Raise {{ r.from }} → {{ r.to }}, {{ r.state }}, proposed
  • +
      +
    • + Autonomy proposal {{ p.from }} → {{ p.to }}, {{ p.state }}, proposed +
    • Reset {{ r.from }} → {{ r.to }} by {{ r.by }}
    • @@ -31,6 +33,6 @@ onMounted(reload);
    -

    No decisions yet.

    +

    No decisions yet.

diff --git a/ui/src/controls/ControlsPage.vue b/ui/src/controls/ControlsPage.vue index 5630cf70e..0407e97a9 100644 --- a/ui/src/controls/ControlsPage.vue +++ b/ui/src/controls/ControlsPage.vue @@ -13,19 +13,19 @@ import { Skeleton } from "@/components/ui/skeleton"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Timestamp } from "@/components/ui/timestamp"; import { errors } from "@/copy/errors"; -import { api, describeError, type ActionClass, type Judge } from "@/lib/api"; +import { api, describeError, type ActionType, type Judge } from "@/lib/api"; import { useRead } from "@/lib/use-read"; import { stateLabel } from "@/runs/state"; -import ActionClassDetail from "./ActionClassDetail.vue"; +import ActionTypeDetail from "./ActionTypeDetail.vue"; import PolicyText from "./PolicyText.vue"; /** What bounds every action: hard rules, change-request rules, the guards' - * judges, and the approval level each class of action has earned. */ + * judges, and the approval level each action type has earned. */ const judges = useRead(() => api.judges()); -const classes = useRead(() => api.actionClasses()); +const actionTypes = useRead(() => api.actionTypes()); onMounted(() => { void judges.reload(); - void classes.reload(); + void actionTypes.reload(); }); const route = useRoute(); @@ -33,7 +33,7 @@ const router = useRouter(); const TABS = [ { id: "rules", label: "Rules" }, { id: "guards", label: "Guards" }, - { id: "classes", label: "Action classes" }, + { id: "action-types", label: "Action types" }, ]; const tab = computed(() => (TABS.some((t) => t.id === route.query.tab) ? String(route.query.tab) : "rules")); const show = (id: unknown) => void router.replace({ query: { ...route.query, tab: id === "rules" ? undefined : String(id) } }); @@ -43,7 +43,7 @@ const judgeColumns: DataTableColumn[] = [ { id: "mode", label: "Mode", fixed: true, width: "8rem" }, { id: "latest", label: "Last evaluation", hide: "md", width: "28rem" }, ]; -const classColumns: DataTableColumn[] = [ +const actionTypeColumns: DataTableColumn[] = [ { id: "action", label: "Action", fixed: true, width: "auto", sort: (c) => `${c.connector}.${c.action}` }, { id: "target", label: "Target", hide: "md", width: "14rem", sort: (c) => c.target_kind ?? "" }, { id: "level", label: "Level", fixed: true, width: "13rem", sort: (c) => c.level }, @@ -53,14 +53,14 @@ const classColumns: DataTableColumn[] = [ ]; const resetError = ref(""); -async function reset(c: ActionClass): Promise { +async function reset(c: ActionType): Promise { resetError.value = ""; try { - await api.resetActionClass(c.id); + await api.resetActionType(c.id); } catch (cause) { resetError.value = describeError(cause, errors.common.unknown); } - await classes.reload(); + await actionTypes.reload(); } @@ -96,9 +96,9 @@ async function reset(c: ActionClass): Promise {
- - - + + +