Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/added-operator-action-ledger.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Activity Monitor row actions now persist their operator, outcome, note, head and stage across reloads, expose the latest action and retained count on tracker rows, and provide a per-item history API.
285 changes: 143 additions & 142 deletions src/docs/api-reference.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions src/pkg/dashboard/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ func (s *Server) RegisterAPI(deps *Dependencies) {
s.mux.HandleFunc("GET /api/repos/pauses", s.handleRepoPauses)
s.mux.HandleFunc("GET /api/repos/{owner}/{repo}/hold-permission", s.handleRepoHoldPermission)
s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/hold", s.handleRepoItemHold)
s.mux.HandleFunc("GET /api/repos/{owner}/{repo}/items/{number}", s.handleRepoItem)
s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/decision", s.handleRepoItemDecision)
s.mux.HandleFunc("POST /api/repos/{owner}/{repo}/items/{number}/decide-delegated", s.handleRepoItemDecideDelegated)
s.mux.HandleFunc("GET /api/repos/{owner}/{repo}/items/{number}/decide-delegated", s.handleRepoItemDecideDelegatedStatus)
Expand Down
7 changes: 7 additions & 0 deletions src/pkg/dashboard/api_repo_hold.go
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,13 @@ func (s *Server) handleRepoItemHold(w http.ResponseWriter, r *http.Request) {
jsonError(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
action := "release"
if body.Held {
action = "hold"
}
var finish func()
w, finish = s.observeOperatorAction(w, r, owner+"/"+repoName, number, action, "")
defer finish()
ctx := context.Background()
if s.deps.Ctx != nil {
ctx = s.deps.Ctx
Expand Down
3 changes: 3 additions & 0 deletions src/pkg/dashboard/api_repo_item_accept_triage.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@ func (s *Server) handleRepoItemAcceptTriage(w http.ResponseWriter, r *http.Reque
jsonError(w, "GitHub client not configured", http.StatusServiceUnavailable)
return
}
var finish func()
w, finish = s.observeOperatorAction(w, r, owner+"/"+repoName, number, "accept-triage", "")
defer finish()
ctx := context.Background()
if s.deps.Ctx != nil {
ctx = s.deps.Ctx
Expand Down
7 changes: 7 additions & 0 deletions src/pkg/dashboard/api_repo_item_decide_delegated.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,11 @@ func (s *Server) handleRepoItemDecideDelegated(w http.ResponseWriter, r *http.Re
ID: key + "@" + strconv.FormatInt(now.UnixNano(), 36), Repo: repoFull, Number: number, Type: itemType,
Status: delegatedJobStatusRunning, Requester: user, StartedAt: now, Marker: delegatedecision.Marker(s.delegateHiveID()),
}
entry := s.newOperatorAction(repoFull, number, user, "decide:delegate", body.Reason)
snapshot, started := s.delegatedJobs.start(key, job, now)
if !started {
entry.Outcome = "a delegated decision is already running"
s.recordOperatorAction(repoFull, number, entry)
w.WriteHeader(http.StatusConflict)
jsonResponse(w, snapshot)
return
Expand All @@ -228,6 +231,10 @@ func (s *Server) handleRepoItemDecideDelegated(w http.ResponseWriter, r *http.Re
ctx = s.deps.Ctx
}
s.runDelegatedDecision(ctx, key, repoFull, number, itemType, user, mergerRole, body)
if done, ok := s.delegatedJobs.get(key); ok && done.Error != "" {
entry.Outcome = done.Error
}
s.recordOperatorAction(repoFull, number, entry)
}
if delegatedDecisionRunAsync {
go run()
Expand Down
7 changes: 7 additions & 0 deletions src/pkg/dashboard/api_repo_item_decision.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,13 @@ func (s *Server) handleRepoItemDecision(w http.ResponseWriter, r *http.Request)
return
}
decision := strings.ToLower(strings.TrimSpace(body.Decision))
note := strings.TrimSpace(body.Comment)
if body.SupersededBy != "" {
note += "\nSuperseded by: " + body.SupersededBy
}
var finish func()
w, finish = s.observeOperatorAction(w, r, owner+"/"+repoName, number, "decide:"+decision, note)
defer finish()
comment := strings.TrimSpace(body.Comment)
if len(comment) > repoItemDecisionMaxComment {
jsonError(w, fmt.Sprintf("comment exceeds %d characters", repoItemDecisionMaxComment), http.StatusBadRequest)
Expand Down
45 changes: 45 additions & 0 deletions src/pkg/dashboard/api_repos_rescan.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package dashboard

import (
"context"
"encoding/json"
"errors"
"io"
"math"
"net/http"
"strconv"
Expand Down Expand Up @@ -57,6 +60,48 @@ type ReposRescanResult struct {
// already see, and the far more expensive ACMM re-evaluation is ungated too.
// The API budget is protected by repoRescanDebounce, not by a role.
func (s *Server) handleReposRescan(w http.ResponseWriter, r *http.Request) {
// Activity Monitor retries identify their rows; other rescan callers keep
// the existing empty-body contract.
var body struct {
Items []struct {
Repo string `json:"repo"`
Number int `json:"number"`
} `json:"items"`
}
if r.Body != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&body); err != nil && !errors.Is(err, io.EOF) {
jsonError(w, "invalid request body", http.StatusBadRequest)
return
}
}
if len(body.Items) > 500 {
jsonError(w, "too many retry items", http.StatusBadRequest)
return
}
seen := map[string]bool{}
for _, item := range body.Items {
if item.Number <= 0 || !s.prQueueRepoAllowed(item.Repo) {
jsonError(w, "invalid retry item", http.StatusBadRequest)
return
}
}
var finishes []func()
for _, item := range body.Items {
key := item.Repo + "#" + strconv.Itoa(item.Number)
if seen[key] {
continue
}
seen[key] = true
var finish func()
w, finish = s.observeOperatorAction(w, r, item.Repo, item.Number, "retry", "")
finishes = append(finishes, finish)
}
defer func() {
for _, finish := range finishes {
finish()
}
}()

if s.deps == nil || s.deps.RescanReposFunc == nil {
jsonError(w, "repository rescan is not available on this hive", http.StatusServiceUnavailable)
return
Expand Down
3 changes: 3 additions & 0 deletions src/pkg/dashboard/api_review_pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,9 @@ func (s *Server) handleReviewPipelineSendToHuman(w http.ResponseWriter, r *http.
reason = "the review loop is at its safety cap"
}

var finish func()
w, finish = s.observeOperatorAction(w, r, repo, number, "needs-human", reason)
defer finish()
gh := s.deps.GHClient
if err := gh.AddLabels(r.Context(), repo, number, []string{config.DefaultNeedsHumanLabel}); err != nil {
jsonError(w, fmt.Sprintf("applying %s: %v", config.DefaultNeedsHumanLabel, err), http.StatusBadGateway)
Expand Down
198 changes: 198 additions & 0 deletions src/pkg/dashboard/operator_actions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
package dashboard

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
)

const operatorActionCap = 20

// OperatorAction is the durable outcome of an Activity Monitor row action.
type OperatorAction struct {
Action string `json:"action"`
Actor string `json:"actor"`
At time.Time `json:"at"`
Note string `json:"note"`
Outcome string `json:"outcome"`
Head string `json:"head"`
Stage int `json:"stage"`
}

// Serialize read-modify-rename across Server instances.
var operatorActionsMu sync.Mutex

func (s *Server) operatorActionsPath() string {
if s.operatorActionPath != "" {
return s.operatorActionPath
}
return "/data/operator-actions.json"
}

func readOperatorActions(path string) (map[string][]OperatorAction, error) {
entries := map[string][]OperatorAction{}
data, err := os.ReadFile(path)
if os.IsNotExist(err) {
return entries, nil
}
if err != nil {
return nil, err
}
if err := json.Unmarshal(data, &entries); err != nil {
return nil, err
}
if entries == nil {
entries = map[string][]OperatorAction{}
}
return entries, nil
}

func (s *Server) operatorActions(repo string, number int) ([]OperatorAction, error) {
operatorActionsMu.Lock()
defer operatorActionsMu.Unlock()
entries, err := readOperatorActions(s.operatorActionsPath())
if err != nil {
return nil, err
}
out := append([]OperatorAction{}, entries[fmt.Sprintf("%s#%d", strings.ToLower(repo), number)]...)
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
}
return out, nil
}

func (s *Server) appendOperatorAction(repo string, number int, entry OperatorAction) error {
operatorActionsMu.Lock()
defer operatorActionsMu.Unlock()
path := s.operatorActionsPath()
entries, err := readOperatorActions(path)
if err != nil {
return err
} // Never overwrite an unreadable ledger.
key := fmt.Sprintf("%s#%d", strings.ToLower(repo), number)
trail := append(entries[key], entry)
if len(trail) > operatorActionCap {
trail = trail[len(trail)-operatorActionCap:]
}
entries[key] = trail
data, err := json.Marshal(entries)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
if err := os.WriteFile(path+".tmp", data, 0o600); err != nil {
return err
}
return os.Rename(path+".tmp", path)
}

func (s *Server) newOperatorAction(repo string, number int, actor, action, note string) OperatorAction {
entry := OperatorAction{Action: action, Actor: actor, At: time.Now().UTC(), Note: note, Outcome: "ok"}
// Capture the row before the action changes its stage or head.
s.statusMu.RLock()
if s.status != nil {
rows := s.buildStageTracker(s.status, s.stageStoreOrShared(), entry.At)
for _, row := range rows.Items {
if stageTrackerSameRepo(row.Repo, repo) && row.Number == number {
entry.Head, entry.Stage = row.Head, row.Stage
break
}
}
}
s.statusMu.RUnlock()
return entry
}

func (s *Server) recordOperatorAction(repo string, number int, entry OperatorAction) {
if err := s.appendOperatorAction(repo, number, entry); err != nil && s.logger != nil {
s.logger.Warn("failed to persist operator action", "repo", repo, "number", number, "error", err)
}
s.invalidateStageTrackerForWebhook()
}

func (s *Server) attachOperatorActions(items []StageTrackerItem) {
operatorActionsMu.Lock()
entries, err := readOperatorActions(s.operatorActionsPath())
operatorActionsMu.Unlock()
if err != nil {
return
}
for i := range items {
trail := entries[fmt.Sprintf("%s#%d", strings.ToLower(items[i].Repo), items[i].Number)]
items[i].OperatorActionCount = len(trail)
if len(trail) > 0 {
last := trail[len(trail)-1]
items[i].LastOperatorAction = &last
}
}
}

// Observe the existing response without changing its status or body.
type operatorActionResponse struct {
http.ResponseWriter
status int
body bytes.Buffer
}

func (w *operatorActionResponse) WriteHeader(status int) {
if w.status == 0 {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
}
func (w *operatorActionResponse) Write(p []byte) (int, error) {
if w.status == 0 {
w.WriteHeader(http.StatusOK)
}
if w.body.Len() < 16384 {
remaining := 16384 - w.body.Len()
if remaining > len(p) {
remaining = len(p)
}
w.body.Write(p[:remaining])
}
return w.ResponseWriter.Write(p)
}
func (s *Server) observeOperatorAction(w http.ResponseWriter, r *http.Request, repo string, number int, action, note string) (http.ResponseWriter, func()) {
entry := s.newOperatorAction(repo, number, strings.TrimSpace(r.Header.Get("X-Hive-User")), action, note)
response := &operatorActionResponse{ResponseWriter: w}
return response, func() {
if response.status >= 400 {
var body struct {
Error string `json:"error"`
}
_ = json.Unmarshal(response.body.Bytes(), &body)
entry.Outcome = body.Error
if entry.Outcome == "" {
entry.Outcome = http.StatusText(response.status)
}
}
s.recordOperatorAction(repo, number, entry)
}
}

// handleRepoItem serves the retained ledger, newest first.
func (s *Server) handleRepoItem(w http.ResponseWriter, r *http.Request) {
owner, repo, number, ok := s.parseRepoItemPath(w, r)
if !ok {
return
}
if !s.prQueueRepoAllowed(owner + "/" + repo) {
jsonError(w, "repository is not managed by this hive", http.StatusForbidden)
return
}
entries, err := s.operatorActions(owner+"/"+repo, number)
if err != nil {
jsonError(w, "operator action ledger unavailable", http.StatusServiceUnavailable)
return
}
jsonResponse(w, entries)
}
Loading
Loading