Files
samandCopilot cf6108ad14 feat(chat): conversations belong to their person and act with their access (#2065)
Sessions carry an owner; every chat route serves only the caller's own
conversations (others are 404). Each turn and each approved held action
acts as its owner's principal, checked against the access rules before
judgement, so an operator's chat can't do what the operator can't. Chat is
open to any signed-in person, and the stream sends chat updates only to
the owner.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-20 19:05:20 +11:00

227 lines
7.6 KiB
Go

package chat
import (
"context"
"encoding/json"
"encoding/json/jsontext"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/hub"
"github.com/samcharles93/archie-core/modules/approvals"
"github.com/samcharles93/archie-core/modules/chat/internal/store"
"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"
)
// Action states.
const (
actionWaiting = "waiting"
actionApproved = "approved"
actionRunning = "running"
actionSucceeded = "succeeded"
actionFailed = "failed"
actionUnknown = "unknown"
actionDenied = "denied"
actionExpired = "expired"
)
// Signal takes the answer to an approval a chat turn asked for. It reports
// false when id is not a chat turn, so the caller passes the answer on to the
// run waiting on it. The answer is stored before anything runs; the work loop
// runs an approved action once.
func (m *Module) Signal(ctx context.Context, id uuid.UUID, key string, payload jsontext.Value) (bool, error) {
owner, ours, err := m.store.TurnOwner(ctx, id)
if err != nil || !ours {
return false, err
}
var answer approvals.Answer
if err := json.Unmarshal(payload, &answer); err != nil {
return true, fmt.Errorf("decode approval answer: %w", err)
}
state := actionDenied
if answer.Approved {
state = actionApproved
}
answered, err := m.store.Answer(ctx, id, key, state, payload)
if err != nil || !answered {
return true, err
}
if !answer.Approved {
m.record(ctx, id, kindAction, ActionDone{RequestID: answer.RequestID, State: actionDenied})
m.hub.Publish(hub.Note{Topic: OwnerTopic(owner)})
}
m.poke()
return true, nil
}
// settleActions escalates or expires actions nobody answered in time and runs
// the approved ones. An action found running was started by a process that
// stopped: it may have taken effect, so it is never started again.
func (m *Module) settleActions(ctx context.Context) {
d, ok := m.uses()
if !ok {
return
}
open, err := m.store.Open(ctx)
if err != nil {
if ctx.Err() == nil {
m.log.ErrorContext(ctx, "list held chat actions", "error", err)
}
return
}
for _, a := range open {
var err error
switch a.State {
case actionWaiting:
if time.Now().After(a.StepDue) {
err = m.escalate(ctx, d, a)
}
case actionApproved:
err = m.runApproved(ctx, d, a)
case actionRunning:
err = m.settled(ctx, d, a, actionRunning, actionUnknown,
"It was started before Archie restarted and its outcome is unknown; it may have taken effect and won't run again.")
}
if err != nil {
m.log.ErrorContext(ctx, "settle chat action", "action", a.ID, "request", a.RequestID, "error", err)
}
}
}
// escalate passes an unanswered action to the next step of its path, or
// expires it after the last.
func (m *Module) escalate(ctx context.Context, d Deps, a store.Action) error {
var path []governance.PathStep
if err := json.Unmarshal(a.Path, &path); err != nil {
return fmt.Errorf("decode escalation path: %w", err)
}
next := a.Step + 1
if next < len(path) {
if err := d.Approver.Escalate(ctx, a.RequestID, next, path[next]); err != nil {
return err
}
return m.store.Escalated(ctx, a.ID, next, time.Now().Add(path[next].Deadline()))
}
if err := d.Approver.Expire(ctx, a.RequestID); err != nil {
return err
}
return m.settled(ctx, d, a, actionWaiting, actionExpired, "Nobody answered before the last deadline, so it didn't run.")
}
// runApproved judges an approved action again and runs it once. An approval
// for an action that has since changed or become stricter is discarded, and
// the operator asks again.
func (m *Module) runApproved(ctx context.Context, d Deps, a store.Action) error {
var (
held judgement.Decision
answer approvals.Answer
)
if err := json.Unmarshal(a.Decision, &held); err != nil {
return fmt.Errorf("decode decision: %w", err)
}
if err := json.Unmarshal(a.Answer, &answer); err != nil {
return fmt.Errorf("decode answer: %w", err)
}
ctx, err := m.actingAs(ctx, d, a.Owner)
if err != nil {
return err
}
if err := m.allowed(ctx, d, governance.ActionRun, governance.KindConnector, held.Action.Connector); err != nil {
if derr := d.Approver.Discard(ctx, a.RequestID, err.Error()); derr != nil {
return derr
}
return m.settled(ctx, d, a, actionApproved, actionFailed, err.Error())
}
fresh, err := d.Judge.Assess(ctx, judgement.Request{
RunID: a.TurnID, Key: held.Key + ":again", Connector: held.Action.Connector, Action: held.Action.Name,
Input: held.Action.Input, Workflow: principal,
})
if err != nil {
// Nothing runs that wasn't judged again; the operator asks again.
return m.settled(ctx, d, a, actionApproved, actionFailed, "It couldn't be judged again before running: "+err.Error())
}
if why := invalidated(held, fresh); why != "" {
if err := d.Approver.Discard(ctx, a.RequestID, why); err != nil {
return err
}
return m.settled(ctx, d, a, actionApproved, actionFailed, "The approval no longer holds: "+why+". Ask Archie again.")
}
started, err := m.store.Move(ctx, a.ID, actionApproved, actionRunning, "")
if err != nil || !started {
return err
}
var out string
if fresh.Level.Runs() {
out, err = d.Judge.Execute(ctx, fresh, fresh.Action.Input, a.Key)
} else {
if err := d.Approver.Accept(ctx, a.RequestID); err != nil {
return err
}
out, err = d.Judge.ExecuteApproved(ctx, held, answer.Approval(held), held.Action.Input, a.Key)
}
switch {
case errors.Is(err, connectors.ErrOutcomeUnknown):
return m.settled(ctx, d, a, actionRunning, actionUnknown, "It was started and its outcome is unknown; it may have taken effect: "+err.Error())
case err != nil:
return m.settled(ctx, d, a, actionRunning, actionFailed, err.Error())
}
return m.settled(ctx, d, a, actionRunning, actionSucceeded, out)
}
// invalidated says why an approval no longer covers the action as judged now,
// or nothing when it still does.
func invalidated(approved, fresh judgement.Decision) string {
switch {
case fresh.Level == judgement.Never:
return "it is now refused: " + fresh.Reason
case fresh.Level.Runs():
return ""
case fresh.Action.Target != approved.Action.Target:
return "its target changed since it was approved"
case fresh.Action.Effect != approved.Action.Effect:
return "its effect changed since it was approved"
case fresh.Level > approved.Level:
return "judgement is stricter than when it was approved: now " + fresh.Level.String()
}
return ""
}
// settled records what became of an action, shows it in its conversation and
// tells the people notifications go to. The notification names no run: a
// chat turn isn't one.
func (m *Module) settled(ctx context.Context, d Deps, a store.Action, from, to, result string) error {
moved, err := m.store.Move(ctx, a.ID, from, to, result)
if err != nil || !moved {
return err
}
done := ActionDone{RequestID: a.RequestID, State: to, Result: truncateRunes(result, outputMaxRunes)}
m.record(ctx, a.TurnID, kindAction, done)
m.hub.Publish(hub.Note{Topic: OwnerTopic(a.Owner)})
var held judgement.Decision
_ = json.Unmarshal(a.Decision, &held)
return d.Notifier.Notify(ctx, deliveries.Notification{
Key: "chat:" + a.ID.String() + ":" + to,
Title: actionTitle(to) + ": " + held.Action.Connector + " " + held.Action.Name,
Body: result,
})
}
func actionTitle(state string) string {
switch state {
case actionSucceeded:
return "Approved action ran"
case actionExpired:
return "Approval timed out"
case actionUnknown:
return "An action's outcome is unknown"
default:
return "Approved action didn't run"
}
}