feat(governance): each escalation step has its own deadline, and the path skips anyone below the authority an action needs (#1985)

This commit is contained in:
sam committed 2026-11-16 09:42:23 +11:00
1 parent 50b75f6987
commit 4b1ae4babf
7 files changed
+266 -40

No files matched your search

@@ -0,0 +1,41 @@
-- +goose Up
-- An escalation step carries its own deadline. The path was a list of person
-- ids; each entry becomes a person and the time that step waits, starting from
-- the default approval deadline.
UPDATE governance.settings s
SET escalation = COALESCE((
SELECT jsonb_agg(jsonb_build_object('person', e.person, 'deadline_ms', s.approval_deadline_ms) ORDER BY e.n)
FROM jsonb_array_elements_text(s.escalation) WITH ORDINALITY AS e (person, n)
), '[]'::jsonb);
-- A request records who has been asked so far and when the current step runs
-- out, so an answer is accepted only from someone the request has reached. A
-- discarded approval is one the action no longer matched when it came to run.
-- counted is set once, before the approval counts toward a raise, so a retry
-- can't count it twice.
ALTER TABLE approvals.requests DROP CONSTRAINT requests_state_check;
ALTER TABLE approvals.requests ADD CONSTRAINT requests_state_check
CHECK (state IN ('pending', 'approved', 'denied', 'expired', 'discarded'));
ALTER TABLE approvals.requests ADD COLUMN step integer NOT NULL DEFAULT 0;
ALTER TABLE approvals.requests ADD COLUMN step_deadline timestamptz;
ALTER TABLE approvals.requests ADD COLUMN asked jsonb NOT NULL DEFAULT '[]';
ALTER TABLE approvals.requests ADD COLUMN change_request boolean NOT NULL DEFAULT false;
ALTER TABLE approvals.requests ADD COLUMN counted boolean NOT NULL DEFAULT false;
ALTER TABLE approvals.requests ADD COLUMN discarded_because text;
-- +goose Down
ALTER TABLE approvals.requests DROP COLUMN discarded_because;
ALTER TABLE approvals.requests DROP COLUMN counted;
ALTER TABLE approvals.requests DROP COLUMN change_request;
ALTER TABLE approvals.requests DROP COLUMN asked;
ALTER TABLE approvals.requests DROP COLUMN step_deadline;
ALTER TABLE approvals.requests DROP COLUMN step;
UPDATE approvals.requests SET state = 'denied' WHERE state = 'discarded';
ALTER TABLE approvals.requests DROP CONSTRAINT requests_state_check;
ALTER TABLE approvals.requests ADD CONSTRAINT requests_state_check
CHECK (state IN ('pending', 'approved', 'denied', 'expired'));
UPDATE governance.settings s
SET escalation = COALESCE((
SELECT jsonb_agg(e.step ->> 'person' ORDER BY e.n)
FROM jsonb_array_elements(s.escalation) WITH ORDINALITY AS e (step, n)
), '[]'::jsonb);
+84 -27
View File
@@ -96,9 +96,9 @@ type Settings struct {
// DefaultOwner is the id of the person who answers for what has no other
// owner, or empty.
DefaultOwner string
// Escalation is the ids of the people an unanswered request moves through,
// in order.
Escalation []string
// Escalation is the people an unanswered request moves through, in order,
// each with how long the request waits on them.
Escalation []Step
// Timing is when changing actions may run without asking.
Timing Timing
// ActionsPerRun and ActionsPerDay are how many actions one run, and the
@@ -107,32 +107,74 @@ type Settings struct {
ActionsPerDay int
}
// Step is one stop on the escalation path: a person and how long an unanswered
// request waits on them before it moves to the next.
type Step struct {
// Person is the id of the person the request is passed to.
Person string
Deadline time.Duration
}
// stepRow is a step as stored.
type stepRow struct {
Person string `json:"person"`
DeadlineMS int64 `json:"deadline_ms"`
}
// stepRequest is a step as the API shows and sets it. Its deadline travels as
// a Go duration string, like the approval deadline.
type stepRequest struct {
Person string `json:"person"`
Deadline string `json:"deadline"`
}
// settingsRequest is the settings as the API shows and sets them. A duration
// 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 lists person ids.
Escalation []string `json:"escalation"`
Timing Timing `json:"timing"`
ActionsPerRun int `json:"actions_per_run"`
ActionsPerDay int `json:"actions_per_day"`
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"`
}
func (s Settings) request() settingsRequest {
return settingsRequest{
ApprovalDeadline: s.ApprovalDeadline.String(), RaiseAfter: s.RaiseAfter, Frozen: s.Frozen,
RecurrenceThreshold: s.RecurrenceThreshold, AttemptsPerRun: s.AttemptsPerRun,
DefaultOwner: s.DefaultOwner, Escalation: s.Escalation,
DefaultOwner: s.DefaultOwner, Escalation: stepRequests(s.Escalation),
Timing: s.Timing, ActionsPerRun: s.ActionsPerRun, ActionsPerDay: s.ActionsPerDay,
}
}
func stepRequests(steps []Step) []stepRequest {
out := make([]stepRequest, 0, len(steps))
for _, st := range steps {
out = append(out, stepRequest{Person: st.Person, Deadline: st.Deadline.String()})
}
return out
}
// stepsOf reads the steps of a request, each with a deadline inside the range
// an answer can be given in.
func stepsOf(req []stepRequest) ([]Step, error) {
out := make([]Step, 0, len(req))
for _, r := range req {
d, err := time.ParseDuration(r.Deadline)
if err != nil {
return nil, errors.New("each escalation deadline is a duration, such as 4h")
}
out = append(out, Step{Person: r.Person, Deadline: d})
}
return out, nil
}
// Model is the model chosen for a role.
type Model struct {
Class string `json:"class"`
@@ -194,14 +236,18 @@ func (m *Module) Settings(ctx context.Context) (Settings, error) {
return Settings{
ApprovalDeadline: DefaultApprovalDeadline, RaiseAfter: DefaultRaiseAfter,
RecurrenceThreshold: DefaultRecurrenceThreshold, AttemptsPerRun: DefaultAttemptsPerRun,
Escalation: []string{}, Timing: Timing{}.normalised(),
Escalation: []Step{}, Timing: Timing{}.normalised(),
ActionsPerRun: DefaultActionsPerRun, ActionsPerDay: DefaultActionsPerDay,
}, nil
}
escalation := []string{}
if err := json.Unmarshal(jsontext.Value(row.Escalation), &escalation); err != nil {
var rows []stepRow
if err := json.Unmarshal(jsontext.Value(row.Escalation), &rows); err != nil {
return Settings{}, fmt.Errorf("read escalation path: %w", err)
}
escalation := make([]Step, 0, len(rows))
for _, r := range rows {
escalation = append(escalation, Step{Person: r.Person, Deadline: time.Duration(r.DeadlineMS) * time.Millisecond})
}
var timing Timing
if err := json.Unmarshal(jsontext.Value(row.Timing), &timing); err != nil {
return Settings{}, fmt.Errorf("read timing: %w", err)
@@ -296,15 +342,17 @@ func (m *Module) putSettings(w http.ResponseWriter, r *http.Request) {
httpjson.Error(w, http.StatusBadRequest, "approval deadline is a duration, such as 24h")
return
}
steps, err := stepsOf(req.Escalation)
if err != nil {
httpjson.Error(w, http.StatusBadRequest, err.Error())
return
}
set := Settings{
ApprovalDeadline: deadline, RaiseAfter: req.RaiseAfter, Frozen: req.Frozen,
RecurrenceThreshold: req.RecurrenceThreshold, AttemptsPerRun: req.AttemptsPerRun,
DefaultOwner: req.DefaultOwner, Escalation: req.Escalation,
DefaultOwner: req.DefaultOwner, Escalation: steps,
Timing: req.Timing.normalised(), ActionsPerRun: req.ActionsPerRun, ActionsPerDay: req.ActionsPerDay,
}
if set.Escalation == nil {
set.Escalation = []string{}
}
if err := set.validate(); err != nil {
httpjson.Error(w, http.StatusBadRequest, err.Error())
return
@@ -319,7 +367,11 @@ func (m *Module) putSettings(w http.ResponseWriter, r *http.Request) {
httpjson.Error(w, http.StatusBadRequest, err.Error())
return
}
escalation, err := json.Marshal(set.Escalation)
rows := make([]stepRow, 0, len(set.Escalation))
for _, st := range set.Escalation {
rows = append(rows, stepRow{Person: st.Person, DeadlineMS: st.Deadline.Milliseconds()})
}
escalation, err := json.Marshal(rows)
if err != nil {
httpjson.Error(w, http.StatusInternalServerError, "couldn't save the settings")
return
@@ -358,6 +410,11 @@ func (s Settings) validate() error {
if s.AttemptsPerRun < minAttemptsPerRun || s.AttemptsPerRun > maxAttemptsPerRun {
return fmt.Errorf("attempts per run must be between %d and %d", minAttemptsPerRun, maxAttemptsPerRun)
}
for _, st := range s.Escalation {
if st.Deadline < minApprovalDeadline || st.Deadline > maxApprovalDeadline {
return fmt.Errorf("each escalation deadline must be between %s and %s", minApprovalDeadline, maxApprovalDeadline)
}
}
if s.ActionsPerRun < 1 || s.ActionsPerRun > maxActionBudget || s.ActionsPerDay < s.ActionsPerRun || s.ActionsPerDay > maxActionBudget {
return fmt.Errorf("actions per run must be at least 1, and actions per day at least that and at most %d", maxActionBudget)
}
@@ -374,14 +431,14 @@ func (s Settings) knows(people []store.Person) error {
return errors.New("the default owner must be one of the people")
}
seen := map[string]bool{}
for _, id := range s.Escalation {
if !known(id) {
for _, st := range s.Escalation {
if !known(st.Person) {
return errors.New("everyone on the escalation path must be one of the people")
}
if seen[id] {
if seen[st.Person] {
return errors.New("a person can be on the escalation path once")
}
seen[id] = true
seen[st.Person] = true
}
return nil
}
+61
View File
@@ -0,0 +1,61 @@
package governance
import (
"context"
"slices"
"time"
"github.com/samcharles93/archie-core/modules/governance/internal/store"
)
// PathStep is one stop on the route an unanswered approval request takes: who
// it is passed to, and how long it waits there. The first step is the default
// owner, who may be nobody, and anyone with authority.
type PathStep struct {
// Person is the id of the person asked at this step, or empty.
Person string `json:"person"`
Name string `json:"name"`
DeadlineMS int64 `json:"deadline_ms"`
}
// Deadline is how long the request waits at this step.
func (p PathStep) Deadline() time.Duration { return time.Duration(p.DeadlineMS) * time.Millisecond }
// EscalationPath returns the route an approval request takes, with its first
// step the default owner and every later step a person on the escalation path.
// When the action needs authority, a step held by someone without it is left
// out, so the request never moves to a person who could not answer it.
func (m *Module) EscalationPath(ctx context.Context, needAuthority bool) ([]PathStep, error) {
set, err := m.Settings(ctx)
if err != nil {
return nil, err
}
people, err := m.store.People(ctx, m.orgID)
if err != nil {
return nil, err
}
return set.path(people, needAuthority), nil
}
func (s Settings) path(people []store.Person, needAuthority bool) []PathStep {
find := func(id string) (store.Person, bool) {
i := slices.IndexFunc(people, func(p store.Person) bool { return p.ID.String() == id })
if i < 0 {
return store.Person{}, false
}
return people[i], true
}
first := PathStep{Person: s.DefaultOwner, DeadlineMS: s.ApprovalDeadline.Milliseconds()}
if p, ok := find(s.DefaultOwner); ok {
first.Name = p.Name
}
out := []PathStep{first}
for _, st := range s.Escalation {
p, ok := find(st.Person)
if !ok || (needAuthority && !p.Authority) {
continue
}
out = append(out, PathStep{Person: st.Person, Name: p.Name, DeadlineMS: st.Deadline.Milliseconds()})
}
return out
}
+56
View File
@@ -0,0 +1,56 @@
package governance
import (
"slices"
"testing"
"time"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/modules/governance/internal/store"
)
// TestPathNeverDropsBelowTheAuthorityTheActionNeeds guards the escalation
// path: an action that needs authority is never passed to a person without
// it, however the path is set, and every step keeps its own deadline.
func TestPathNeverDropsBelowTheAuthorityTheActionNeeds(t *testing.T) {
owner := store.Person{ID: uuid.New(), Name: "Owner"}
peer := store.Person{ID: uuid.New(), Name: "Peer"}
lead := store.Person{ID: uuid.New(), Name: "Lead", Authority: true}
set := Settings{
ApprovalDeadline: time.Hour, DefaultOwner: owner.ID.String(),
Escalation: []Step{
{Person: peer.ID.String(), Deadline: 2 * time.Hour},
{Person: lead.ID.String(), Deadline: 3 * time.Hour},
},
}
people := []store.Person{owner, peer, lead}
tests := []struct {
name string
needAuthority bool
want []string
wantDeadlines []time.Duration
}{
{
name: "an ordinary action goes through every step", want: []string{"Owner", "Peer", "Lead"},
wantDeadlines: []time.Duration{time.Hour, 2 * time.Hour, 3 * time.Hour},
},
{
name: "an action that needs authority skips a step without it", needAuthority: true,
want: []string{"Owner", "Lead"}, wantDeadlines: []time.Duration{time.Hour, 3 * time.Hour},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var names []string
var deadlines []time.Duration
for _, st := range set.path(people, tt.needAuthority) {
names = append(names, st.Name)
deadlines = append(deadlines, st.Deadline())
}
if !slices.Equal(names, tt.want) || !slices.Equal(deadlines, tt.wantDeadlines) {
t.Fatalf("path = %v %v, want %v %v", names, deadlines, tt.want, tt.wantDeadlines)
}
})
}
}
+5 -2
View File
@@ -16,6 +16,8 @@ import (
// Verified is a person an identity was verified as.
type Verified struct {
// ID is the person's id, as the settings name them.
ID string
Name string
// Authority is whether the person may approve changes to policy and
// ceilings, such as raising an action class.
@@ -38,8 +40,9 @@ func (m *Module) Verify(ctx context.Context, identity string) (Verified, bool, e
return Verified{}, false, err
}
id := p.ID.String()
approver := p.Authority || set.DefaultOwner == id || slices.Contains(set.Escalation, id)
return Verified{Name: p.Name, Authority: p.Authority, Approver: approver}, true, nil
onPath := slices.ContainsFunc(set.Escalation, func(st Step) bool { return st.Person == id })
approver := p.Authority || set.DefaultOwner == id || onPath
return Verified{ID: id, Name: p.Name, Authority: p.Authority, Approver: approver}, true, nil
}
// personRequest is a person as the API shows and sets them. An empty id is a
+10 -9
View File
@@ -12,7 +12,7 @@ import { SettingRow } from "@/components/ui/setting-row";
import { Spinner } from "@/components/ui/spinner";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { getPeople, getSettings, saveSettings, Unauthorized, type Blackout, type Person } from "./api";
import { getPeople, getSettings, saveSettings, Unauthorized, type Blackout, type EscalationStep, type Person } from "./api";
/**
* Organisation settings: what Archie does when nobody has decided otherwise.
@@ -42,7 +42,7 @@ const blackouts = ref<BlackoutRow[]>([]);
const people = ref<Person[]>([]);
const none = "none";
const owner = ref(none);
const escalation = ref<string[]>([]);
const escalation = ref<EscalationStep[]>([]);
const saved = ref("");
const loading = ref(true);
const saving = ref(false);
@@ -123,7 +123,7 @@ function toggleDay(day: string) {
days.value = days.value.includes(day) ? days.value.filter((d) => d !== day) : [...days.value, day];
}
const addable = () => people.value.filter((p) => !escalation.value.includes(p.id));
const addable = () => people.value.filter((p) => !escalation.value.some((st) => st.person === p.id));
const nameOf = (id: string) => people.value.find((p) => p.id === id)?.name ?? id;
function move(index: number, by: number) {
@@ -153,7 +153,7 @@ onBeforeUnmount(() => controller.abort());
<DurationInput id="approval-deadline" v-model="deadline" />
</SettingRow>
<p class="text-caption text-muted-foreground">
How long an approval request waits for an answer. Nothing runs when it expires.
How long a request waits on the default owner before it moves to the first person on the escalation path.
</p>
<SettingRow label="Approvals to propose a raise" for="raise-after">
<NumberField v-model="raiseAfter" :min="1" :max="100" class="w-32">
@@ -256,13 +256,14 @@ onBeforeUnmount(() => controller.abort());
</SettingRow>
<SettingRow label="Escalation path">
<div class="flex flex-col gap-2">
<div v-for="(id, index) in escalation" :key="id" class="flex items-center gap-2">
<span class="text-label">{{ index + 1 }}. {{ nameOf(id) }}</span>
<div v-for="(step, index) in escalation" :key="step.person" class="flex items-center gap-2">
<span class="text-label">{{ index + 1 }}. {{ nameOf(step.person) }}</span>
<DurationInput v-model="step.deadline" />
<Button variant="ghost" size="xs" :disabled="index === 0" aria-label="Move up" @click="move(index, -1)">Up</Button>
<Button variant="ghost" size="xs" :disabled="index === escalation.length - 1" aria-label="Move down" @click="move(index, 1)">Down</Button>
<Button variant="ghost" size="xs" @click="escalation = escalation.filter((x) => x !== id)">Remove</Button>
<Button variant="ghost" size="xs" @click="escalation = escalation.filter((x) => x.person !== step.person)">Remove</Button>
</div>
<Select v-if="addable().length" model-value="" @update:model-value="(id) => escalation.push(String(id))">
<Select v-if="addable().length" model-value="" @update:model-value="(id) => escalation.push({ person: String(id), deadline: deadline })">
<SelectTrigger class="w-64" aria-label="Add to escalation path"><SelectValue placeholder="Add person" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="p in addable()" :key="p.id" :value="p.id">{{ p.name }}</SelectItem>
@@ -271,7 +272,7 @@ onBeforeUnmount(() => controller.abort());
</div>
</SettingRow>
<p class="text-caption text-muted-foreground">
The default owner, the people on the path and anyone with authority may answer approvals.
A request goes to the default owner first. When a step's deadline passes unanswered it moves to the next person, and when the last one passes nothing runs. People on the path answer once it reaches them; an action that needs authority skips anyone without it.
</p>
<SettingRow label="Freeze" for="frozen" tone="danger">
<Switch id="frozen" v-model="frozen" aria-label="Freeze" />
+9 -2
View File
@@ -152,8 +152,8 @@ export interface Settings {
attempts_per_run: number;
/** Person id, or empty. */
default_owner: string;
/** Person ids, in the order an unanswered request moves through them. */
escalation: string[];
/** The people an unanswered request moves through, in order, each with how long it waits on them. */
escalation: EscalationStep[];
/** When actions that change something may run without asking. */
timing: Timing;
/** Changing actions one run may take before the next waits for approval. */
@@ -180,6 +180,13 @@ export interface Blackout {
reason: string;
}
export interface EscalationStep {
/** Person id. */
person: string;
/** A Go duration, such as "4h". */
deadline: string;
}
export const getSettings = (signal?: AbortSignal) => get<Settings>("/api/settings", signal);
export interface Person {