feat(judgement): the weakest-link decision, and executing only what was judged (#1986, #1989, #1990, #1988)

A new judgement module assesses one concrete action: hard rules refuse before
any guard runs; every guard sets a ceiling and the action runs at the lowest;
a guard that fails, panics or gives no ceiling holds it at propose and wait;
an advisory verdict is recorded and sets no ceiling. Reversibility and
Precedent (the fresh-install class default) are the first guards. Every
decision is recorded with its verdicts and class, and the run's trail lists
them. Agent tools now offer connector actions too: each call is assessed and
executed only as decided and only with the judged input, and a held action
comes back to the agent as a failed call naming its level and findings.
Tools gain Resolve, so an MCP server's declared effect reaches judgement.
This commit is contained in:
sam committed 2026-11-16 01:05:29 +11:00
1 parent af753290e7
commit 0dbf241106
11 files changed
+760 -34

No files matched your search

+6 -3
View File
@@ -27,6 +27,7 @@ import (
"github.com/samcharles93/archie-core/modules/deliveries"
"github.com/samcharles93/archie-core/modules/events"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement"
"github.com/samcharles93/archie-core/modules/runs"
"github.com/samcharles93/archie-core/ui"
)
@@ -81,11 +82,13 @@ func Run(ctx context.Context, configPath string) error {
engine := runs.New(db, log.With("module", "runs"), runs.Options{Owner: owner()})
// A workflow takes its context from the run handle, as a handler takes it
// from the request.
engine.Register("investigate", runs.Investigate(settings, conns, tell)) //nolint:contextcheck // see above
judge := judgement.NewModule(db, log.With("module", "judgement"), orgID, conns, nil,
[]judgement.Guard{judgement.Reversibility{}, judgement.Precedent{}})
engine.Register("investigate", runs.Investigate(settings, conns, judge, tell)) //nolint:contextcheck // see above
hear := events.NewModule(db, log.With("module", "events"), orgID, conns, engine)
hear.Routes(mux, guard)
engine.Routes(mux, guard, orgID, hear)
engine.Routes(mux, guard, orgID, hear, judge)
dashboard.Routes(mux, ui.DistDirFS)
ctx, stop := context.WithCancel(ctx)
@@ -104,7 +107,7 @@ func Run(ctx context.Context, configPath string) error {
const orgID = "default"
// schemas are the module schemas the runtime role is granted DML on.
var schemas = []string{"runs", "connectors", "events", "governance", "deliveries"}
var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement"}
// owner names this process in run leases.
func owner() string {
@@ -0,0 +1,27 @@
-- +goose Up
CREATE SCHEMA judgement;
-- A decision is the judgement of one concrete action, with every verdict in
-- its body. key identifies the attempt to run it, so a replayed step finds the
-- decision already made. The class columns are what earned autonomy is
-- counted against.
CREATE TABLE judgement.decisions (
id uuid PRIMARY KEY,
org_id text NOT NULL,
run_id uuid NOT NULL,
key text NOT NULL,
connector text NOT NULL,
action text NOT NULL,
target_kind text NOT NULL,
environment text NOT NULL,
level text NOT NULL CHECK (level IN ('act_quietly', 'act_and_tell', 'propose_and_wait', 'escalate', 'never')),
body json NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (org_id, key)
);
CREATE INDEX decisions_by_run ON judgement.decisions (org_id, run_id, created_at);
CREATE INDEX decisions_by_class ON judgement.decisions (org_id, connector, action, target_kind, environment, created_at);
-- +goose Down
DROP SCHEMA judgement CASCADE;
+3
View File
@@ -120,6 +120,9 @@ type Tool interface {
Lookup(ctx context.Context, name string, input jsontext.Value) (output string, found bool, err error)
// Invoke runs one judged action.
Invoke(ctx context.Context, inv Invocation) (output string, err error)
// Resolve works out one concrete action's target and effect, for
// judgement before it runs.
Resolve(ctx context.Context, name string, input jsontext.Value) (Resolution, error)
}
// Connector is a running connector and what it declared.
+16 -2
View File
@@ -145,8 +145,22 @@ func (s *Server) Lookup(ctx context.Context, name string, input jsontext.Value)
return s.call(ctx, name, KindLookup, input)
}
// Invoke calls one declared action and returns the result verbatim. Nothing
// judges an action yet, so a declared one is never offered.
// Resolve returns a declared action's effect as its acceptance states it. An
// MCP server can't name the target an action touches, so the target is left
// unknown, which judgement treats as missing evidence.
func (s *Server) Resolve(_ context.Context, name string, input jsontext.Value) (Resolution, error) {
t, err := s.tool(name, KindAction)
if err != nil {
return Resolution{}, err
}
if err := validate(t.input, input); err != nil {
return Resolution{}, fmt.Errorf("mcp server %q: tool %q: %w", s.name, name, err)
}
return Resolution{Effect: t.effect}, nil
}
// Invoke calls one declared action and returns the result verbatim. It runs
// only what judgement allowed.
func (s *Server) Invoke(ctx context.Context, inv Invocation) (string, error) {
out, _, err := s.call(ctx, inv.Action, KindAction, inv.Input)
return out, err
+53
View File
@@ -0,0 +1,53 @@
package judgement
import (
"context"
"errors"
"github.com/samcharles93/archie-core/modules/connectors"
)
// Reversibility sets a ceiling from whether the action can be undone, as the
// connector declares it.
type Reversibility struct{}
// Name is the guard's name in verdicts.
func (Reversibility) Name() string { return "reversibility" }
// Advisory is false: the declaration is data, not a model's opinion.
func (Reversibility) Advisory() bool { return false }
// Judge maps the declared reversibility to a ceiling. An action that declares
// none lacks the evidence this guard needs.
func (Reversibility) Judge(_ context.Context, a Action) (Verdict, error) {
switch {
case a.Effect.ReadOnly:
return Verdict{Ceiling: ActQuietly}, nil
case a.Effect.Reversibility == connectors.UndoneAutomatically:
return Verdict{Ceiling: ActQuietly, Findings: []Finding{{Text: "undone automatically"}}}, nil
case a.Effect.Reversibility == connectors.Recoverable || a.Target.Disposable:
return Verdict{Ceiling: ActAndTell, Findings: []Finding{{Text: "recoverable, or the target is disposable"}}}, nil
case a.Effect.Reversibility == connectors.Irreversible:
return Verdict{Ceiling: ProposeAndWait, Findings: []Finding{{Text: "irreversible"}}}, nil
}
return Verdict{}, errors.New("the connector declares no reversibility for this action")
}
// Precedent sets a ceiling from the action class's earned level. Until a
// class has history, it is the fresh-install default: read-only classes act
// quietly, every other class proposes and waits.
type Precedent struct{}
// Name is the guard's name in verdicts.
func (Precedent) Name() string { return "precedent" }
// Advisory is false.
func (Precedent) Advisory() bool { return false }
// Judge returns the class's level.
func (Precedent) Judge(_ context.Context, a Action) (Verdict, error) {
if a.Effect.ReadOnly {
return Verdict{Ceiling: ActQuietly}, nil
}
return Verdict{Ceiling: ProposeAndWait, Findings: []Finding{{Text: "this action class has no approvals yet"}}}, nil
}
+68
View File
@@ -0,0 +1,68 @@
// Package store holds the judgement module's SQL: every decision, with the
// action class it belongs to.
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// Decision is one recorded decision. Body is the whole decision as JSON.
type Decision struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
RunID uuid.UUID `db:"run_id"`
Key string `db:"key"`
Connector string `db:"connector"`
Action string `db:"action"`
TargetKind string `db:"target_kind"`
Environment string `db:"environment"`
Level string `db:"level"`
Body []byte `db:"body"`
}
// Store is the judgement module's Postgres store.
type Store struct {
db *sqlx.DB
}
// New returns a store on db.
func New(db *sqlx.DB) *Store { return &Store{db: db} }
// Record stores d unless a decision with its key exists, and returns the
// decision that is kept.
func (s *Store) Record(ctx context.Context, d Decision) (Decision, error) {
var kept Decision
err := s.db.GetContext(ctx, &kept, `
INSERT INTO judgement.decisions
(id, org_id, run_id, key, connector, action, target_kind, environment, level, body)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT (org_id, key) DO NOTHING
RETURNING id, org_id, run_id, key, connector, action, target_kind, environment, level, body`,
d.ID, d.OrgID, d.RunID, d.Key, d.Connector, d.Action, d.TargetKind, d.Environment, d.Level, d.Body)
if errors.Is(err, sql.ErrNoRows) {
err = s.db.GetContext(ctx, &kept, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body
FROM judgement.decisions WHERE org_id = $1 AND key = $2`, d.OrgID, d.Key)
}
if err != nil {
return Decision{}, fmt.Errorf("record decision: %w", err)
}
return kept, nil
}
// ForRun returns a run's decisions in the order they were made.
func (s *Store) ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]Decision, error) {
var out []Decision
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, run_id, key, connector, action, target_kind, environment, level, body
FROM judgement.decisions WHERE org_id = $1 AND run_id = $2 ORDER BY created_at, id`, orgID, runID); err != nil {
return nil, fmt.Errorf("list decisions: %w", err)
}
return out, nil
}
+275
View File
@@ -0,0 +1,275 @@
// Package judgement decides whether a concrete action runs, and runs only the
// action it judged. Hard rules refuse first; every guard then sets a ceiling,
// and the action runs at the lowest one. Each decision is recorded with every
// verdict, so the run's trail and the action class's history can read it.
package judgement
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
"sync"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/judgement/internal/store"
)
// guardTimeout bounds one guard, so a slow guard holds an action no longer.
const guardTimeout = 10 * time.Second
var (
// ErrRefused means a hard rule refused the action.
ErrRefused = errors.New("refused by a hard rule")
// ErrHeld means the action's level needs someone's approval first.
ErrHeld = errors.New("held for approval")
// ErrAltered means the action to run isn't the one that was judged.
ErrAltered = errors.New("action differs from the one judged")
)
// Action is one concrete action: the exact operation on the exact target.
type Action struct {
Connector string `json:"connector"`
Name string `json:"name"`
Input jsontext.Value `json:"input"`
Digest string `json:"digest"`
Target connectors.Target `json:"target"`
Effect connectors.Effect `json:"effect"`
}
// Class is what an action's earned autonomy belongs to.
type Class struct {
Connector string `json:"connector"`
Action string `json:"action"`
TargetKind string `json:"target_kind"`
Environment string `json:"environment"`
}
// Class returns the action's class.
func (a Action) Class() Class {
return Class{Connector: a.Connector, Action: a.Name, TargetKind: a.Target.Kind, Environment: a.Target.Environment}
}
// Finding is one thing a guard noticed, with what it rests on.
type Finding struct {
Text string `json:"text"`
Evidence string `json:"evidence,omitzero"`
}
// Verdict is one guard's judgement of one action.
type Verdict struct {
Guard string `json:"guard"`
Ceiling Level `json:"ceiling"`
Findings []Finding `json:"findings,omitzero"`
BlindSpots []string `json:"blind_spots,omitzero"`
// Advisory verdicts are recorded and set no ceiling.
Advisory bool `json:"advisory,omitzero"`
// Failed says why the guard couldn't answer; its ceiling is then
// propose and wait.
Failed string `json:"failed,omitzero"`
}
// Guard judges one concrete action.
type Guard interface {
Name() string
// Advisory guards are recorded but set no ceiling.
Advisory() bool
// Judge returns the guard's verdict. An error, a timeout or a verdict
// with no ceiling holds the action at propose and wait.
Judge(ctx context.Context, a Action) (Verdict, error)
}
// HardRule refuses actions outright. Hard rules run before any guard.
type HardRule interface {
Name() string
// Refuses reports whether the rule forbids the action, and why.
Refuses(a Action) (reason string, refused bool)
}
// Decision is the judgement of one action.
type Decision struct {
ID uuid.UUID `json:"id"`
RunID uuid.UUID `json:"run_id"`
Key string `json:"key"`
Action Action `json:"action"`
Level Level `json:"level"`
Verdicts []Verdict `json:"verdicts"`
// RefusedBy names the hard rule that refused the action, if one did.
RefusedBy string `json:"refused_by,omitzero"`
Reason string `json:"reason,omitzero"`
At time.Time `json:"at"`
}
// Request asks for one action to be judged. Key identifies the attempt to run
// it: the same key is the same decision, so a replayed step never judges
// twice.
type Request struct {
RunID uuid.UUID
Key string
Connector string
Action string
Input jsontext.Value
}
// Tools finds the tool that resolves and runs an action.
type Tools interface {
Tool(name string) (connectors.Tool, bool)
}
type recorder interface {
Record(ctx context.Context, d store.Decision) (store.Decision, error)
ForRun(ctx context.Context, orgID string, runID uuid.UUID) ([]store.Decision, error)
}
// Module judges one organisation's actions.
type Module struct {
orgID string
tools Tools
rules []HardRule
guards []Guard
store recorder
log *slog.Logger
now func() time.Time
}
// NewModule returns the judgement module for orgID, with its hard rules and
// guards.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tools Tools, rules []HardRule, guards []Guard) *Module {
return &Module{orgID: orgID, tools: tools, rules: rules, guards: guards, store: store.New(db), log: log, now: time.Now}
}
// Assess judges one action and records the decision. Judging the same key
// again returns the recorded decision.
func (m *Module) Assess(ctx context.Context, req Request) (Decision, error) {
tool, ok := m.tools.Tool(req.Connector)
if !ok {
return Decision{}, fmt.Errorf("%q isn't running", req.Connector)
}
res, err := tool.Resolve(ctx, req.Action, req.Input)
if err != nil {
return Decision{}, fmt.Errorf("resolve %s %s: %w", req.Connector, req.Action, err)
}
a := Action{
Connector: req.Connector, Name: req.Action, Input: req.Input,
Digest: connectors.Digest(req.Action, req.Input), Target: res.Target, Effect: res.Effect,
}
d := m.decide(ctx, a)
d.ID, d.RunID, d.Key, d.At = uuid.New(), req.RunID, req.Key, m.now().UTC()
return m.record(ctx, d)
}
// decide runs the hard rules, then every guard in parallel, and folds their
// ceilings: the action runs at the lowest.
func (m *Module) decide(ctx context.Context, a Action) Decision {
for _, r := range m.rules {
if reason, refused := r.Refuses(a); refused {
return Decision{Action: a, Level: Never, RefusedBy: r.Name(), Reason: reason, Verdicts: []Verdict{}}
}
}
verdicts := make([]Verdict, len(m.guards))
var wg sync.WaitGroup
for i, g := range m.guards {
wg.Go(func() { verdicts[i] = judge(ctx, g, a) })
}
wg.Wait()
ceilings := []Level{}
for _, v := range verdicts {
if !v.Advisory {
ceilings = append(ceilings, v.Ceiling)
}
}
level := ProposeAndWait
if len(ceilings) > 0 {
level = lowest(ceilings...)
}
return Decision{Action: a, Level: level, Verdicts: verdicts}
}
// judge asks one guard, turning a failure, a timeout or a missing ceiling
// into propose and wait. A panic is a failure too.
func judge(ctx context.Context, g Guard, a Action) (v Verdict) {
ctx, cancel := context.WithTimeout(ctx, guardTimeout)
defer cancel()
failed := func(why string) Verdict {
return Verdict{Guard: g.Name(), Ceiling: ProposeAndWait, Advisory: g.Advisory(), Failed: why}
}
defer func() {
if r := recover(); r != nil {
v = failed(fmt.Sprintf("panicked: %v", r))
}
}()
got, err := g.Judge(ctx, a)
switch {
case err != nil:
return failed(err.Error())
case got.Ceiling < ActQuietly || got.Ceiling > Never:
return failed("returned no ceiling")
}
got.Guard, got.Advisory = g.Name(), g.Advisory()
return got
}
// Execute runs a decided action if its level lets it run and the input is
// exactly the one judged. key is the idempotency key the connector honours.
func (m *Module) Execute(ctx context.Context, d Decision, input jsontext.Value, key string) (string, error) {
switch {
case d.Level == Never:
return "", fmt.Errorf("%w: %s: %s", ErrRefused, d.RefusedBy, d.Reason)
case !d.Level.Runs():
return "", fmt.Errorf("%w at %s", ErrHeld, d.Level)
case connectors.Digest(d.Action.Name, input) != d.Action.Digest:
return "", ErrAltered
}
tool, ok := m.tools.Tool(d.Action.Connector)
if !ok {
return "", fmt.Errorf("%q isn't running", d.Action.Connector)
}
return tool.Invoke(ctx, connectors.Invocation{Action: d.Action.Name, Input: input, IdempotencyKey: key})
}
// ForRun returns a run's decisions in the order they were made.
func (m *Module) ForRun(ctx context.Context, runID uuid.UUID) ([]Decision, error) {
rows, err := m.store.ForRun(ctx, m.orgID, runID)
if err != nil {
return nil, err
}
out := make([]Decision, 0, len(rows))
for _, r := range rows {
var d Decision
if err := json.Unmarshal(r.Body, &d); err != nil {
return nil, fmt.Errorf("decision %s: %w", r.ID, err)
}
out = append(out, d)
}
return out, nil
}
func (m *Module) record(ctx context.Context, d Decision) (Decision, error) {
body, err := json.Marshal(d)
if err != nil {
return Decision{}, fmt.Errorf("encode decision: %w", err)
}
c := d.Action.Class()
row, err := m.store.Record(ctx, store.Decision{
ID: d.ID, OrgID: m.orgID, RunID: d.RunID, Key: d.Key,
Connector: c.Connector, Action: c.Action, TargetKind: c.TargetKind, Environment: c.Environment,
Level: d.Level.String(), Body: body,
})
if err != nil {
return Decision{}, err
}
if row.ID == d.ID {
return d, nil
}
var kept Decision
if err := json.Unmarshal(row.Body, &kept); err != nil {
return Decision{}, fmt.Errorf("decision %s: %w", row.ID, err)
}
return kept, nil
}
+182
View File
@@ -0,0 +1,182 @@
package judgement
import (
"context"
"encoding/json/jsontext"
"errors"
"sync/atomic"
"testing"
"github.com/samcharles93/archie-core/modules/connectors"
)
type fixedGuard struct {
name string
ceiling Level
err error
advisory bool
panics bool
calls *atomic.Int32
}
func (g fixedGuard) Name() string { return g.name }
func (g fixedGuard) Advisory() bool { return g.advisory }
func (g fixedGuard) Judge(context.Context, Action) (Verdict, error) {
if g.calls != nil {
g.calls.Add(1)
}
if g.panics {
panic("guard bug")
}
return Verdict{Ceiling: g.ceiling}, g.err
}
type refuseAll struct{}
func (refuseAll) Name() string { return "no deletes in production" }
func (refuseAll) Refuses(Action) (string, bool) { return "production is off limits", true }
// TestDecisionRunsAtTheLowestCeiling guards the weakest-link decision (spec
// section 5, decision tree 8.3): hard rules refuse before any guard runs; the
// action runs at the lowest ceiling; a guard that fails, panics or gives no
// ceiling holds the action at propose and wait; an advisory verdict is
// recorded but sets no ceiling.
func TestDecisionRunsAtTheLowestCeiling(t *testing.T) {
tests := []struct {
name string
rules []HardRule
guards []Guard
want Level
wantCalls int32
}{
{
name: "the lower of two ceilings wins",
guards: []Guard{fixedGuard{name: "a", ceiling: ActAndTell}, fixedGuard{name: "b", ceiling: ProposeAndWait}},
want: ProposeAndWait,
},
{
name: "guards with no concern act quietly",
guards: []Guard{fixedGuard{name: "a", ceiling: ActQuietly}, fixedGuard{name: "b", ceiling: ActQuietly}},
want: ActQuietly,
},
{
name: "a failing guard holds the action",
guards: []Guard{fixedGuard{name: "a", ceiling: ActQuietly}, fixedGuard{name: "b", err: errors.New("no evidence")}},
want: ProposeAndWait,
},
{
name: "a panicking guard holds the action",
guards: []Guard{fixedGuard{name: "a", ceiling: ActQuietly}, fixedGuard{name: "b", panics: true}},
want: ProposeAndWait,
},
{
name: "a guard without a ceiling holds the action",
guards: []Guard{fixedGuard{name: "a", ceiling: ActQuietly}, fixedGuard{name: "b"}},
want: ProposeAndWait,
},
{
name: "an advisory verdict sets no ceiling",
guards: []Guard{fixedGuard{name: "a", ceiling: ActQuietly}, fixedGuard{name: "judge", ceiling: Never, advisory: true}},
want: ActQuietly,
},
{
name: "a failing advisory guard sets no ceiling",
guards: []Guard{fixedGuard{name: "a", ceiling: ActAndTell}, fixedGuard{name: "judge", err: errors.New("timeout"), advisory: true}},
want: ActAndTell,
},
{
name: "no guards at all holds the action",
want: ProposeAndWait,
},
{
name: "a hard rule refuses before any guard runs",
rules: []HardRule{refuseAll{}},
guards: []Guard{fixedGuard{name: "a", ceiling: ActQuietly}},
want: Never,
wantCalls: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var calls atomic.Int32
for i, g := range tt.guards {
if f, ok := g.(fixedGuard); ok {
f.calls = &calls
tt.guards[i] = f
}
}
m := &Module{rules: tt.rules, guards: tt.guards}
d := m.decide(t.Context(), Action{Connector: "c", Name: "delete"})
if d.Level != tt.want {
t.Fatalf("level = %s, want %s (verdicts %+v)", d.Level, tt.want, d.Verdicts)
}
if len(d.Verdicts) != len(tt.guards) && tt.want != Never {
t.Fatalf("verdicts = %d, want one per guard (%d)", len(d.Verdicts), len(tt.guards))
}
if tt.rules != nil && calls.Load() != tt.wantCalls {
t.Fatalf("guards ran %d times, want %d", calls.Load(), tt.wantCalls)
}
})
}
}
type countingTool struct{ invoked *atomic.Int32 }
func (t countingTool) Lookup(context.Context, string, jsontext.Value) (string, bool, error) {
return "", false, nil
}
func (t countingTool) Invoke(context.Context, connectors.Invocation) (string, error) {
t.invoked.Add(1)
return "done", nil
}
func (t countingTool) Resolve(context.Context, string, jsontext.Value) (connectors.Resolution, error) {
return connectors.Resolution{}, nil
}
type oneTool struct{ tool connectors.Tool }
func (o oneTool) Tool(string) (connectors.Tool, bool) { return o.tool, true }
// TestExecuteRunsOnlyTheJudgedAction guards spec section 5 rule 6 and
// decision tree 8.5: an action runs only at a level that runs without
// approval, and only with exactly the input that was judged. A refused, held
// or altered action never reaches the connector.
func TestExecuteRunsOnlyTheJudgedAction(t *testing.T) {
judged := jsontext.Value(`{"path":"/tmp/runner"}`)
decided := func(l Level) Decision {
return Decision{Level: l, Action: Action{Connector: "c", Name: "delete", Input: judged, Digest: connectors.Digest("delete", judged)}}
}
tests := []struct {
name string
d Decision
input jsontext.Value
wantErr error
}{
{name: "act quietly runs", d: decided(ActQuietly), input: judged},
{name: "act and tell runs", d: decided(ActAndTell), input: judged},
{name: "propose and wait is held", d: decided(ProposeAndWait), input: judged, wantErr: ErrHeld},
{name: "escalate is held", d: decided(Escalate), input: judged, wantErr: ErrHeld},
{name: "never is refused", d: decided(Never), input: judged, wantErr: ErrRefused},
{name: "altered input is refused", d: decided(ActQuietly), input: jsontext.Value(`{"path":"/"}`), wantErr: ErrAltered},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var invoked atomic.Int32
m := &Module{tools: oneTool{countingTool{&invoked}}}
_, err := m.Execute(t.Context(), tt.d, tt.input, "run:1")
if !errors.Is(err, tt.wantErr) {
t.Fatalf("err = %v, want %v", err, tt.wantErr)
}
want := int32(1)
if tt.wantErr != nil {
want = 0
}
if invoked.Load() != want {
t.Fatalf("connector invoked %d times, want %d", invoked.Load(), want)
}
})
}
}
+63
View File
@@ -0,0 +1,63 @@
package judgement
import "fmt"
// Level is how much autonomy an action runs with, from the most (act
// quietly) to the least (never). A higher value means less autonomy.
type Level int
// The five levels, in order of decreasing autonomy.
const (
ActQuietly Level = iota + 1
ActAndTell
ProposeAndWait
Escalate
Never
)
var levelNames = [...]string{
ActQuietly: "act_quietly",
ActAndTell: "act_and_tell",
ProposeAndWait: "propose_and_wait",
Escalate: "escalate",
Never: "never",
}
func (l Level) String() string {
if l < ActQuietly || l > Never {
return fmt.Sprintf("level(%d)", int(l))
}
return levelNames[l]
}
// MarshalText writes the level's name.
func (l Level) MarshalText() ([]byte, error) {
if l < ActQuietly || l > Never {
return nil, fmt.Errorf("no level %d", int(l))
}
return []byte(levelNames[l]), nil
}
// UnmarshalText reads a level's name.
func (l *Level) UnmarshalText(b []byte) error {
for i, name := range levelNames {
if name != "" && name == string(b) {
*l = Level(i)
return nil
}
}
return fmt.Errorf("no level named %q", b)
}
// Runs reports whether an action at this level runs without waiting for
// anyone.
func (l Level) Runs() bool { return l == ActQuietly || l == ActAndTell }
// lowest is the level with the least autonomy among levels.
func lowest(levels ...Level) Level {
out := ActQuietly
for _, l := range levels {
out = max(out, l)
}
return out
}
+46 -21
View File
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"regexp"
"strings"
"time"
"github.com/google/uuid"
@@ -17,6 +18,7 @@ import (
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/deliveries"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/judgement"
)
// AgentModels is where a workflow finds the organisation's agent model.
@@ -31,6 +33,13 @@ type Toolbox interface {
Tool(name string) (connectors.Tool, bool)
}
// Judge decides whether an agent's action runs, and runs only what it
// decided.
type Judge interface {
Assess(ctx context.Context, req judgement.Request) (judgement.Decision, error)
Execute(ctx context.Context, d judgement.Decision, input jsontext.Value, key string) (string, error)
}
// Notifier tells people what a run found.
type Notifier interface {
Notify(ctx context.Context, n deliveries.Notification) error
@@ -44,7 +53,7 @@ var investigateBudget = agentloop.Budget{MaxSteps: 20, MaxTokens: 200_000, WallC
// started the run and report its findings. The agent model and the tools are
// pinned in the run's first steps, so a resumed run asks the same model with
// the same tools even if settings or connectors changed meanwhile.
func Investigate(models AgentModels, box Toolbox, notify Notifier) Workflow {
func Investigate(models AgentModels, box Toolbox, judge Judge, notify Notifier) Workflow {
return func(rc *Context, input jsontext.Value) (jsontext.Value, error) {
model, err := rc.Step("agent-model", func(ctx context.Context, _ string) (governance.Model, error) {
return models.AgentModel(ctx)
@@ -53,7 +62,7 @@ func Investigate(models AgentModels, box Toolbox, notify Notifier) Workflow {
return nil, err
}
decls, err := rc.Step("agent-tools", func(context.Context, string) ([]connectors.Declaration, error) {
return offered(box.Declarations()), nil
return box.Declarations(), nil
})
if err != nil {
return nil, err
@@ -69,7 +78,7 @@ func Investigate(models AgentModels, box Toolbox, notify Notifier) Workflow {
ModelInfo: info,
System: prompts.Investigate(),
Prompt: string(input),
Tools: toolSet(box, decls),
Tools: toolSet(box, judge, rc.RunID(), decls),
Budget: investigateBudget,
})
if err != nil {
@@ -101,25 +110,13 @@ func findings(runID uuid.UUID, key string, res AgentResult) deliveries.Notificat
return n
}
// offered keeps what an agent may call before judgement exists: lookups,
// which change nothing, and read-only actions.
func offered(all []connectors.Declaration) []connectors.Declaration {
var out []connectors.Declaration
for _, d := range all {
if d.ReadOnly {
out = append(out, d)
}
}
return out
}
// unsafeToolChars are those a model API refuses in a tool name.
var unsafeToolChars = regexp.MustCompile(`[^a-zA-Z0-9_-]`)
// toolSet turns pinned declarations into the agent's tools. Each tool calls
// its connector or MCP server by name when the model asks, so one that has
// since stopped fails that call rather than the run.
func toolSet(box Toolbox, decls []connectors.Declaration) core.ToolSet {
func toolSet(box Toolbox, judge Judge, runID uuid.UUID, decls []connectors.Declaration) core.ToolSet {
set := core.ToolSet{}
for _, d := range decls {
name := unsafeToolChars.ReplaceAllString(d.Connector+"_"+d.Name, "_")
@@ -128,14 +125,14 @@ func toolSet(box Toolbox, decls []connectors.Declaration) core.ToolSet {
Description: d.Description,
Parameters: []byte(d.Schema),
Execute: func(ctx context.Context, input string) (string, error) {
return call(ctx, box, d, jsontext.Value(input))
return call(ctx, box, judge, runID, d, jsontext.Value(input))
},
}
}
return set
}
func call(ctx context.Context, box Toolbox, d connectors.Declaration, input jsontext.Value) (string, error) {
func call(ctx context.Context, box Toolbox, judge Judge, runID uuid.UUID, d connectors.Declaration, input jsontext.Value) (string, error) {
tool, ok := box.Tool(d.Connector)
if !ok {
return "", fmt.Errorf("%q isn't running", d.Connector)
@@ -150,9 +147,17 @@ func call(ctx context.Context, box Toolbox, d connectors.Declaration, input json
}
return out, nil
}
out, err := tool.Invoke(ctx, connectors.Invocation{
Action: d.Name, Input: input, IdempotencyKey: core.IdempotencyKey(ctx),
})
// An action is judged first and runs only as decided. A held one comes
// back to the agent as a failed call naming the level and the findings.
key := core.IdempotencyKey(ctx)
decision, err := judge.Assess(ctx, judgement.Request{RunID: runID, Key: key, Connector: d.Connector, Action: d.Name, Input: input})
if err != nil {
return "", err
}
out, err := judge.Execute(ctx, decision, input, key)
if errors.Is(err, judgement.ErrHeld) {
return "", fmt.Errorf("%w: %s; approvals aren't available yet, so propose it in your findings instead", err, findingsOf(decision))
}
if errors.Is(err, connectors.ErrOutcomeUnknown) {
return "", fmt.Errorf("%w: %w", core.ErrOutcomeUnknown, err)
}
@@ -161,3 +166,23 @@ func call(ctx context.Context, box Toolbox, d connectors.Declaration, input json
}
return out, nil
}
// findingsOf lists what held a decision back, for the agent.
func findingsOf(d judgement.Decision) string {
var parts []string
for _, v := range d.Verdicts {
if v.Advisory || v.Ceiling != d.Level {
continue
}
for _, f := range v.Findings {
parts = append(parts, v.Guard+": "+f.Text)
}
if v.Failed != "" {
parts = append(parts, v.Guard+" couldn't judge: "+v.Failed)
}
}
if len(parts) == 0 {
return "no guard allowed it to run unattended"
}
return strings.Join(parts, "; ")
}
+21 -8
View File
@@ -14,6 +14,7 @@ import (
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/archie-core/internal/platform/httpjson"
"github.com/samcharles93/archie-core/modules/judgement"
"github.com/samcharles93/archie-core/modules/runs/internal/store"
)
@@ -49,9 +50,11 @@ type RunView struct {
// Trail is a run's decision trail: what started it and every step it took,
// in order.
type Trail struct {
Run RunView `json:"run"`
Origin *Origin `json:"origin,omitzero"`
Entries []TrailEntry `json:"entries"`
Run RunView `json:"run"`
Origin *Origin `json:"origin,omitzero"`
// Decisions are the judgements of the run's actions, with every verdict.
Decisions []judgement.Decision `json:"decisions"`
Entries []TrailEntry `json:"entries"`
}
// TrailEntry is one recorded step. Kind is "model" or "compaction" for an
@@ -79,17 +82,23 @@ type ToolCallView struct {
Input string `json:"input"`
}
// Decisions finds the judgements made in a run.
type Decisions interface {
ForRun(ctx context.Context, runID uuid.UUID) ([]judgement.Decision, error)
}
// Routes adds the run API for orgID to mux behind guard.
func (e *Engine) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler, orgID string, origins Origins) {
api := &runAPI{db: e.db, orgID: orgID, origins: origins}
func (e *Engine) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler, orgID string, origins Origins, decisions Decisions) {
api := &runAPI{db: e.db, orgID: orgID, origins: origins, decisions: decisions}
mux.Handle("GET /api/runs", guard(http.HandlerFunc(api.recent)))
mux.Handle("GET /api/runs/{id}", guard(http.HandlerFunc(api.trail)))
}
type runAPI struct {
db *store.Store
orgID string
origins Origins
db *store.Store
orgID string
origins Origins
decisions Decisions
}
func (a *runAPI) recent(w http.ResponseWriter, r *http.Request) {
@@ -139,6 +148,10 @@ func (a *runAPI) trail(w http.ResponseWriter, r *http.Request) {
for _, s := range steps {
t.Entries = append(t.Entries, entry(s))
}
if t.Decisions, err = a.decisions.ForRun(r.Context(), id); err != nil {
httpjson.Error(w, http.StatusInternalServerError, "couldn't read the run's decisions")
return
}
httpjson.Write(w, http.StatusOK, t)
}