diff --git a/changelog.d/added-18916-kick-outcome-record.md b/changelog.d/added-18916-kick-outcome-record.md new file mode 100644 index 0000000000..b31699d278 --- /dev/null +++ b/changelog.d/added-18916-kick-outcome-record.md @@ -0,0 +1 @@ +- Per-kick outcome record: the hive now keeps a durable, bounded record of what each kick of an agent came to (opened a PR, pushed a commit, commented, stood down, was refused, still running, or ended with no visible action), who or what triggered it, and when, derived only from signals it already has, and exposes it on `GET /api/kick-outcomes` (owner and read-write see detail; read-only sees a one-line summary) (#18916). diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 2871112881..c9dd9a9d20 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -37370,6 +37370,185 @@ } } }, + "/api/kick-outcomes": { + "get": { + "tags": [ + "Agents" + ], + "summary": "What each kick of an agent came to", + "description": "Any authenticated role. Without `agent`, lists every agent's latest kick as a one-line summary (`agents`). With `agent`, lists that agent's last ten kicks, newest first (`kicks`). Owner and read-write sessions also receive the detail of each kick: trigger_kind (dashboard, governor, workflow_dispatch, other), trigger_actor (the dashboard user's login), started_at, ended_at, pr_url, pr_number, branch, sha, refusal_code (a reason code from the kick-refusals page) and `quote`, the agent's own stand-down line or the text behind a refusal. A read-only session receives only the latest kick's one-line summary. The outcome is derived from real signals only (hivecommons/hive#18916): a kick no signal speaks for is ended_no_visible_action, never a guess. `quote` is untrusted agent text: tokens are redacted and it is length-capped, and a client must escape it. Not reachable by agents.", + "parameters": [ + { + "name": "agent", + "in": "query", + "required": false, + "schema": { + "type": "string" + }, + "description": "Agent name; omit for every agent's latest kick." + } + ], + "responses": { + "200": { + "description": "Kick outcomes", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "detail": { + "type": "boolean", + "description": "True when this session may see kick detail." + }, + "agent": { + "type": "string" + }, + "agents": { + "type": "object", + "description": "Latest kick per agent, keyed by agent name.", + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "agent": { + "type": "string" + }, + "kind": { + "type": "string", + "enum": [ + "opened_pr", + "pushed_commit", + "commented", + "stood_down", + "refused", + "still_running", + "ended_no_visible_action" + ] + }, + "summary": { + "type": "string", + "description": "One line, e.g. \"opened PR #12\". The age is rendered from `at`." + }, + "at": { + "type": "string", + "format": "date-time" + } + } + } + }, + "latest": { + "type": "object", + "description": "Read-only sessions: the agent's latest kick summary.", + "properties": { + "id": { + "type": "string" + }, + "agent": { + "type": "string" + }, + "kind": { + "type": "string", + "enum": [ + "opened_pr", + "pushed_commit", + "commented", + "stood_down", + "refused", + "still_running", + "ended_no_visible_action" + ] + }, + "summary": { + "type": "string", + "description": "One line, e.g. \"opened PR #12\". The age is rendered from `at`." + }, + "at": { + "type": "string", + "format": "date-time" + } + } + }, + "kicks": { + "type": "array", + "description": "Owner and read-write sessions: the agent's last kicks.", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "agent": { + "type": "string" + }, + "kind": { + "type": "string", + "enum": [ + "opened_pr", + "pushed_commit", + "commented", + "stood_down", + "refused", + "still_running", + "ended_no_visible_action" + ] + }, + "summary": { + "type": "string", + "description": "One line, e.g. \"opened PR #12\". The age is rendered from `at`." + }, + "at": { + "type": "string", + "format": "date-time" + }, + "trigger_kind": { + "type": "string" + }, + "trigger_actor": { + "type": "string" + }, + "started_at": { + "type": "string", + "format": "date-time" + }, + "ended_at": { + "type": "string", + "format": "date-time" + }, + "pr_url": { + "type": "string" + }, + "pr_number": { + "type": "integer" + }, + "branch": { + "type": "string" + }, + "sha": { + "type": "string" + }, + "refusal_code": { + "type": "string" + }, + "quote": { + "type": "string", + "description": "Untrusted agent text, redacted and capped." + } + } + } + } + } + } + } + } + }, + "503": { + "description": "Kick outcomes are not available on this hive" + } + } + } + }, "/api/hive-advice": { "get": { "tags": [ diff --git a/src/cmd/hive/github_client_config.go b/src/cmd/hive/github_client_config.go index 30cecf8b23..b8b68ecba2 100644 --- a/src/cmd/hive/github_client_config.go +++ b/src/cmd/hive/github_client_config.go @@ -462,6 +462,8 @@ func (b *boot) applyGitHubClientDashboardHooks(client *github.Client) { sessions = b.agentMgr } recordPRFollowUpPointer(b.cfg, sessions, d, time.Now(), b.logger) + // The kick this PR came from is told (hivecommons/hive#18916). + kickOutcomesFor(b.cfg, b.logger).PROpened(d.Agent, d.URL, d.Number, time.Now()) // The issues the PR fixes get their own pr_opened stage: the // start→PR SLA boundary, and the link a later merge folds back on. recordPROpenedForIssues(b.dashSrv, b.cfg.Project.Org, d.Agent, d.Repo, d.Number, d.URL, d.Issues) @@ -470,6 +472,7 @@ func (b *boot) applyGitHubClientDashboardHooks(client *github.Client) { // PR already covers in the gap between (hivecommons/hive#14472). client.RecordOpenedPRClaims(getClaimLedger(b.logger), d, hiveIdentity(b.cfg), time.Now()) }) + client.SetAgentActionHook(func(a github.AgentAction) { kickOutcomeAgentAction(kickOutcomesFor(b.cfg, b.logger), a) }) client.SetCanaryScanner(b.cfg.Ioscan.IsEnabled() && b.cfg.Ioscan.CanariesEnabled(), b.cfg.Ioscan.FailClosedAtLevel(b.cfg.ACMMLevelOrZero()), ioscan.DefaultCanaries, b.handleCanaryLeak) } diff --git a/src/cmd/hive/kick_outcome_wire.go b/src/cmd/hive/kick_outcome_wire.go new file mode 100644 index 0000000000..3f336f84db --- /dev/null +++ b/src/cmd/hive/kick_outcome_wire.go @@ -0,0 +1,134 @@ +package main + +import ( + "errors" + "log/slog" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/dashboard" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/kickoutcome" + wfstore "github.com/hivecommons/hive/pkg/workflowmodel/store" +) + +// Per-kick outcome record, host wiring (hivecommons/hive#18916). +// +// pkg/kickoutcome keeps the record; this file feeds it the signals the hive +// already has: the fan-out kick observer (a kick was delivered), the runtime's +// turn-end classification, the relay's pull-request, push and comment events, +// and the callers that know who or what is kicking (the governor here; the +// dashboard in pkg/dashboard). Nothing here reads agent text into a prompt. + +// kickOutcomesFile is the durable record under the hive's data root. +const kickOutcomesFile = "kick-outcomes.json" + +var ( + kickOutcomesOnce sync.Once + kickOutcomesStore *kickoutcome.Store +) + +// kickOutcomesFor is the process's kick outcome store, opened on first use. A +// corrupt or unreadable file starts the store empty with a warning: a lost +// record must not stop kicks. +func kickOutcomesFor(cfg *config.Config, logger *slog.Logger) *kickoutcome.Store { + kickOutcomesOnce.Do(func() { + path := "" + if cfg != nil { + path = filepath.Join(wfstore.Root(cfg.Data.WorkflowsDir), kickOutcomesFile) + } + s, err := kickoutcome.Open(path, logger) + if err != nil && logger != nil { + logger.Warn("kick outcomes unreadable; starting empty", "path", path, "error", err) + } + kickOutcomesStore = s + }) + return kickOutcomesStore +} + +// kickOutcomeTurnEnded files how an agent's kicked turn ended. The agent +// manager's refusal flag, when set and not a startup deferral, also marks the +// kick as declined by the agent's own model. +func kickOutcomeTurnEnded(s *kickoutcome.Store, status func(agent string) (*crux.Process, error), agent string, o crux.KickOutcome) { + if s == nil { + return + } + s.TurnEnded(agent, o.Kind, o.Reason, o.KickAt, o.At) + if status == nil { + return + } + if p, err := status(agent); err == nil && p != nil && p.KickRefused && + !strings.Contains(p.KickRefusalReason, workflowStartupDeferral) && p.LastKick != nil && p.LastKick.Equal(o.KickAt) { + s.Declined(agent, p.KickRefusalReason, o.At) + } +} + +// kickOutcomeDelivered files a delivered kick from a fan-out kick event. +func kickOutcomeDelivered(s *kickoutcome.Store, ev crux.KickEvent) { + if ev.Event == crux.KickEventDelivered { + s.Delivered(ev.Agent, ev.At) + } +} + +// kickOutcomeAgentAction files a relay push or comment. +func kickOutcomeAgentAction(s *kickoutcome.Store, a github.AgentAction) { + switch a.Kind { + case github.AgentActionPush: + s.Pushed(a.Agent, a.Branch, a.SHA, a.At) + case github.AgentActionComment: + s.Commented(a.Agent, a.At) + } +} + +// kickOutcomeSender wraps the governor's kick delivery: it says the kick is +// the governor's (or a workflow hand-off's, when workflowKick says so) and +// files a refusal the hive's delivery checks raise. A busy bounce is a +// deferral, not a refusal, and is left to the next pass. +func kickOutcomeSender(s *kickoutcome.Store, send func(agent, message string) error, workflowKick func(agent, message string) bool) func(agent, message string) error { + return func(agent, message string) error { + kind := kickoutcome.TriggerGovernor + if workflowKick != nil && workflowKick(agent, message) { + kind = kickoutcome.TriggerWorkflowDispatch + } + s.Intend(agent, kickoutcome.Trigger{Kind: kind, Actor: "governor"}) + err := send(agent, message) + if err != nil && !isKickBusy(err) { + if code := dashboard.ClassifyKickRefusal(err.Error()); code != "" { + s.Refused(agent, kickoutcome.Trigger{Kind: kind, Actor: "governor"}, code, err.Error(), time.Now()) + } + } + return err + } +} + +// isKickBusy reports a busy bounce (agent mid-turn). +func isKickBusy(err error) bool { return errors.Is(err, crux.ErrAgentBusy) } + +// kickOutcomeSource adapts the store to the dashboard's KickOutcomeSource, so +// the dashboard takes no import of pkg/kickoutcome. +type kickOutcomeSource struct{ s *kickoutcome.Store } + +func (a kickOutcomeSource) Intend(agent, kind, actor string) { + a.s.Intend(agent, kickoutcome.Trigger{Kind: kind, Actor: actor}) +} + +func (a kickOutcomeSource) Refused(agent, kind, actor, code, reason string, at time.Time) { + a.s.Refused(agent, kickoutcome.Trigger{Kind: kind, Actor: actor}, code, reason, at) +} + +func (a kickOutcomeSource) Latest() any { return a.s.Latest() } + +func (a kickOutcomeSource) Recent(agent string, n int) (any, any) { + kicks := a.s.Recent(agent, n) + if kicks == nil { + kicks = []kickoutcome.Detail{} + } + if len(kicks) == 0 { + return nil, kicks + } + return kicks[0].View, kicks +} diff --git a/src/cmd/hive/kick_outcome_wire_test.go b/src/cmd/hive/kick_outcome_wire_test.go new file mode 100644 index 0000000000..9804fb168e --- /dev/null +++ b/src/cmd/hive/kick_outcome_wire_test.go @@ -0,0 +1,69 @@ +package main + +import ( + "errors" + "testing" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/kickoutcome" +) + +func TestKickOutcomeSenderAttributesAndFilesRefusals(t *testing.T) { + s, _ := kickoutcome.Open("", nil) + wf := func(agent, message string) bool { return message == "handoff" } + send := kickOutcomeSender(s, func(agent, message string) error { + switch message { + case "paused": + return errors.New("agent a cannot be kicked: it is paused") + case "busy": + return crux.ErrAgentBusy + case "mystery": + return errors.New("nobody documented this") + } + s.Delivered(agent, time.Now()) + return nil + }, wf) + _ = send("a", "handoff") + _ = send("a", "plain") + _ = send("a", "busy") + _ = send("a", "mystery") + if err := send("a", "paused"); err == nil { + t.Fatal("the send error was swallowed") + } + rs := s.Records("a", 0) + if len(rs) != 3 { + t.Fatalf("want 2 kicks and 1 documented refusal, got %d: %+v", len(rs), rs) + } + if rs[2].TriggerKind != kickoutcome.TriggerWorkflowDispatch || rs[1].TriggerKind != kickoutcome.TriggerGovernor { + t.Fatalf("triggers: %+v", rs) + } + if rs[0].RefusalCode != "paused" { + t.Fatalf("refusal: %+v", rs[0]) + } +} + +func TestKickOutcomeRelayActionsFileOnTheKick(t *testing.T) { + s, _ := kickoutcome.Open("", nil) + now := time.Now() + s.Delivered("a", now) + kickOutcomeAgentAction(s, github.AgentAction{Agent: "a", Kind: github.AgentActionPush, Branch: "fix/x", SHA: "abc123", At: now.Add(time.Minute)}) + s.SetClock(func() time.Time { return now.Add(2 * time.Minute) }) + if v, _ := s.LatestOf("a"); v.Kind != kickoutcome.KindPushedCommit { + t.Fatalf("%+v", v) + } + kickOutcomeAgentAction(s, github.AgentAction{Agent: "a", Kind: "unknown", At: now}) +} + +func TestKickOutcomeDeliveredIgnoresOtherEvents(t *testing.T) { + s, _ := kickoutcome.Open("", nil) + kickOutcomeDelivered(s, crux.KickEvent{Agent: "a", Event: crux.KickEventQueued, At: time.Now()}) + if len(s.Records("a", 0)) != 0 { + t.Fatal("a queued event opened a kick record") + } + kickOutcomeDelivered(s, crux.KickEvent{Agent: "a", Event: crux.KickEventDelivered, At: time.Now()}) + if len(s.Records("a", 0)) != 1 { + t.Fatal("a delivered event did not") + } +} diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 5c734560cc..251828353e 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -1131,6 +1131,7 @@ func (b *boot) wireBootClosures() { WorkflowProvisionLabels: workflowProvisionLabels(b.cfg, func() *github.Client { return b.ghClient }, b.logger), WorkflowDispatchPrepare: workflowDispatchPrepare(b.cfg, func() *github.Client { return b.ghClient }, b.logger), WorkflowDispatchHandoffs: workflowDispatchHandoffs(b.cfg, b.logger), + KickOutcomes: kickOutcomeSource{kickOutcomesFor(b.cfg, b.logger)}, WorkflowEmitChecks: workflowEmitChecks(b.cfg, func() *github.Client { return b.ghClient }), WorkflowClusterRunner: workflowClusterRunner(), WorkflowSpecLLM: newWorkflowSpecRunner(func() *config.Config { return b.cfg }), @@ -2009,9 +2010,16 @@ func (b *boot) bootAgentsWith(deps bootAgentsDeps) { // tells it afterwards how the turn ENDED, so a kick that produced a // clarifying question or a policy stand-down is not counted like one that // produced work (and a question earns an early re-kick). + koStore := kickOutcomesFor(b.cfg, b.logger) b.agentMgr.SetKickOutcomeObserver(func(agentName string, outcome crux.KickOutcome) { b.gov.RecordKickOutcome(agentName, outcome.Kind, outcome.Reason, outcome.KickAt, outcome.At) + kickOutcomeTurnEnded(koStore, b.agentMgr.GetStatus, agentName, outcome) }) + // #18916: a delivered kick opens its outcome record; the relay's push and + // comment events (and the PR-opened hook) close it. + if reg, ok := b.agentMgr.(crux.KickObserverRegistry); ok { + b.cleanup.push(reg.AddKickObserver(func(ev crux.KickEvent) { kickOutcomeDelivered(koStore, ev) })) + } // Say out loud when the sandbox opt-in is configured but inert. The gate is // two-part (global agent_sandbox.enabled AND a per-agent sandbox.enabled), diff --git a/src/cmd/hive/main_eval_cycle.go b/src/cmd/hive/main_eval_cycle.go index 7e5b031f5c..0032ce4f91 100644 --- a/src/cmd/hive/main_eval_cycle.go +++ b/src/cmd/hive/main_eval_cycle.go @@ -1218,7 +1218,10 @@ func runEvalCycle( ctx := kickCtx dispatchAgentKicks(messages, releaseProviderBudgetProbe, kickDispatchDeps{ backoffRemaining: agentMgr.ProviderErrorBackoffRemaining, - sendKick: agentMgr.SendKick, + sendKick: kickOutcomeSender(kickOutcomesFor(cfg, logger), agentMgr.SendKick, func(agent, message string) bool { + _, ok := workflowKickByMessage[workflowDispatchKickKey(scheduler.KickMessage{Agent: agent, Message: message})] + return ok + }), startStoppedAgent: func(agentName string) error { if !agentMgr.GovernorMayStart(agentName) { return nil diff --git a/src/docs/api-reference/agents-and-controls.md b/src/docs/api-reference/agents-and-controls.md index d0f3c90311..bb94c2e63f 100644 --- a/src/docs/api-reference/agents-and-controls.md +++ b/src/docs/api-reference/agents-and-controls.md @@ -8,6 +8,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/kick/{agent}` | Owner only | Kick — asynchronous; answers `202` once queued (see below) | `pkg/dashboard/api.go:120` | | `GET` | `/api/kick/{agent}/status` | Dashboard auth/session | Outcome of the most recent kick | `pkg/dashboard/api.go:124` | +| `GET` | `/api/kick-outcomes` | Dashboard auth/session; detail for owner and read-write | What each kick of an agent came to ([#18916](https://github.com/hivecommons/hive/issues/18916)). Without `?agent=`, every agent's latest kick as `{kind, summary, at}` under `agents`. With `?agent=`, that agent's last ten kicks under `kicks`, newest first, each with `trigger_kind` (`dashboard`, `governor`, `workflow_dispatch`, `other`), `trigger_actor`, `started_at`, `ended_at`, `pr_url`/`pr_number`, `branch`/`sha`, `refusal_code` (a [kick-refusals](../kick-refusals.md) reason) and `quote`; a read-only session gets only the latest one-line summary. `kind` is one of `opened_pr`, `pushed_commit`, `commented`, `stood_down`, `refused`, `still_running`, `ended_no_visible_action`, derived from real signals only. `quote` is untrusted agent text (redacted, capped): escape it. Not reachable by agents. `503` without the store | `pkg/dashboard/api_kick_outcomes.go:49` | | `POST` | `/api/switch/{agent}/{backend}` | Owner only | Switch | `pkg/dashboard/api.go:125` | | `POST` | `/api/model/{agent}/{model}` | Owner only | Model Set | `pkg/dashboard/api.go:126` | | `POST` | `/api/effort/{agent}/{effort}` | Owner only | Set launch-only reasoning effort after validating against the agent's live backend (including runtime override); persists config/agent overlay, restarts the session, and `default` clears the stored effort | `pkg/dashboard/api.go:127` | diff --git a/src/docs/kick-refusals.md b/src/docs/kick-refusals.md index 723bae811f..4bdff020e6 100644 --- a/src/docs/kick-refusals.md +++ b/src/docs/kick-refusals.md @@ -207,6 +207,34 @@ agent, often after a rename or a config reload. - **What to do:** check the agent list in the dashboard or `hive.yaml`. +## What a kick came to + +A delivered kick is not a finished piece of work. The hive keeps a durable, +bounded record of the last ten kicks of each agent (`GET /api/kick-outcomes`): +who or what triggered each one (a dashboard user's login, the governor, a +workflow hand-off), when it started and ended, and what it came to: + +| Outcome | Derived from | +|---|---| +| `opened_pr` | the relay opened a pull request for the agent during the kick (or within 15 minutes after its turn ended); the record keeps the PR number and URL | +| `pushed_commit` | the relay pushed a branch for the agent; the record keeps the branch and sha | +| `commented` | the relay posted a comment for the agent | +| `stood_down` | the agent ended its turn on a stand-down line; the record quotes that line | +| `refused` | the hive refused to deliver the kick, or the agent's model declined it; the record keeps the reason code from this page and the quoted text | +| `still_running` | the kick's turn has not ended and no signal has arrived yet | +| `ended_no_visible_action` | the turn ended, or can no longer be told apart from one that ended, and no signal above speaks for it | + +The outcome is derived only from those signals when it is read, so a pull +request the relay opens a few minutes after the turn ends upgrades the outcome. +Where the hive cannot tell, it says `ended_no_visible_action`; it never +guesses. Refusals are recorded only for the reasons on this page. + +The quoted text is what an agent (or the hive) wrote, so it is untrusted: the +hive redacts token-shaped strings, caps it at 200 characters and escapes it +when shown, and never puts it into an agent prompt. Agents cannot query the +record. Owner and read-write sessions see the detail; a read-only session sees +only the one-line summary. Log lines about the record hold ids and kinds only. + ## Where to see refusals - **Toast.** Clicking **kick** on an agent card shows "Kick failed: ..." with a diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index 40fbbcbd8f..73811c04cf 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -571,6 +571,8 @@ func (s *Server) RegisterAPI(deps *Dependencies) { // api_repo_agents.go): list, approve, reject, rescan. s.registerRepoAgentRoutes() s.registerVersionContainsRoute() + // Per-kick outcome record (#18916, api_kick_outcomes.go). + s.registerKickOutcomeRoutes() } var ( diff --git a/src/pkg/dashboard/api_agent_control.go b/src/pkg/dashboard/api_agent_control.go index f3970410e6..e0dba7dc06 100644 --- a/src/pkg/dashboard/api_agent_control.go +++ b/src/pkg/dashboard/api_agent_control.go @@ -39,13 +39,18 @@ func (s *Server) handleKick(w http.ResponseWriter, r *http.Request) { return } + kickUser := requestUser(r) deliverKick := func(kickMsg string) (bool, error) { - return s.deps.AgentMgr.SendKickAsync(name, kickMsg) + s.kickIntend(name, kickTriggerDashboard, kickUser) + started, err := s.deps.AgentMgr.SendKickAsync(name, kickMsg) + s.kickRefusedOnError(name, kickTriggerDashboard, kickUser, err) + return started, err } if msg == "" && s.deps.Scheduler != nil { if !s.deps.Scheduler.FirstScanDone() { if err := s.deps.AgentMgr.ValidateKick(name); err != nil { + s.kickRefusedOnError(name, kickTriggerDashboard, kickUser, err) jsonKickError(w, err.Error(), http.StatusBadRequest) return } diff --git a/src/pkg/dashboard/api_kick_outcomes.go b/src/pkg/dashboard/api_kick_outcomes.go new file mode 100644 index 0000000000..637bb94657 --- /dev/null +++ b/src/pkg/dashboard/api_kick_outcomes.go @@ -0,0 +1,112 @@ +package dashboard + +import ( + "net/http" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +// Per-kick outcome record (hivecommons/hive#18916). +// +// GET /api/kick-outcomes answers "what did that kick come to?" from the +// durable record pkg/kickoutcome keeps. Without `agent` it lists every agent's +// latest kick as a one-line summary; with `agent` it lists that agent's last +// kicks. Any authenticated role sees the one-line summary (kind, summary, at); +// owner and read-write roles also see the detail: trigger, times, the pull +// request, branch and sha, the refusal reason code and the quoted text behind a +// stand-down or refusal. The quote is untrusted agent text: it is redacted and +// capped when stored, and the page escapes it. It is never fed back to an +// agent, and agents cannot reach this route. + +// kickOutcomeRecentLimit is how many kicks the per-agent list returns. +const kickOutcomeRecentLimit = 10 + +// Trigger kinds the dashboard declares; they match pkg/kickoutcome's. +const ( + kickTriggerDashboard = "dashboard" + kickTriggerWorkflowDispatch = "workflow_dispatch" +) + +// KickOutcomeSource is the durable per-kick record (pkg/kickoutcome behind an +// adapter in cmd/hive), kept behind an interface so the dashboard takes no new +// package import. Views and details are JSON-shaped values the handler passes +// through; the handler never builds or trusts quoted text itself. +type KickOutcomeSource interface { + // Intend says who or what is about to kick agent. + Intend(agent, kind, actor string) + // Refused files a kick the hive refused, with a documented reason code. + Refused(agent, kind, actor, code, reason string, at time.Time) + // Latest is every agent's latest kick as one-line summaries. + Latest() any + // Recent is the agent's last n kicks as detail (kicks) and its latest + // kick's one-line summary (latest, nil when there is none). + Recent(agent string, n int) (latest any, kicks any) +} + +func (s *Server) registerKickOutcomeRoutes() { + s.mux.HandleFunc("GET /api/kick-outcomes", s.handleKickOutcomes) +} + +// canSeeKickOutcomeDetail admits owner (verified) and read-write sessions to +// the detail of a kick; a read-only session sees the one-line summary only. +func canSeeKickOutcomeDetail(r *http.Request) bool { + role := r.Header.Get("X-Hive-Role") + if isOwnerRole(role) && r.Header.Get(ownerRoleVerifiedHeader) != "true" { + return false + } + return config.RoleAtLeast(role, config.RoleReadWrite) +} + +func (s *Server) handleKickOutcomes(w http.ResponseWriter, r *http.Request) { + if s.deps == nil || s.deps.KickOutcomes == nil { + jsonError(w, "kick outcomes are not available on this hive", http.StatusServiceUnavailable) + return + } + detail := canSeeKickOutcomeDetail(r) + agent := strings.TrimSpace(r.URL.Query().Get("agent")) + if agent == "" { + jsonResponse(w, map[string]interface{}{"detail": detail, "agents": s.deps.KickOutcomes.Latest()}) + return + } + agent = s.resolveAgentParam(agent) + latest, kicks := s.deps.KickOutcomes.Recent(agent, kickOutcomeRecentLimit) + if detail { + jsonResponse(w, map[string]interface{}{"detail": true, "agent": agent, "kicks": kicks}) + return + } + // Read-only: the latest kick's one-line summary and nothing else. + resp := map[string]interface{}{"detail": false, "agent": agent} + if latest != nil { + resp["latest"] = latest + } + jsonResponse(w, resp) +} + +// kickIntend tells the record who or what is about to kick agent. +func (s *Server) kickIntend(agent, kind, actor string) { + if s == nil || s.deps == nil || s.deps.KickOutcomes == nil { + return + } + s.deps.KickOutcomes.Intend(agent, kind, actor) +} + +// kickRefusedOnError records a kick the hive refused to deliver, when err +// names a documented refusal reason (kick-refusals.md). An error that matches +// no reason is not recorded: the record never invents a code. +func (s *Server) kickRefusedOnError(agent, kind, actor string, err error) { + if s == nil || s.deps == nil || s.deps.KickOutcomes == nil || err == nil { + return + } + code := classifyKickError(err.Error()) + if code == "" { + return + } + s.deps.KickOutcomes.Refused(agent, kind, actor, code, err.Error(), time.Now()) +} + +// ClassifyKickRefusal maps a kick error message to its kick-refusals.md +// reason code, or "" when it matches none. Exported for the governor's kick +// path in cmd/hive. +func ClassifyKickRefusal(msg string) string { return classifyKickError(msg) } diff --git a/src/pkg/dashboard/api_kick_outcomes_test.go b/src/pkg/dashboard/api_kick_outcomes_test.go new file mode 100644 index 0000000000..b897ae2aac --- /dev/null +++ b/src/pkg/dashboard/api_kick_outcomes_test.go @@ -0,0 +1,127 @@ +package dashboard + +import ( + "encoding/json" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// fakeKickOutcomes is a canned KickOutcomeSource: the derivation, redaction +// and caps are pkg/kickoutcome's tests; here only the route is under test. +type fakeKickOutcomes struct { + intents, refusals []string +} + +func (f *fakeKickOutcomes) Intend(agent, kind, actor string) { + f.intents = append(f.intents, agent+"|"+kind+"|"+actor) +} + +func (f *fakeKickOutcomes) Refused(agent, kind, actor, code, reason string, _ time.Time) { + f.refusals = append(f.refusals, agent+"|"+kind+"|"+actor+"|"+code) +} + +func (f *fakeKickOutcomes) Latest() any { + return map[string]any{"scanner": map[string]any{"kind": "stood_down", "summary": "stood down"}} +} + +func (f *fakeKickOutcomes) Recent(agent string, _ int) (any, any) { + return map[string]any{"kind": "stood_down", "summary": "stood down"}, + []any{map[string]any{"kind": "stood_down", "summary": "stood down", "trigger_kind": "governor", "started_at": "x", "quote": "no push rights"}} +} + +func kickOutcomeServer(t *testing.T) (*Server, *fakeKickOutcomes) { + t.Helper() + s := NewServer(0, slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelError}))) + deps := testDeps(t) + f := &fakeKickOutcomes{} + deps.KickOutcomes = f + s.RegisterAPI(deps) + return s, f +} + +func kickOutcomeGet(s *Server, path, role string, verified bool) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Header.Set("X-Hive-User", "u") + if role != "" { + req.Header.Set("X-Hive-Role", role) + } + if verified { + req.Header.Set(ownerRoleVerifiedHeader, "true") + } + rec := httptest.NewRecorder() + s.mux.ServeHTTP(rec, req) + return rec +} + +// A read-only session sees the one-line summary and nothing else: no quoted +// reason, no trigger, no times of the turn. An owner and a read-write session +// see the detail, with tokens redacted. +func TestKickOutcomesRoleGatedDetail(t *testing.T) { + s, _ := kickOutcomeServer(t) + + for _, c := range []struct { + name, role string + verified bool + detail bool + }{{"read-only", "read", false, false}, {"proofless owner", "owner", false, false}, {"read-write", "read-write", false, true}, {"owner", "owner", true, true}} { + rec := kickOutcomeGet(s, "/api/kick-outcomes?agent=scanner", c.role, c.verified) + if rec.Code != http.StatusOK { + t.Fatalf("%s: %d %s", c.name, rec.Code, rec.Body) + } + body := rec.Body.String() + hasQuote := strings.Contains(body, "no push rights") + if hasQuote != c.detail { + t.Fatalf("%s: quote visible=%v want %v: %s", c.name, hasQuote, c.detail, body) + } + if !c.detail && (strings.Contains(body, "trigger") || strings.Contains(body, "started_at") || strings.Contains(body, "kicks")) { + t.Fatalf("%s: detail fields leaked to a read-only session: %s", c.name, body) + } + if !strings.Contains(body, "stood down") { + t.Fatalf("%s: summary missing: %s", c.name, body) + } + } +} + +func TestKickOutcomesLatestListHoldsSummariesOnly(t *testing.T) { + s, _ := kickOutcomeServer(t) + rec := kickOutcomeGet(s, "/api/kick-outcomes", "owner", true) + var resp struct { + Agents map[string]map[string]any `json:"agents"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if v := resp.Agents["scanner"]; v["kind"] != "stood_down" || v["quote"] != nil { + t.Fatalf("%v", v) + } +} + +func TestKickOutcomesUnavailableWithoutStore(t *testing.T) { + s, _ := kickOutcomeServer(t) + s.deps.KickOutcomes = nil + if rec := kickOutcomeGet(s, "/api/kick-outcomes", "owner", true); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("%d", rec.Code) + } +} + +// A refusal is recorded only with a documented reason code; the record never +// invents one. +func TestKickRefusedOnErrorUsesDocumentedCodes(t *testing.T) { + s, f := kickOutcomeServer(t) + s.kickRefusedOnError("a", kickTriggerDashboard, "alice", errors.New("agent a cannot be kicked: it is paused (by budget)")) + s.kickRefusedOnError("a", kickTriggerDashboard, "alice", errors.New("something nobody documented")) + s.kickRefusedOnError("a", kickTriggerDashboard, "alice", nil) + if len(f.refusals) != 1 || f.refusals[0] != "a|dashboard|alice|"+kickRefusalPaused { + t.Fatalf("%v", f.refusals) + } + s.kickIntend("a", kickTriggerWorkflowDispatch, "bob") + if len(f.intents) != 1 { + t.Fatalf("%v", f.intents) + } +} diff --git a/src/pkg/dashboard/api_workflows_dispatch.go b/src/pkg/dashboard/api_workflows_dispatch.go index be6fab66de..35b6367c7d 100644 --- a/src/pkg/dashboard/api_workflows_dispatch.go +++ b/src/pkg/dashboard/api_workflows_dispatch.go @@ -77,7 +77,9 @@ func (s *Server) handleWorkflowDispatch(w http.ResponseWriter, r *http.Request) jsonError(w, err.Error(), workflowDispatchStatus(err)) return } + s.kickIntend(plan.Agent, kickTriggerWorkflowDispatch, by) if err := s.deps.AgentMgr.SendKick(plan.Agent, plan.Message); err != nil { + s.kickRefusedOnError(plan.Agent, kickTriggerWorkflowDispatch, by, err) status := http.StatusBadGateway if errors.Is(err, crux.ErrAgentBusy) { status = http.StatusConflict diff --git a/src/pkg/dashboard/deps.go b/src/pkg/dashboard/deps.go index 03629a8711..39ffe50432 100644 --- a/src/pkg/dashboard/deps.go +++ b/src/pkg/dashboard/deps.go @@ -104,8 +104,11 @@ type Dependencies struct { // test without a runtime) leaves the field out of the body. CruxRuntimeHealth func() CruxRuntimeHealth Governor *governor.Governor - GHClient *ghpkg.Client - GHAppAuth *ghpkg.AppAuth + // KickOutcomes is the durable per-kick outcome record behind + // GET /api/kick-outcomes (hivecommons/hive#18916). Nil answers 503. + KickOutcomes KickOutcomeSource + GHClient *ghpkg.Client + GHAppAuth *ghpkg.AppAuth // GHTokenScopes is the boot-time PAT scope probe result (see // ghpkg.CheckTokenScopes). It is set only on the token-auth path; the App // path leaves it at ScopeStatusSkipped because Apps carry permissions, not diff --git a/src/pkg/github/agent_action_hook.go b/src/pkg/github/agent_action_hook.go new file mode 100644 index 0000000000..e450b81e66 --- /dev/null +++ b/src/pkg/github/agent_action_hook.go @@ -0,0 +1,53 @@ +package github + +import "time" + +// Agent actions the relay performed on an agent's behalf (hivecommons/hive#18916). +// +// The per-kick outcome record needs to know what a kick came to. The relay is +// where an agent's GitHub writes happen, so it tells one observer, with ids +// only: which agent, what kind of write, where. The hook is told after the +// write succeeded; a failed or denied request is never reported. + +// Agent action kinds. +const ( + AgentActionPush = "push" + AgentActionComment = "comment" +) + +// AgentAction is one write the relay made for an agent. +type AgentAction struct { + Agent string + Kind string + Repo string + Number int + Branch string + SHA string + At time.Time +} + +// AgentActionHook is told of each AgentAction. +type AgentActionHook func(AgentAction) + +// SetAgentActionHook installs (or with nil, removes) the hook. Safe to call +// before or after the watchers start. +func (c *Client) SetAgentActionHook(fn AgentActionHook) { + if c == nil { + return + } + if fn == nil { + c.agentActionHook.Store(nil) + return + } + c.agentActionHook.Store(&fn) +} + +// notifyAgentAction reports a completed write to the installed hook, if any. +func (c *Client) notifyAgentAction(a AgentAction) { + if c == nil || a.Agent == "" { + return + } + if hook := c.agentActionHook.Load(); hook != nil && *hook != nil { + (*hook)(a) + } +} diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 5a797d038f..dd9c534872 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -374,7 +374,10 @@ type Client struct { prOpenedHook atomic.Pointer[PROpenedHook] // prOpenedDetailHook is the richer sibling of prOpenedHook (body and // handoff summary included), used by PR follow-up resume (#9583). - prOpenedDetailHook atomic.Pointer[PROpenedDetailHook] + prOpenedDetailHook atomic.Pointer[PROpenedDetailHook] + // agentActionHook is told of each push and comment the relay made for an + // agent (agent_action_hook.go). + agentActionHook atomic.Pointer[AgentActionHook] prTerminalObservedHook atomic.Pointer[PRTerminalObservedHook] // prReviewObservedHook and prTerminalReviews: other people's reviews on // terminal PRs, read once per PR by the settle scan (#16116). See diff --git a/src/pkg/github/issue_request_watcher.go b/src/pkg/github/issue_request_watcher.go index 6740e21e7c..394d5beadd 100644 --- a/src/pkg/github/issue_request_watcher.go +++ b/src/pkg/github/issue_request_watcher.go @@ -1075,6 +1075,7 @@ func (c *Client) handleOneIssueRequestFrom(ctx context.Context, path string, src // A deferral on a PR is a decision the activity monitor shows // ("Deferred · waiting on #N"), not an absence of pickup (#17347). c.recordPRDeferral(ctx, req, meta, resp.URL) + c.notifyAgentAction(AgentAction{Agent: req.Agent, Kind: AgentActionComment, Repo: req.Repo, Number: resp.Number, At: nowFn()}) } c.logger.Info("issue-request watcher: request completed", slog.String("repo", req.Repo), slog.String("kind", kind), diff --git a/src/pkg/github/push_branch_request_watcher.go b/src/pkg/github/push_branch_request_watcher.go index 73ec561179..c6bb6b995e 100644 --- a/src/pkg/github/push_branch_request_watcher.go +++ b/src/pkg/github/push_branch_request_watcher.go @@ -435,6 +435,7 @@ func (c *Client) handleOnePushBranchRequest(ctx context.Context, path string, no "force_with_lease", strconv.FormatBool(req.ForceWithLease)) c.writePushBranchResult(path, PushBranchResponse{OK: true, Branch: branch, SHA: sha, Attempts: attempts, At: nowFn().UTC().Format(time.RFC3339)}) _ = os.Remove(path) + c.notifyAgentAction(AgentAction{Agent: req.Agent, Kind: AgentActionPush, Repo: req.Repo, Branch: branch, SHA: sha, At: nowFn()}) c.logger.Info("push-branch-request watcher: branch pushed", slog.String("repo", req.Repo), slog.String("branch", branch), slog.String("sha", sha), slog.String("agent", req.Agent)) diff --git a/src/pkg/kickoutcome/coverage_test.go b/src/pkg/kickoutcome/coverage_test.go new file mode 100644 index 0000000000..42f39b6a13 --- /dev/null +++ b/src/pkg/kickoutcome/coverage_test.go @@ -0,0 +1,155 @@ +package kickoutcome + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +func TestOpenCorruptAndUnreadable(t *testing.T) { + dir := t.TempDir() + bad := filepath.Join(dir, "bad.json") + _ = os.WriteFile(bad, []byte("{not json"), 0o600) + if s, err := Open(bad, nil); err == nil || s == nil || len(s.Agents()) != 0 { + t.Fatalf("corrupt file: %v", err) + } + if s, err := Open(dir, nil); err == nil || s == nil { + t.Fatalf("a directory is not a store: %v", err) + } + if s, err := Open(filepath.Join(dir, "missing.json"), nil); err != nil || s == nil { + t.Fatalf("missing file is an empty store: %v", err) + } +} + +func TestOpenTrimsLoadedRecords(t *testing.T) { + p := filepath.Join(t.TempDir(), "k.json") + s, _ := Open(p, nil) + for i := 0; i < MaxRecordsPerAgent; i++ { + s.Delivered("a", t0.Add(time.Duration(i)*time.Hour)) + } + s2, _ := Open(p, nil) + if len(s2.Records("a", 3)) != 3 || len(s2.Agents()) != 1 { + t.Fatal("limit or agents") + } +} + +func TestAgentsAreBounded(t *testing.T) { + s, _ := Open("", nil) + for i := 0; i < MaxAgents+5; i++ { + s.Delivered("agent"+strconv.Itoa(i), t0.Add(time.Duration(i)*time.Minute)) + } + if n := len(s.Agents()); n != MaxAgents { + t.Fatalf("%d agents", n) + } + if len(s.Records("agent0", 0)) != 0 { + t.Fatal("the oldest agent was kept") + } +} + +func TestPushCommentAndDeclinedSignals(t *testing.T) { + s, _ := Open("", nil) + s.Delivered("a", t0) + s.Pushed("a", "fix/x", "abc123", t0.Add(time.Minute)) + s.Pushed("a", "fix/y", "def456", t0.Add(2*time.Minute)) // first push wins + s.Commented("a", t0.Add(time.Minute)) + s.Declined("a", "I'm declining to execute this", t0.Add(time.Minute)) + s.Declined("a", "again", t0.Add(time.Minute)) // already refused: ignored + s.SetClock(func() time.Time { return t0.Add(5 * time.Minute) }) + d := s.Recent("a", 10) + if len(d) != 1 || d[0].Kind != KindRefused || d[0].RefusalCode != "agent_declined" || !strings.Contains(d[0].Quote, "declining") { + t.Fatalf("%+v", d) + } + r := s.Records("a", 1)[0] + if r.PushBranch != "fix/x" || r.CommentAt == nil { + t.Fatalf("%+v", r) + } + // A push alone derives pushed_commit and keeps branch and sha. + s.Delivered("b", t0) + s.Pushed("b", "fix/x", "abc123", t0.Add(time.Minute)) + b := s.Recent("b", 1)[0] + if b.Kind != KindPushedCommit || b.Branch != "fix/x" || b.SHA != "abc123" || b.Summary != "pushed a commit to fix/x" { + t.Fatalf("%+v", b) + } + s.Delivered("c", t0) + s.Commented("c", t0.Add(time.Minute)) + if c := s.Recent("c", 1)[0]; c.Kind != KindCommented || c.Summary != "commented" { + t.Fatalf("%+v", c) + } +} + +func TestSummaries(t *testing.T) { + for kind, want := range map[string]string{ + KindStillRunning: "still running", KindEndedNoVisibleAction: "ended, no visible action", + KindStoodDown: "stood down", KindOpenedPR: "opened a PR", + } { + if got := Summary(Record{}, Outcome{Kind: kind}); got != want { + t.Errorf("%s: %q", kind, got) + } + } + if got := Summary(Record{PushBranch: ""}, Outcome{Kind: KindPushedCommit}); got != "pushed a commit" { + t.Error(got) + } + if got := Summary(Record{RefusalCode: "paused"}, Outcome{Kind: KindRefused}); got != "refused (paused)" { + t.Error(got) + } +} + +func TestLatestAndLatestOf(t *testing.T) { + s, _ := Open("", nil) + s.SetClock(func() time.Time { return t0.Add(time.Minute) }) + s.Delivered("a", t0) + if l := s.Latest(); len(l) != 1 || l["a"].Kind != KindStillRunning { + t.Fatalf("%+v", l) + } + if _, ok := s.LatestOf("nobody"); ok { + t.Fatal("unknown agent") + } + var nilStore *Store + if len(nilStore.Latest()) != 0 || nilStore.Records("a", 0) != nil || nilStore.Agents() != nil { + t.Fatal("nil store") + } + nilStore.Delivered("a", t0) + nilStore.Refused("a", Trigger{}, "paused", "x", t0) + nilStore.TurnEnded("a", "ended", "", t0, t0) + nilStore.Intend("a", Trigger{}) + nilStore.SetClock(time.Now) + nilStore.Declined("a", "x", t0) + nilStore.PROpened("a", "u", 1, t0) + nilStore.Pushed("a", "b", "s", t0) + nilStore.Commented("a", t0) + if v := nilStore.Recent("a", 3); len(v) != 0 { + t.Fatal("nil recent") + } +} + +func TestRefusedNeedsACode(t *testing.T) { + s, _ := Open("", nil) + s.Refused("a", Trigger{Kind: TriggerGovernor}, "", "x", t0) + s.Refused("", Trigger{Kind: TriggerGovernor}, "paused", "x", t0) + if len(s.Agents()) != 0 { + t.Fatal("a refusal with no code or agent was recorded") + } +} + +func TestSavingFailureIsLoggedNotFatal(t *testing.T) { + dir := t.TempDir() + file := filepath.Join(dir, "f") + _ = os.WriteFile(file, []byte("x"), 0o600) + s, _ := Open(filepath.Join(file, "sub", "k.json"), nil) // parent is a file + s.Delivered("a", t0) + if len(s.Records("a", 0)) != 1 { + t.Fatal("the in-memory record was lost with the save") + } +} + +func TestCleanRefAndCap(t *testing.T) { + if got := cleanRef(" a b\tc\x00d ", 10); got != "abcd" { + t.Fatalf("%q", got) + } + if capRunes("abcdef", 0) != "" || capRunes("abc", 5) != "abc" || capRunes("abcdef", 3) != "ab…" { + t.Fatal("capRunes") + } +} diff --git a/src/pkg/kickoutcome/kickoutcome.go b/src/pkg/kickoutcome/kickoutcome.go new file mode 100644 index 0000000000..8ea3f4f31b --- /dev/null +++ b/src/pkg/kickoutcome/kickoutcome.go @@ -0,0 +1,192 @@ +// Package kickoutcome keeps a durable, bounded record of what each kick of an +// agent came to (hivecommons/hive#18916). +// +// "Kick sent" says the agent was told; it does not say whether a pull request +// opened, a commit was pushed, the agent stood down, the hive refused the kick, +// or the turn ended with nothing visible. The Store records, per kick, who or +// what triggered it, when it started and ended, and the raw signals the hive +// already has about it: the turn-end classification, a kick refusal, a pull +// request opened through the relay, a branch pushed or an item commented on +// through the relay. The outcome is DERIVED from those signals when it is read +// (Derive), so a signal that arrives late (the relay opens a pull request after +// the turn ends) upgrades the outcome, and a kick no signal speaks for is +// reported as ended_no_visible_action, never guessed. +// +// Security model: the store is hive-side only. Agents cannot query it, and no +// text it holds is ever put into an agent prompt. The text an agent wrote (a +// stand-down line, a refusal line) is untrusted: it is redacted for tokens, +// stripped of control characters and length-capped on the way in (Quote), and +// the dashboard escapes it on the way out. Log lines carry ids and kinds only. +package kickoutcome + +import ( + "strings" + "time" + "unicode" + + "github.com/hivecommons/hive/crux/logscrub" +) + +// Outcome kinds: what a kick came to. +const ( + KindOpenedPR = "opened_pr" + KindPushedCommit = "pushed_commit" + KindCommented = "commented" + KindStoodDown = "stood_down" + KindRefused = "refused" + KindStillRunning = "still_running" + KindEndedNoVisibleAction = "ended_no_visible_action" +) + +// Trigger kinds: who or what started a kick. +const ( + TriggerDashboard = "dashboard" + TriggerGovernor = "governor" + TriggerWorkflowDispatch = "workflow_dispatch" + // TriggerOther is a kick no caller declared (a meeting or inbox prompt, a + // canary retry): only the runtime's own trigger word is known. + TriggerOther = "other" +) + +// Turn-end kinds the runtime reports (crux.KickOutcome*), mirrored here so the +// package needs no import edge to the runtime. +const ( + turnStandDown = "stand-down" +) + +// Bounds. Every record, string and list the store keeps is capped. +const ( + // MaxRecordsPerAgent is how many kicks are kept per agent: the dashboard + // shows the last ten. + MaxRecordsPerAgent = 10 + // MaxAgents bounds the agents the store tracks. + MaxAgents = 256 + // MaxQuoteRunes caps agent-written text kept in a record. + MaxQuoteRunes = 200 + // MaxActorRunes caps a trigger actor (a login). + MaxActorRunes = 64 + // MaxRefRunes caps a URL, branch or sha. + MaxRefRunes = 300 + // ActionGrace is how long after a turn ended a pull request, push or + // comment is still attributed to it: the relay acts after the turn. + ActionGrace = 15 * time.Minute + // RunningCeiling is how long a kick with no turn-end signal is still + // called running; past it the hive cannot tell and says + // ended_no_visible_action (a restart forgets turns). + RunningCeiling = 2 * time.Hour + // IntentTTL is how long a declared trigger waits for its delivery. + IntentTTL = 2 * time.Minute +) + +// Record is one kick and the raw signals about it. It is what is persisted. +type Record struct { + ID string `json:"id"` + Agent string `json:"agent"` + // TriggerKind is one of the Trigger* kinds; TriggerActor the dashboard + // user's login for a dashboard kick, empty otherwise; TriggerWord the + // runtime's own trigger word. + TriggerKind string `json:"trigger_kind"` + TriggerActor string `json:"trigger_actor,omitempty"` + StartedAt time.Time `json:"started_at"` + // EndedAt and TurnKind are the turn-end signal; TurnReason the agent's + // own line for it (sanitized). + EndedAt *time.Time `json:"ended_at,omitempty"` + TurnKind string `json:"turn_kind,omitempty"` + TurnReason string `json:"turn_reason,omitempty"` + // RefusalCode is a refusal reason code from the kick-refusals docs; + // RefusalReason the quoted text behind it (sanitized). + RefusalCode string `json:"refusal_code,omitempty"` + RefusalReason string `json:"refusal_reason,omitempty"` + // PR, push and comment signals, each with the time it was seen. + PRURL string `json:"pr_url,omitempty"` + PRNumber int `json:"pr_number,omitempty"` + PRAt *time.Time `json:"pr_at,omitempty"` + PushBranch string `json:"push_branch,omitempty"` + PushSHA string `json:"push_sha,omitempty"` + PushAt *time.Time `json:"push_at,omitempty"` + CommentAt *time.Time `json:"comment_at,omitempty"` +} + +// Outcome is what Derive concludes about a record. +type Outcome struct { + Kind string + // At is when the outcome happened (the signal's time, else the turn end, + // else the start). + At time.Time + // Quote is the agent's or the hive's own words behind stood_down and + // refused; empty otherwise. Untrusted. + Quote string +} + +// Derive concludes what a kick came to from its signals alone. latest says it +// is the agent's most recent kick (only that one can still be running). The +// order is the strength of the evidence: a refusal means nothing ran; a pull +// request, push or comment is visible GitHub activity; a stand-down is the +// agent's own statement; a turn that ended with none of those, or a kick that +// can no longer be told apart from one that ended, is ended_no_visible_action. +func Derive(r Record, now time.Time, latest bool) Outcome { + switch { + case r.RefusalCode != "": + return Outcome{Kind: KindRefused, At: r.StartedAt, Quote: r.RefusalReason} + case r.PRAt != nil: + return Outcome{Kind: KindOpenedPR, At: *r.PRAt} + case r.PushAt != nil: + return Outcome{Kind: KindPushedCommit, At: *r.PushAt} + case r.CommentAt != nil: + return Outcome{Kind: KindCommented, At: *r.CommentAt} + case r.EndedAt != nil && r.TurnKind == turnStandDown: + return Outcome{Kind: KindStoodDown, At: *r.EndedAt, Quote: r.TurnReason} + case r.EndedAt != nil: + return Outcome{Kind: KindEndedNoVisibleAction, At: *r.EndedAt} + case latest && now.Sub(r.StartedAt) < RunningCeiling: + return Outcome{Kind: KindStillRunning, At: r.StartedAt} + } + return Outcome{Kind: KindEndedNoVisibleAction, At: r.StartedAt} +} + +// Quote makes text an agent (or a pane) wrote safe to store and show: tokens +// redacted, control characters dropped, whitespace collapsed, length capped. +// It does not escape for HTML: the dashboard does that where it renders. +func Quote(s string) string { + s = logscrub.RedactPaneTokens(s) + var b strings.Builder + space := false + for _, r := range s { + switch { + case unicode.IsSpace(r): + space = b.Len() > 0 + case unicode.IsControl(r) || r == '
' || r == '
': + default: + if space { + b.WriteByte(' ') + space = false + } + b.WriteRune(r) + } + } + return capRunes(b.String(), MaxQuoteRunes) +} + +// capRunes shortens s to at most n runes, marking a cut with an ellipsis. +func capRunes(s string, n int) string { + if n <= 0 { + return "" + } + rs := []rune(s) + if len(rs) <= n { + return s + } + return string(rs[:n-1]) + "…" +} + +// cleanRef bounds an id-like string (login, URL, branch, sha) to printable +// text without whitespace. +func cleanRef(s string, n int) string { + s = strings.Map(func(r rune) rune { + if unicode.IsSpace(r) || unicode.IsControl(r) { + return -1 + } + return r + }, s) + return capRunes(logscrub.RedactPaneTokens(s), n) +} diff --git a/src/pkg/kickoutcome/kickoutcome_test.go b/src/pkg/kickoutcome/kickoutcome_test.go new file mode 100644 index 0000000000..212d006e76 --- /dev/null +++ b/src/pkg/kickoutcome/kickoutcome_test.go @@ -0,0 +1,175 @@ +package kickoutcome + +import ( + "bytes" + "log/slog" + "path/filepath" + "strings" + "testing" + "time" +) + +var t0 = time.Date(2026, 11, 17, 12, 0, 0, 0, time.UTC) + +func TestDeriveOnlyFromRealSignals(t *testing.T) { + r := Record{StartedAt: t0} + if o := Derive(r, t0.Add(time.Minute), true); o.Kind != KindStillRunning { + t.Fatalf("open latest kick: %q", o.Kind) + } + if o := Derive(r, t0.Add(time.Minute), false); o.Kind != KindEndedNoVisibleAction { + t.Fatalf("a kick superseded by a later one cannot be running: %q", o.Kind) + } + if o := Derive(r, t0.Add(RunningCeiling+time.Minute), true); o.Kind != KindEndedNoVisibleAction { + t.Fatalf("past the ceiling the hive cannot tell and must not guess: %q", o.Kind) + } + end := t0.Add(time.Minute) + r.EndedAt, r.TurnKind = &end, "ended" + if o := Derive(r, end, true); o.Kind != KindEndedNoVisibleAction { + t.Fatalf("a turn end with no action: %q", o.Kind) + } + r.TurnKind = "question" + if o := Derive(r, end, true); o.Kind != KindEndedNoVisibleAction || o.Quote != "" { + t.Fatalf("a question is not a stand-down: %+v", o) + } + r.TurnKind, r.TurnReason = "stand-down", "no push rights" + if o := Derive(r, end, true); o.Kind != KindStoodDown || o.Quote != "no push rights" { + t.Fatalf("stand-down: %+v", o) + } + pr := end.Add(time.Minute) + r.PRAt, r.PRNumber = &pr, 9 + if o := Derive(r, pr, true); o.Kind != KindOpenedPR || o.Quote != "" { + t.Fatalf("a real PR outranks the agent's stand-down line: %+v", o) + } + r.RefusalCode = "paused" + if o := Derive(r, pr, true); o.Kind != KindRefused { + t.Fatalf("refusal: %q", o.Kind) + } +} + +func TestQuoteRedactsCapsAndCleans(t *testing.T) { + in := "stand down: token ghp_abcdefghijklmnopqrstuvwxyz0123456789 and sk-ant-abcdef123456 and Bearer abcdefghijklmnop.qrstuvwxyz\x1b[31m\n\tred " + strings.Repeat("x", 500) + q := Quote(in) + for _, leak := range []string{"ghp_abcdefghijklmnopqrstuvwxyz0123456789", "sk-ant-abcdef123456", "\x1b", "\n", "\t"} { + if strings.Contains(q, leak) { + t.Fatalf("quote kept %q: %q", leak, q) + } + } + if n := len([]rune(q)); n > MaxQuoteRunes { + t.Fatalf("quote is %d runes", n) + } +} + +func TestLatePullRequestUpgradesTheOutcome(t *testing.T) { + s, _ := Open("", nil) + s.Delivered("a", t0) + s.TurnEnded("a", "ended", "", t0, t0.Add(5*time.Minute)) + s.SetClock(func() time.Time { return t0.Add(6 * time.Minute) }) + if v, _ := s.LatestOf("a"); v.Kind != KindEndedNoVisibleAction { + t.Fatalf("before the relay acts: %q", v.Kind) + } + s.PROpened("a", "https://github.com/o/r/pull/7", 7, t0.Add(8*time.Minute)) + if v, _ := s.LatestOf("a"); v.Kind != KindOpenedPR || v.Summary != "opened PR #7" { + t.Fatalf("after the relay opened the PR: %+v", v) + } +} + +func TestActionOutsideAnyKickIsNotAttributed(t *testing.T) { + s, _ := Open("", nil) + s.Delivered("a", t0) + s.TurnEnded("a", "ended", "", t0, t0.Add(time.Minute)) + s.PROpened("a", "https://github.com/o/r/pull/7", 7, t0.Add(time.Minute+ActionGrace+time.Minute)) + s.Commented("a", t0.Add(-time.Hour)) + s.SetClock(func() time.Time { return t0.Add(3 * time.Hour) }) + if v, _ := s.LatestOf("a"); v.Kind != KindEndedNoVisibleAction { + t.Fatalf("an unrelated PR was claimed by the kick: %+v", v) + } +} + +func TestRefusedKickNeverCollectsActions(t *testing.T) { + s, _ := Open("", nil) + s.Refused("a", Trigger{Kind: TriggerDashboard, Actor: "alice"}, "paused", "agent a cannot be kicked: it is paused", t0) + s.PROpened("a", "https://github.com/o/r/pull/7", 7, t0.Add(time.Minute)) + rs := s.Records("a", 0) + if len(rs) != 1 || rs[0].PRAt != nil { + t.Fatalf("a refused kick collected a PR: %+v", rs) + } + d := s.Recent("a", 10) + if d[0].Kind != KindRefused || d[0].RefusalCode != "paused" || d[0].TriggerActor != "alice" || d[0].Quote == "" { + t.Fatalf("%+v", d[0]) + } +} + +func TestTriggerAttributionAndOtherDefault(t *testing.T) { + s, _ := Open("", nil) + now := t0 + s.SetClock(func() time.Time { return now }) + s.Intend("a", Trigger{Kind: TriggerDashboard, Actor: "alice"}) + now = t0.Add(time.Second) + s.Delivered("a", now) + now = t0.Add(time.Minute) + s.Delivered("a", now) // the intent was consumed by the first delivery + now = t0.Add(10 * time.Minute) + s.Intend("a", Trigger{Kind: "bogus"}) + s.Delivered("a", now) + rs := s.Records("a", 0) + if rs[2].TriggerKind != TriggerDashboard || rs[2].TriggerActor != "alice" || rs[1].TriggerKind != TriggerOther || rs[0].TriggerKind != TriggerOther { + t.Fatalf("%+v", rs) + } + now = t0.Add(time.Hour) + s.Intend("a", Trigger{Kind: TriggerGovernor}) + now = t0.Add(time.Hour + 2*IntentTTL) + s.Delivered("a", now) + if got := s.Records("a", 1)[0].TriggerKind; got != TriggerOther { + t.Fatalf("a stale intent was claimed: %q", got) + } +} + +func TestTurnEndBelongsToItsOwnKick(t *testing.T) { + s, _ := Open("", nil) + s.Delivered("a", t0) + s.Delivered("a", t0.Add(time.Hour)) + s.TurnEnded("a", "stand-down", "first", t0, t0.Add(time.Minute)) + rs := s.Records("a", 0) + if rs[1].EndedAt == nil || rs[0].EndedAt != nil { + t.Fatalf("turn end landed on the wrong kick: %+v", rs) + } +} + +func TestBoundedAndPersistent(t *testing.T) { + p := filepath.Join(t.TempDir(), "k.json") + s, err := Open(p, nil) + if err != nil { + t.Fatal(err) + } + for i := 0; i < MaxRecordsPerAgent+5; i++ { + s.Delivered("a", t0.Add(time.Duration(i)*time.Hour)) + } + s2, err := Open(p, nil) + if err != nil || len(s2.Records("a", 0)) != MaxRecordsPerAgent { + t.Fatalf("not bounded or not durable: %v %d", err, len(s2.Records("a", 0))) + } +} + +func TestAuditLinesHoldIDsAndKindsOnly(t *testing.T) { + var buf bytes.Buffer + s, _ := Open("", slog.New(slog.NewTextHandler(&buf, nil))) + s.Delivered("a", t0) + s.TurnEnded("a", "stand-down", "SECRET-PHRASE the agent said", t0, t0.Add(time.Minute)) + s.Refused("a", Trigger{Kind: TriggerDashboard, Actor: "alice"}, "paused", "SECRET-PHRASE hive text", t0.Add(time.Hour)) + if buf.Len() == 0 || strings.Contains(buf.String(), "SECRET-PHRASE") || strings.Contains(buf.String(), "alice") { + t.Fatalf("audit log: %q", buf.String()) + } +} + +func TestOnlyStandDownAndRefusedQuote(t *testing.T) { + end := t0.Add(time.Minute) + pr := t0.Add(2 * time.Minute) + r := Record{ID: "k", Agent: "a", StartedAt: t0, EndedAt: &end, TurnKind: "stand-down", TurnReason: "why", PRAt: &pr, PRNumber: 3} + if d := DetailOf(r, pr, true); d.Quote != "" { + t.Fatalf("an opened PR quoted the stand-down line: %+v", d) + } + r.PRAt = nil + if d := DetailOf(r, pr, true); d.Quote != "why" { + t.Fatalf("%+v", d) + } +} diff --git a/src/pkg/kickoutcome/store.go b/src/pkg/kickoutcome/store.go new file mode 100644 index 0000000000..cbf15faebb --- /dev/null +++ b/src/pkg/kickoutcome/store.go @@ -0,0 +1,376 @@ +package kickoutcome + +import ( + "encoding/json" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "sort" + "strconv" + "sync" + "time" +) + +// Trigger says who or what is about to kick an agent. +type Trigger struct { + Kind string + Actor string +} + +type intent struct { + t Trigger + at time.Time +} + +type fileShape struct { + Version int `json:"version"` + Agents map[string][]Record `json:"agents"` +} + +const fileVersion = 1 + +// Store is the durable record of kicks. The zero value is not usable; open one +// with Open. A nil *Store accepts every call and records nothing. +type Store struct { + path string + logger *slog.Logger + now func() time.Time + + mu sync.Mutex + agents map[string][]Record + intents map[string]intent +} + +// Open loads the store at path ("" keeps it in memory). A missing file is an +// empty store; an unreadable or corrupt one is returned empty with the error, +// so the caller can warn and keep recording. +func Open(path string, logger *slog.Logger) (*Store, error) { + s := &Store{path: path, logger: logger, now: time.Now, agents: map[string][]Record{}, intents: map[string]intent{}} + if path == "" { + return s, nil + } + b, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return s, nil + } + if err != nil { + return s, fmt.Errorf("reading kick outcomes %s: %w", path, err) + } + var f fileShape + if err := json.Unmarshal(b, &f); err != nil { + return s, fmt.Errorf("parsing kick outcomes %s: %w", path, err) + } + for a, rs := range f.Agents { + if len(rs) > MaxRecordsPerAgent { + rs = rs[len(rs)-MaxRecordsPerAgent:] + } + if a != "" && len(s.agents) < MaxAgents { + s.agents[a] = rs + } + } + return s, nil +} + +// SetClock replaces the clock; for tests. +func (s *Store) SetClock(now func() time.Time) { + if s != nil && now != nil { + s.now = now + } +} + +// Intend declares who or what is about to kick agent, so the delivery that +// follows is attributed to them. An intent unclaimed after IntentTTL is +// dropped. The runtime reports only a bare trigger word, so a caller that +// knows more says it here. +func (s *Store) Intend(agent string, t Trigger) { + if s == nil || agent == "" { + return + } + s.mu.Lock() + defer s.mu.Unlock() + s.intents[agent] = intent{t: cleanTrigger(t), at: s.now()} +} + +func cleanTrigger(t Trigger) Trigger { + switch t.Kind { + case TriggerDashboard, TriggerGovernor, TriggerWorkflowDispatch: + default: + t.Kind = TriggerOther + } + t.Actor = cleanRef(t.Actor, MaxActorRunes) + return t +} + +// takeIntent returns and clears the live intent for agent. +func (s *Store) takeIntent(agent string, at time.Time) Trigger { + in, ok := s.intents[agent] + delete(s.intents, agent) + if !ok || at.Sub(in.at) > IntentTTL || at.Before(in.at.Add(-IntentTTL)) { + return Trigger{Kind: TriggerOther} + } + return in.t +} + +// Delivered records that a kick was typed into agent at at. +func (s *Store) Delivered(agent string, at time.Time) { + if s == nil || agent == "" { + return + } + s.mu.Lock() + defer s.mu.Unlock() + t := s.takeIntent(agent, at) + r := s.add(agent, t, at) + s.log("kick outcome: started", r, "") +} + +// Refused records a kick the hive did not deliver, with the refusal reason +// code from the kick-refusals docs and the hive's own message. The declared +// trigger is t (an intent is consumed). +func (s *Store) Refused(agent string, t Trigger, code, reason string, at time.Time) { + if s == nil || agent == "" || code == "" { + return + } + s.mu.Lock() + defer s.mu.Unlock() + delete(s.intents, agent) + r := s.add(agent, cleanTrigger(t), at) + end := at + r.EndedAt = &end + r.RefusalCode = cleanRef(code, 40) + r.RefusalReason = Quote(reason) + s.set(agent, r) + s.log("kick outcome: refused", r, "") +} + +// Declined marks the agent's open kick as refused by the agent's own model +// (the agent_declined reason), quoting its line. +func (s *Store) Declined(agent, line string, at time.Time) { + s.update(agent, at, "declined", func(r *Record) bool { + if r.RefusalCode != "" { + return false + } + r.RefusalCode, r.RefusalReason = codeAgentDeclined, Quote(line) + return true + }) +} + +// TurnEnded records that the turn of the kick delivered at kickAt ended at at, +// classified as kind, with the agent's own line reason (sanitized here). +func (s *Store) TurnEnded(agent, kind, reason string, kickAt, at time.Time) { + s.updateKick(agent, kickAt, "ended", func(r *Record) bool { + if r.EndedAt != nil { + return false + } + end := at + r.EndedAt, r.TurnKind, r.TurnReason = &end, cleanRef(kind, 40), Quote(reason) + return true + }) +} + +// PROpened records a pull request the relay opened for agent. +func (s *Store) PROpened(agent, url string, number int, at time.Time) { + s.update(agent, at, "pr", func(r *Record) bool { + if r.PRAt != nil { + return false + } + t := at + r.PRAt, r.PRURL, r.PRNumber = &t, cleanRef(url, MaxRefRunes), number + return true + }) +} + +// Pushed records a branch the relay pushed for agent. +func (s *Store) Pushed(agent, branch, sha string, at time.Time) { + s.update(agent, at, "push", func(r *Record) bool { + if r.PushAt != nil { + return false + } + t := at + r.PushAt, r.PushBranch, r.PushSHA = &t, cleanRef(branch, MaxRefRunes), cleanRef(sha, 64) + return true + }) +} + +// Commented records a comment the relay posted for agent. +func (s *Store) Commented(agent string, at time.Time) { + s.update(agent, at, "comment", func(r *Record) bool { + if r.CommentAt != nil { + return false + } + t := at + r.CommentAt = &t + return true + }) +} + +// codeAgentDeclined is the refusal code of a kick the agent's own model +// refused: that kick ran, unlike one the hive refused to deliver. +const codeAgentDeclined = "agent_declined" + +// update applies fn to the agent's latest kick that an action at at can be +// attributed to: started before at, and either still open or ended no more +// than ActionGrace before. A kick the hive refused never ran, so it is +// skipped; the latest kick that could have run is the only candidate. +func (s *Store) update(agent string, at time.Time, what string, fn func(*Record) bool) { + if s == nil || agent == "" { + return + } + s.mu.Lock() + defer s.mu.Unlock() + rs := s.agents[agent] + for i := len(rs) - 1; i >= 0; i-- { + r := rs[i] + if (r.RefusalCode != "" && r.RefusalCode != codeAgentDeclined) || r.StartedAt.After(at) { + continue + } + switch { + case r.EndedAt != nil && at.Sub(*r.EndedAt) > ActionGrace: + return + case r.EndedAt == nil && at.Sub(r.StartedAt) > RunningCeiling: + return + } + if fn(&r) { + s.set(agent, r) + s.log("kick outcome: signal", r, what) + } + return + } +} + +// updateKick applies fn to the agent's kick that started at kickAt (within +// KickSlack): a turn end belongs to one specific kick, never to a neighbour. +func (s *Store) updateKick(agent string, kickAt time.Time, what string, fn func(*Record) bool) { + if s == nil || agent == "" { + return + } + s.mu.Lock() + defer s.mu.Unlock() + rs := s.agents[agent] + for i := len(rs) - 1; i >= 0; i-- { + r := rs[i] + if r.RefusalCode != "" && r.RefusalCode != codeAgentDeclined { + continue + } + if d := r.StartedAt.Sub(kickAt); d < -KickSlack || d > KickSlack { + continue + } + if fn(&r) { + s.set(agent, r) + s.log("kick outcome: signal", r, what) + } + return + } +} + +// KickSlack is how far the runtime's kick time may be from the time the +// delivery was recorded and still be the same kick. +const KickSlack = 2 * time.Minute + +// add appends a new record for agent and persists. Caller holds mu. +func (s *Store) add(agent string, t Trigger, at time.Time) Record { + r := Record{ID: "k" + strconv.FormatInt(at.UnixNano(), 36), Agent: agent, TriggerKind: t.Kind, TriggerActor: t.Actor, StartedAt: at} + rs := append(s.agents[agent], r) + if len(rs) > MaxRecordsPerAgent { + rs = rs[len(rs)-MaxRecordsPerAgent:] + } + s.agents[agent] = rs + s.trimAgentsLocked() + s.saveLocked() + return r +} + +// set replaces the record with r's id and persists. Caller holds mu. +func (s *Store) set(agent string, r Record) { + rs := s.agents[agent] + for i := range rs { + if rs[i].ID == r.ID { + rs[i] = r + break + } + } + s.saveLocked() +} + +// trimAgentsLocked bounds the number of agents tracked, dropping the ones +// whose latest kick is oldest. +func (s *Store) trimAgentsLocked() { + if len(s.agents) <= MaxAgents { + return + } + type last struct { + name string + at time.Time + } + var all []last + for n, rs := range s.agents { + all = append(all, last{n, rs[len(rs)-1].StartedAt}) + } + sort.Slice(all, func(i, j int) bool { return all[i].at.After(all[j].at) }) + for _, l := range all[MaxAgents:] { + delete(s.agents, l.name) + } +} + +func (s *Store) saveLocked() { + if s.path == "" { + return + } + b, err := json.Marshal(fileShape{Version: fileVersion, Agents: s.agents}) + if err == nil { + err = os.MkdirAll(filepath.Dir(s.path), 0o750) + } + if err == nil { + tmp := s.path + ".tmp" + if err = os.WriteFile(tmp, b, 0o600); err == nil { + err = os.Rename(tmp, s.path) + } + } + if err != nil && s.logger != nil { + s.logger.Warn("kick outcome: saving failed", "error", err) + } +} + +// log writes an audit line with ids and kinds only: never agent text. +func (s *Store) log(msg string, r Record, signal string) { + if s.logger == nil { + return + } + o := Derive(r, s.now(), true) + s.logger.Info(msg, "agent", r.Agent, "kick_id", r.ID, "trigger_kind", r.TriggerKind, "outcome_kind", o.Kind, "signal", signal) +} + +// Records returns the agent's kicks, newest first, at most n (all kept when n +// is not positive). +func (s *Store) Records(agent string, n int) []Record { + if s == nil { + return nil + } + s.mu.Lock() + defer s.mu.Unlock() + rs := s.agents[agent] + out := make([]Record, 0, len(rs)) + for i := len(rs) - 1; i >= 0; i-- { + out = append(out, rs[i]) + } + if n > 0 && len(out) > n { + out = out[:n] + } + return out +} + +// Agents lists the agents with a kick on record. +func (s *Store) Agents() []string { + if s == nil { + return nil + } + s.mu.Lock() + defer s.mu.Unlock() + out := make([]string, 0, len(s.agents)) + for a := range s.agents { + out = append(out, a) + } + sort.Strings(out) + return out +} diff --git a/src/pkg/kickoutcome/view.go b/src/pkg/kickoutcome/view.go new file mode 100644 index 0000000000..0e2ef9b1d5 --- /dev/null +++ b/src/pkg/kickoutcome/view.go @@ -0,0 +1,128 @@ +package kickoutcome + +import ( + "fmt" + "time" +) + +// View is one kick as the read API shows it. Summary is the one-line form +// every role may see; the rest is detail for owner and read-write roles. +type View struct { + ID string `json:"id"` + Agent string `json:"agent"` + Kind string `json:"kind"` + Summary string `json:"summary"` + // At is when the outcome happened (see Outcome.At). + At time.Time `json:"at"` +} + +// Detail is a View with the record behind it. +type Detail struct { + View + TriggerKind string `json:"trigger_kind"` + TriggerActor string `json:"trigger_actor,omitempty"` + StartedAt time.Time `json:"started_at"` + EndedAt *time.Time `json:"ended_at,omitempty"` + PRURL string `json:"pr_url,omitempty"` + PRNumber int `json:"pr_number,omitempty"` + Branch string `json:"branch,omitempty"` + SHA string `json:"sha,omitempty"` + // RefusalCode is the kick-refusals docs reason code of a refused kick. + RefusalCode string `json:"refusal_code,omitempty"` + // Quote is the agent's own stand-down line, or the quoted text behind a + // refusal. Untrusted: redacted and capped here, escaped where shown. + Quote string `json:"quote,omitempty"` +} + +// Summary is the one-line form of an outcome, without its age (the reader +// renders the age from At so it does not go stale between polls). +func Summary(r Record, o Outcome) string { + switch o.Kind { + case KindOpenedPR: + if r.PRNumber > 0 { + return fmt.Sprintf("opened PR #%d", r.PRNumber) + } + return "opened a PR" + case KindPushedCommit: + if r.PushBranch != "" { + return "pushed a commit to " + r.PushBranch + } + return "pushed a commit" + case KindCommented: + return "commented" + case KindStoodDown: + return "stood down" + case KindRefused: + return "refused (" + r.RefusalCode + ")" + case KindStillRunning: + return "still running" + } + return "ended, no visible action" +} + +// ViewOf derives the summary view of a record. +func ViewOf(r Record, now time.Time, latest bool) View { + o := Derive(r, now, latest) + return View{ID: r.ID, Agent: r.Agent, Kind: o.Kind, Summary: Summary(r, o), At: o.At} +} + +// DetailOf derives the full view of a record. +func DetailOf(r Record, now time.Time, latest bool) Detail { + o := Derive(r, now, latest) + d := Detail{ + View: View{ID: r.ID, Agent: r.Agent, Kind: o.Kind, Summary: Summary(r, o), At: o.At}, + TriggerKind: r.TriggerKind, + TriggerActor: r.TriggerActor, + StartedAt: r.StartedAt, + EndedAt: r.EndedAt, + RefusalCode: r.RefusalCode, + } + switch o.Kind { + case KindOpenedPR: + d.PRURL, d.PRNumber = r.PRURL, r.PRNumber + case KindPushedCommit: + d.Branch, d.SHA = r.PushBranch, r.PushSHA + case KindStoodDown, KindRefused: + // Only these two quote text, re-capped on the way out. + d.Quote = Quote(o.Quote) + } + return d +} + +// Latest is the most recent kick of every agent, as summary views. +func (s *Store) Latest() map[string]View { + out := map[string]View{} + now := s.clock() + for _, a := range s.Agents() { + if rs := s.Records(a, 1); len(rs) > 0 { + out[a] = ViewOf(rs[0], now, true) + } + } + return out +} + +// Recent is the agent's last n kicks as detail views, newest first. +func (s *Store) Recent(agent string, n int) []Detail { + now := s.clock() + var out []Detail + for i, r := range s.Records(agent, n) { + out = append(out, DetailOf(r, now, i == 0)) + } + return out +} + +// LatestOf is the agent's most recent kick as a summary view. +func (s *Store) LatestOf(agent string) (View, bool) { + rs := s.Records(agent, 1) + if len(rs) == 0 { + return View{}, false + } + return ViewOf(rs[0], s.clock(), true), true +} + +func (s *Store) clock() time.Time { + if s == nil { + return time.Now() + } + return s.now() +}