Files
archie/modules/runs/trail.go
T
sam 0dbf241106 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.
2026-11-16 01:05:29 +11:00

211 lines
6.5 KiB
Go

package runs
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"net/http"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/samcharles93/ai-sdk/agentloop"
"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"
)
// Origin is the event and trigger that started a run.
type Origin struct {
EventID uuid.UUID `json:"event_id"`
Source string `json:"source"`
Type string `json:"type"`
Fields jsontext.Value `json:"fields"`
ReceivedAt time.Time `json:"received_at"`
Trigger string `json:"trigger"`
Filter jsontext.Value `json:"filter"`
}
// Origins finds the event and trigger that started a run. A run started any
// other way has none.
type Origins interface {
Origin(ctx context.Context, runID uuid.UUID) (Origin, bool, error)
}
// RunView is a run as the API shows it.
type RunView struct {
ID uuid.UUID `json:"id"`
Workflow string `json:"workflow"`
State string `json:"state"`
Attempts int `json:"attempts"`
Error string `json:"error,omitzero"`
CreatedAt time.Time `json:"created_at"`
FinishedAt *time.Time `json:"finished_at,omitzero"`
Result jsontext.Value `json:"result,omitzero"`
}
// 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"`
// 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
// agent's model call, "tool" for its tool call, and "step" for any other
// workflow step.
type TrailEntry struct {
Seq int `json:"seq"`
At time.Time `json:"at"`
Kind string `json:"kind"`
Name string `json:"name,omitzero"`
Text string `json:"text,omitzero"`
Reasoning string `json:"reasoning,omitzero"`
ToolCalls []ToolCallView `json:"tool_calls,omitzero"`
Usage *chat.Usage `json:"usage,omitzero"`
Input string `json:"input,omitzero"`
Output string `json:"output,omitzero"`
Value jsontext.Value `json:"value,omitzero"`
Error string `json:"error,omitzero"`
Unknown bool `json:"unknown,omitzero"`
}
// ToolCallView is a tool call a model asked for.
type ToolCallView struct {
Name string `json:"name"`
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, 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
decisions Decisions
}
func (a *runAPI) recent(w http.ResponseWriter, r *http.Request) {
limit := 50
if n, err := strconv.Atoi(r.URL.Query().Get("limit")); err == nil && n > 0 && n <= 200 {
limit = n
}
runs, err := a.db.Recent(r.Context(), a.orgID, limit)
if err != nil {
httpjson.Error(w, http.StatusInternalServerError, "couldn't list runs")
return
}
views := make([]RunView, 0, len(runs))
for _, s := range runs {
views = append(views, view(s, nil))
}
httpjson.Write(w, http.StatusOK, views)
}
func (a *runAPI) trail(w http.ResponseWriter, r *http.Request) {
id, err := uuid.Parse(r.PathValue("id"))
if err != nil {
httpjson.Error(w, http.StatusBadRequest, "a run id is a UUID")
return
}
d, ok, err := a.db.Detail(r.Context(), a.orgID, id)
switch {
case err != nil:
httpjson.Error(w, http.StatusInternalServerError, "couldn't read the run")
return
case !ok:
httpjson.Error(w, http.StatusNotFound, "no such run")
return
}
steps, err := a.db.RecordedSteps(r.Context(), id)
if err != nil {
httpjson.Error(w, http.StatusInternalServerError, "couldn't read the run's steps")
return
}
t := Trail{Run: view(d.Summary, d.Result), Entries: make([]TrailEntry, 0, len(steps))}
if o, ok, err := a.origins.Origin(r.Context(), id); err != nil {
httpjson.Error(w, http.StatusInternalServerError, "couldn't read what started the run")
return
} else if ok {
t.Origin = &o
}
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)
}
func view(s store.Summary, result jsontext.Value) RunView {
v := RunView{
ID: s.ID, Workflow: s.Workflow, State: s.State, Attempts: s.Attempts,
Error: s.Error.String, CreatedAt: s.CreatedAt, Result: result,
}
if s.FinishedAt.Valid {
v.FinishedAt = &s.FinishedAt.Time
}
return v
}
// entry turns a recorded step into a trail entry. An agent's journal steps
// are unpacked into the model and tool calls they record.
func entry(s store.Recorded) TrailEntry {
e := TrailEntry{Seq: s.Seq, At: s.RecordedAt, Kind: "step", Name: s.Name, Error: s.Error.String}
if s.Outcome == store.OutcomeUnknown {
e.Unknown = true
}
if !strings.HasPrefix(s.Name, "journal:agent:") {
e.Value = s.Output
return e
}
var je agentloop.Entry
if err := json.Unmarshal(s.Output, &je); err != nil {
e.Value = s.Output
return e
}
switch je.Kind {
case agentloop.EntryTool:
e.Kind, e.Name = "tool", je.ToolName
e.Input, e.Output, e.Error, e.Unknown = je.Input, je.Output, je.Error, je.Unknown
case agentloop.EntryModel, agentloop.EntryCompact:
e.Kind, e.Name = "model", ""
if je.Kind == agentloop.EntryCompact {
e.Kind = "compaction"
}
usage := je.Usage
e.Usage = &usage
if je.Message != nil {
e.Text = je.Message.Content
for _, p := range je.Message.Parts {
if rp, ok := p.(chat.ReasoningPart); ok {
e.Reasoning += rp.Text
}
}
for _, c := range je.Message.ToolCalls {
e.ToolCalls = append(e.ToolCalls, ToolCallView{Name: c.Name, Input: c.Arguments})
}
}
e.Error = je.Error
}
return e
}