package judgement import ( "context" json "encoding/json/v2" "net/http" "strconv" "time" "github.com/danielgtaylor/huma/v2" "github.com/samcharles93/archie-core/internal/platform/httpapi" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/governance" ) // guardScanLimit bounds the decisions the control page reads to find a // guard's last recorded standing. const guardScanLimit = 200 // GuardControl is one guard as the Controls page shows it: built-in guards and // every guard extension installation (running, disabled, or failed), with its // configuration and the last model judgement recorded for it. type GuardControl struct { Name string `json:"name"` InstallationID string `json:"installation_id,omitempty"` Package string `json:"package,omitempty"` Scope string `json:"scope,omitempty"` BuiltIn bool `json:"built_in,omitempty"` Version string `json:"version,omitempty"` Digest string `json:"digest,omitempty"` Advisory bool `json:"advisory"` Enabled bool `json:"enabled"` State string `json:"state,omitempty"` Error string `json:"error,omitempty"` Settings map[string]string `json:"settings"` SettingsSchema []connectors.Setting `json:"settings_schema"` Latest *JudgeStanding `json:"latest,omitempty"` } type guardInstallationLister interface { GuardInstallations(ctx context.Context) ([]connectors.ExtensionView, error) } // JudgeStanding is the last model judgement a guard recorded: what the judge // answered, whether its eval counts it, and the date that eval is from. type JudgeStanding struct { Model string `json:"model,omitempty"` Trusted bool `json:"trusted"` AdvisoryReason string `json:"advisory_reason,omitempty"` EvalDate string `json:"eval_date,omitempty"` Answer string `json:"answer,omitempty"` At time.Time `json:"at"` } // Guards returns each built-in guard and every guard extension installation with // its configuration and the last model judgement recorded for it. func (m *Module) Guards(ctx context.Context) ([]GuardControl, error) { out := make([]GuardControl, 0, len(m.guards)) for _, g := range m.guards { latest, err := m.latestJudge(ctx, g.Name()) if err != nil { return nil, err } out = append(out, GuardControl{ Name: g.Name(), BuiltIn: true, Advisory: g.Advisory(), Enabled: true, State: "running", Settings: map[string]string{}, Latest: latest, }) } if m.extensions == nil { return out, nil } ext, err := m.extensionGuards(ctx) if err != nil { return nil, err } return append(out, ext...), nil } func (m *Module) extensionGuards(ctx context.Context) ([]GuardControl, error) { running := map[string]*connectors.Guard{} for _, g := range m.extensions.Guards(ctx) { running[g.Name()] = g } if lister, ok := m.extensions.(guardInstallationLister); ok { views, err := lister.GuardInstallations(ctx) if err == nil && views != nil { return m.viewsToGuards(ctx, views, running) } } out := make([]GuardControl, 0, len(running)) for _, g := range running { latest, err := m.latestJudge(ctx, g.Name()) if err != nil { return nil, err } out = append(out, GuardControl{ Name: g.Name(), Version: g.Version(), Digest: g.Digest(), Advisory: g.Advisory(), Enabled: true, State: "running", Settings: g.Settings(), SettingsSchema: g.SettingsSchema(), Latest: latest, }) } return out, nil } func (m *Module) viewsToGuards(ctx context.Context, views []connectors.ExtensionView, running map[string]*connectors.Guard) ([]GuardControl, error) { out := make([]GuardControl, 0, len(views)) for _, v := range views { advisory := false if g := running[v.Name]; g != nil { advisory = g.Advisory() } latest, err := m.latestJudge(ctx, v.Name) if err != nil { return nil, err } out = append(out, GuardControl{ Name: v.Name, InstallationID: v.ID.String(), Package: v.Package, Scope: v.Scope, Version: v.Version, Digest: v.Digest, Advisory: advisory, Enabled: v.Enabled, State: v.State, Error: v.Error, Settings: v.Settings, SettingsSchema: v.SettingsSchema, Latest: latest, }) } return out, nil } // latestJudge finds the newest verdict a guard recorded with a model judge. func (m *Module) latestJudge(ctx context.Context, guard string) (*JudgeStanding, error) { recent, err := m.queries.RecentBodies(ctx, m.orgID, guardScanLimit) if err != nil { return nil, err } for _, row := range recent { var body Decision if err := json.Unmarshal(row.Body, &body); err != nil { continue } for _, v := range body.Verdicts { if v.Guard != guard || len(v.Judges) == 0 { continue } j := v.Judges[len(v.Judges)-1] return &JudgeStanding{ Model: j.Model, Trusted: j.Trusted, AdvisoryReason: j.AdvisoryReason, EvalDate: j.EvalDate, Answer: j.Answer, At: row.CreatedAt, }, nil } } return nil, nil } // Register adds the guards API. func (m *Module) Register(api huma.API) { httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindGuard), huma.Operation{ OperationID: "list-guard-controls", Method: http.MethodGet, Path: "/api/controls/guards", Summary: "List each guard with its last recorded judgement", Tags: []string{"Controls"}, }, m.listGuards) } type listGuardsInput struct { SysQuery string `query:"sys_query" doc:"Conditions every row must meet, joined by ^: field=value, field!=value or fieldLIKEtext; applied to the rows the limit returns"` } // guardFilterFields are what a guard list's filter may compare. var guardFilterFields = httpapi.Fields[GuardControl]{ "name": func(v GuardControl) string { return v.Name }, "package": func(v GuardControl) string { return v.Package }, "scope": func(v GuardControl) string { return v.Scope }, "version": func(v GuardControl) string { return v.Version }, "advisory": func(v GuardControl) string { return strconv.FormatBool(v.Advisory) }, "enabled": func(v GuardControl) string { return strconv.FormatBool(v.Enabled) }, "state": func(v GuardControl) string { return v.State }, } func (m *Module) listGuards(ctx context.Context, in *listGuardsInput) (*httpapi.Reply[[]GuardControl], error) { out, err := m.Guards(ctx) if err != nil { m.log.ErrorContext(ctx, "list guards", "error", err) return nil, huma.Error500InternalServerError("couldn't read the guards") } filtered, err := httpapi.Filter(in.SysQuery, guardFilterFields, out) if err != nil { return nil, huma.Error400BadRequest(err.Error()) } return httpapi.OK(filtered), nil }