diff --git a/changelog.d/changed-activity-parallel-tracks.md b/changelog.d/changed-activity-parallel-tracks.md new file mode 100644 index 0000000000..e3cb7d9c18 --- /dev/null +++ b/changelog.d/changed-activity-parallel-tracks.md @@ -0,0 +1 @@ +- Activity Monitor now shows independent CI and Review columns on each PR, preserving current-head required App/check identity, freshness and each reviewer's own completion receipt. Source repair returns visually to PR in progress only with verified successful source-edit evidence; assignments, administrative writes and owner/adoption waits stay explicit without changing native stages or merge authority. diff --git a/changelog.d/security-activity-code-work-git.md b/changelog.d/security-activity-code-work-git.md new file mode 100644 index 0000000000..bed4a475cb --- /dev/null +++ b/changelog.d/security-activity-code-work-git.md @@ -0,0 +1 @@ +- Harden Activity Monitor source-work verification with credential-free, bounded, read-only Git inspection that cannot execute workspace hooks, filters or helpers; unsupported normalization and unstable repository evidence stay unknown. diff --git a/src/crux/agent/busy_visibility.go b/src/crux/agent/busy_visibility.go index add112ea11..7c52a8638d 100644 --- a/src/crux/agent/busy_visibility.go +++ b/src/crux/agent/busy_visibility.go @@ -41,14 +41,17 @@ const ( const copilotQuestionFormMessage = "Copilot CLI asked the user a question; no human is attached — dismissed with Escape so the kick can be delivered" type transcriptActivityScan struct { - name string - uid int + name string + uid int + target kickTranscriptTarget } type transcriptActivityResult struct { - name string - at time.Time - ok bool + name string + at time.Time + ok bool + codeWork *crux.CodeWork + since time.Time } // transcriptSessionCache remembers, per agent, the events.jsonl mtime last @@ -324,7 +327,7 @@ func (m *Manager) pendingTranscriptActivityScansLocked(now time.Time) []transcri if !agent.lastTranscriptScanAt.IsZero() && now.Sub(agent.lastTranscriptScanAt) < transcriptLivenessScanInterval { continue } - scans = append(scans, transcriptActivityScan{name: agent.Name, uid: agent.UID}) + scans = append(scans, transcriptActivityScan{name: agent.Name, uid: agent.UID, target: m.kickTranscriptTargetLocked(agent)}) } return scans } @@ -367,6 +370,8 @@ func scanTranscriptActivity(scans []transcriptActivityScan, caches map[string]*t defer func() { <-sem }() at, ok := scanAgentTranscript(scan, perAgent[i], now) results[i] = transcriptActivityResult{name: scan.name, at: at, ok: ok} + results[i].codeWork = scanCodeWork(scan.target, perAgent[i], now) + results[i].since = scan.target.since }() } wg.Wait() @@ -385,6 +390,9 @@ func (m *Manager) applyTranscriptActivityResultsLocked(results []transcriptActiv if result.ok { agent.LastTranscriptActivity = result.at } + if agent.LastKick != nil && agent.LastKick.Equal(result.since) { + agent.CodeWork = cloneCodeWork(result.codeWork) + } } } diff --git a/src/crux/agent/code_work.go b/src/crux/agent/code_work.go new file mode 100644 index 0000000000..7ca7517cf5 --- /dev/null +++ b/src/crux/agent/code_work.go @@ -0,0 +1,215 @@ +package agent + +import ( + "context" + "encoding/json" + "io" + "net/url" + "os" + "path/filepath" + "strings" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/crux/pushbroker" +) + +const ( + codeWorkTranscriptLimit = 8 << 20 + codeWorkFreshWindow = 2 * time.Minute + codeWorkGitTimeout = 2 * time.Second +) + +type sourceEdit struct { + path string + at time.Time + started time.Time +} + +type sourceEditCall struct { + paths []string + at time.Time +} + +// ObserveCodeWorkTranscript reads explicit successful edit results, never +// prose or generic shell intentions, then verifies a real source change. +// Unsupported/partial transcripts and unverifiable worktrees stay unknown. +func ObserveCodeWorkTranscript(r io.Reader, workDir string, since, now time.Time) *crux.CodeWork { + if since.IsZero() { + return nil + } + calls := map[string]sourceEditCall{} + var edits []sourceEdit + err := forEachTranscriptLine(io.LimitReader(r, codeWorkTranscriptLimit), func(line []byte) error { + var event copilotTranscriptEvent + if err := json.Unmarshal(line, &event); err != nil { + return err + } + at := parseTranscriptTime(event.Timestamp) + if at.IsZero() || at.Before(since) || at.After(now) { + return nil + } + switch event.Type { + case "assistant.message": + for _, request := range event.Data.ToolRequests { + if request.ToolCallID == "" { + continue + } + calls[request.ToolCallID] = sourceEditCall{paths: sourceEditPaths(request.Name, request.Arguments), at: at} + } + case "tool.execution_start": + if event.Data.ToolCallID == "" { + return nil + } + calls[event.Data.ToolCallID] = sourceEditCall{paths: sourceEditPaths(event.Data.ToolName, event.Data.Arguments), at: at} + case "tool.execution_complete": + if event.Data.ToolCallID == "" || event.Data.Success == nil || !*event.Data.Success || + transcriptText(event.Data.Error) != "" || now.Sub(at) > codeWorkFreshWindow { + return nil + } + call := calls[event.Data.ToolCallID] + for _, path := range call.paths { + edits = append(edits, sourceEdit{path: path, at: at, started: call.at}) + } + delete(calls, event.Data.ToolCallID) + } + return nil + }) + if err != nil { + return nil + } + for i := len(edits) - 1; i >= 0; i-- { + if observation := verifySourceEdit(edits[i], now); observation != nil { + observation.KickAt = since + return observation + } + } + return nil +} + +func sourceEditPaths(name string, arguments json.RawMessage) []string { + var paths []string + switch name { + case "edit", "create", "Edit", "Write": + var args struct { + Path string `json:"path"` + FilePath string `json:"file_path"` + } + if json.Unmarshal(arguments, &args) != nil { + return nil + } + path := args.Path + if path == "" { + path = args.FilePath + } + if filepath.IsAbs(path) { + paths = append(paths, filepath.Clean(path)) + } + case "apply_patch": + var patch string + if json.Unmarshal(arguments, &patch) != nil { + var args struct { + Input string `json:"input"` + Patch string `json:"patch"` + } + if json.Unmarshal(arguments, &args) != nil { + return nil + } + patch = args.Input + if patch == "" { + patch = args.Patch + } + } + for _, line := range strings.Split(patch, "\n") { + for _, prefix := range []string{"*** Update File: ", "*** Add File: "} { + if strings.HasPrefix(line, prefix) { + path := strings.TrimPrefix(line, prefix) + // A tool may have changed CWD since launch. Relative paths + // are intentionally not attributed using a guessed directory. + if filepath.IsAbs(path) { + paths = append(paths, filepath.Clean(path)) + } + } + } + } + } + return paths +} + +func verifySourceEdit(edit sourceEdit, now time.Time) *crux.CodeWork { + info, err := os.Lstat(edit.path) + if err != nil || !info.Mode().IsRegular() || info.ModTime().Before(edit.started) || info.ModTime().After(edit.at) || info.ModTime().After(now) { + return nil + } + + ctx, cancel := context.WithTimeout(context.Background(), codeWorkGitTimeout) + defer cancel() + observation, err := pushbroker.ObserveWorkspaceFile(ctx, edit.path) + if err != nil || observation == nil { + return nil + } + origin := observation.Origin + if strings.HasPrefix(origin, "git@") { + parts := strings.SplitN(origin, ":", 2) + if len(parts) != 2 { + return nil + } + origin = "ssh://" + strings.TrimPrefix(parts[0], "git@") + "/" + parts[1] + } + remote, err := url.Parse(origin) + if err != nil || remote.Hostname() == "" { + return nil + } + repo := strings.TrimSuffix(strings.Trim(remote.Path, "/"), ".git") + if len(strings.Split(repo, "/")) != 2 { + return nil + } + after, err := os.Lstat(edit.path) + if err != nil || !os.SameFile(info, after) || info.Size() != after.Size() || !info.ModTime().Equal(after.ModTime()) { + return nil + } + return &crux.CodeWork{Repo: repo, Head: observation.Head, Path: observation.Path, Source: crux.CodeWorkSource, At: edit.at, ObservedAt: now} +} + +func cloneCodeWork(observation *crux.CodeWork) *crux.CodeWork { + if observation == nil { + return nil + } + copy := *observation + return © +} + +func scanCodeWork(target kickTranscriptTarget, cache *transcriptSessionCache, now time.Time) *crux.CodeWork { + if target.backend != "copilot" || target.since.IsZero() || cache == nil { + return nil + } + // Reuse the existing liveness scan's session index; never repeat the + // potentially large resume-handle walk or scan on dashboard reads. + name := "" + var newest time.Time + ambiguous := false + for session, at := range cache.sessions { + if at.Before(target.since) || at.After(now) || now.Sub(at) > codeWorkFreshWindow { + continue + } + if at.After(newest) { + name, newest, ambiguous = session, at, false + } else if at.Equal(newest) { + ambiguous = true + } + } + if name == "" || ambiguous { + return nil + } + path := filepath.Join(AgentHome(target.agentName, target.uid, "copilot"), ".copilot", "session-state", name, "events.jsonl") + file, err := os.Open(path) + if err != nil { + return nil + } + defer file.Close() + info, err := file.Stat() + if err != nil || info.Size() > codeWorkTranscriptLimit { + return nil + } + return ObserveCodeWorkTranscript(file, target.workDir, target.since, now) +} diff --git a/src/crux/agent/code_work_git_test.go b/src/crux/agent/code_work_git_test.go new file mode 100644 index 0000000000..efaafa6e45 --- /dev/null +++ b/src/crux/agent/code_work_git_test.go @@ -0,0 +1,178 @@ +package agent + +import ( + "os" + "path/filepath" + "testing" +) + +func TestVerifySourceEditRejectsExecutableWorkspaceConfig(t *testing.T) { + for _, key := range []string{ + "core.fsmonitor", "core.hooksPath", "core.askPass", "core.sshCommand", + "diff.external", "diff.fixture.textconv", "filter.fixture.clean", + "filter.fixture.process", "credential.helper", "core.attributesFile", + "include.path", "remote.origin.uploadpack", "core.worktree", + } { + t.Run(key, func(t *testing.T) { + dir, file, _, start, now := codeWorkTestWorktree(t) + marker := filepath.Join(dir, "helper-ran") + script := filepath.Join(dir, "helper") + if err := os.WriteFile(script, []byte("#!/bin/sh\n: > '"+marker+"'\n"), 0700); err != nil { + t.Fatal(err) + } + value := script + switch key { + case "core.hooksPath": + value = filepath.Join(dir, "hooks") + if err := os.Mkdir(value, 0700); err != nil { + t.Fatal(err) + } + for _, hook := range []string{"pre-commit", "post-commit", "post-index-change"} { + if err := os.WriteFile(filepath.Join(value, hook), []byte("#!/bin/sh\n: > '"+marker+"'\n"), 0700); err != nil { + t.Fatal(err) + } + } + case "include.path": + value = filepath.Join(dir, "included-config") + if err := os.WriteFile(value, []byte("[core]\nfsmonitor = "+script+"\n"), 0600); err != nil { + t.Fatal(err) + } + case "credential.helper": + value = "!" + script + case "core.worktree": + value = t.TempDir() + } + if err := os.WriteFile(filepath.Join(dir, ".gitattributes"), []byte("source.go filter=fixture diff=fixture\n"), 0600); err != nil { + t.Fatal(err) + } + codeWorkTestGit(t, dir, "config", key, value) + if got := verifySourceEdit(sourceEdit{path: file, started: start, at: now}, now); got != nil { + t.Fatalf("unsafe workspace invented source work: %+v", got) + } + if _, err := os.Stat(marker); !os.IsNotExist(err) { + t.Fatalf("workspace helper ran or marker unreadable: %v", err) + } + }) + } +} + +func TestVerifySourceEditIgnoresHostileGitEnvironment(t *testing.T) { + dir, file, head, start, now := codeWorkTestWorktree(t) + decoy, _, _, _, _ := codeWorkTestWorktree(t) + codeWorkTestGit(t, decoy, "remote", "set-url", "origin", "https://github.com/wrong/repo.git") + codeWorkTestGit(t, decoy, "add", "source.go") + codeWorkTestGit(t, decoy, "commit", "--quiet", "-s", "-m", "different decoy head") + marker := filepath.Join(dir, "inherited-helper-ran") + script := filepath.Join(dir, "inherited-helper") + if err := os.WriteFile(script, []byte("#!/bin/sh\n: > '"+marker+"'\n"), 0700); err != nil { + t.Fatal(err) + } + config := filepath.Join(dir, "inherited-config") + if err := os.WriteFile(config, []byte("[core]\nfsmonitor = "+script+"\n[diff]\nexternal = "+script+"\n"), 0600); err != nil { + t.Fatal(err) + } + for key, value := range map[string]string{ + "GIT_DIR": filepath.Join(decoy, ".git"), + "GIT_COMMON_DIR": filepath.Join(decoy, ".git"), + "GIT_WORK_TREE": decoy, + "GIT_INDEX_FILE": filepath.Join(decoy, ".git", "index"), + "GIT_OBJECT_DIRECTORY": filepath.Join(decoy, ".git", "objects"), + "GIT_ALTERNATE_OBJECT_DIRECTORIES": filepath.Join(decoy, ".git", "objects"), + "GIT_CONFIG": config, + "GIT_CONFIG_SYSTEM": config, + "GIT_CONFIG_GLOBAL": config, + "GIT_CONFIG_COUNT": "1", + "GIT_CONFIG_KEY_0": "core.fsmonitor", + "GIT_CONFIG_VALUE_0": script, + "GIT_CONFIG_PARAMETERS": "'core.fsmonitor=" + script + "'", + "GIT_TRACE": marker, + "GIT_TRACE_SETUP": marker, + "GIT_EXTERNAL_DIFF": script, + "GIT_SSH_COMMAND": script, + "GIT_ASKPASS": script, + "GIT_PROXY_COMMAND": script, + "GIT_EXEC_PATH": decoy, + "GIT_NAMESPACE": "decoy", + "GIT_REPLACE_REF_BASE": "refs/decoy/", + "GIT_NO_REPLACE_OBJECTS": "0", + "GIT_OPTIONAL_LOCKS": "1", + "GIT_ATTR_SOURCE": "refs/heads/decoy", + } { + t.Setenv(key, value) + } + got := verifySourceEdit(sourceEdit{path: file, started: start, at: now}, now) + if got == nil || got.Repo != "org/repo" || got.Head != head || got.Path != "source.go" || !got.At.Equal(now) || !got.ObservedAt.Equal(now) { + t.Fatalf("inherited Git state retargeted actual repository/head/path: %+v", got) + } + if _, err := os.Stat(marker); !os.IsNotExist(err) { + t.Fatalf("inherited Git helper/trace executed or marker unreadable: %v", err) + } + // Keep the receipt and file timestamp valid: only actual content changes + // distinguish this negative, even while the decoy worktree is dirty. + if err := os.WriteFile(file, []byte("package before\n"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(file, start, start); err != nil { + t.Fatal(err) + } + if got := verifySourceEdit(sourceEdit{path: file, started: start, at: now}, now); got != nil { + t.Fatalf("unchanged real file borrowed decoy source work: %+v", got) + } +} + +func TestVerifySourceEditNormalizationRemainsUnknown(t *testing.T) { + for _, tc := range []struct { + name string + configKey string + value string + attribute string + }{ + {name: "autocrlf", configKey: "core.autocrlf", value: "true"}, + {name: "eol", configKey: "core.eol", value: "crlf"}, + {name: "text", attribute: "text=auto"}, + {name: "eol attribute", attribute: "eol=lf"}, + {name: "ident", attribute: "ident"}, + {name: "encoding", attribute: "working-tree-encoding=UTF-16"}, + {name: "legacy crlf", attribute: "crlf"}, + } { + t.Run(tc.name, func(t *testing.T) { + dir, file, _, start, now := codeWorkTestWorktree(t) + if tc.configKey != "" { + codeWorkTestGit(t, dir, "config", tc.configKey, tc.value) + } + if tc.attribute != "" { + if err := os.WriteFile(filepath.Join(dir, ".gitattributes"), []byte("source.go "+tc.attribute+"\n"), 0600); err != nil { + t.Fatal(err) + } + } + if got := verifySourceEdit(sourceEdit{path: file, started: start, at: now}, now); got != nil { + t.Fatalf("unsupported normalization invented a verified Git change: %+v", got) + } + }) + } +} + +func TestVerifySourceEditUntrackedIgnoredAndSSHOrigin(t *testing.T) { + dir, file, head, start, now := codeWorkTestWorktree(t) + codeWorkTestGit(t, dir, "remote", "set-url", "origin", "git@github.com:org/repo.git") + got := verifySourceEdit(sourceEdit{path: file, started: start, at: now}, now) + if got == nil || got.Repo != "org/repo" || got.Head != head { + t.Fatalf("actual SCP origin lost provenance: %+v", got) + } + added := filepath.Join(dir, "added.go") + if err := os.WriteFile(added, []byte("package added\n"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(added, start, start); err != nil { + t.Fatal(err) + } + if got := verifySourceEdit(sourceEdit{path: added, started: start, at: now}, now); got == nil || got.Path != "added.go" || got.Head != head { + t.Fatalf("nonignored source creation lost actual head/path: %+v", got) + } + if err := os.WriteFile(filepath.Join(dir, ".gitignore"), []byte("added.go\n"), 0600); err != nil { + t.Fatal(err) + } + if got := verifySourceEdit(sourceEdit{path: added, started: start, at: now}, now); got != nil { + t.Fatalf("ignored file invented source work: %+v", got) + } +} diff --git a/src/crux/agent/code_work_test.go b/src/crux/agent/code_work_test.go new file mode 100644 index 0000000000..e14825513c --- /dev/null +++ b/src/crux/agent/code_work_test.go @@ -0,0 +1,263 @@ +package agent + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/crux" +) + +func TestCodeWorkSuccessfulEditRequiresActualWorktreeChange(t *testing.T) { + dir, file, head, start, now := codeWorkTestWorktree(t) + since := now.Add(-time.Minute) + args, _ := json.Marshal(map[string]string{"path": file}) + transcript := func(name, success string, arguments []byte) string { + return `{"type":"tool.execution_start","timestamp":"` + start.Format(time.RFC3339Nano) + + `","data":{"toolCallId":"edit-1","toolName":"` + name + `","arguments":` + string(arguments) + `}}` + "\n" + + `{"type":"tool.execution_complete","timestamp":"` + now.Format(time.RFC3339Nano) + + `","data":{"toolCallId":"edit-1","success":` + success + `}}` + "\n" + } + got := ObserveCodeWorkTranscript(strings.NewReader(transcript("edit", "true", args)), dir, since, now) + if got == nil || got.Repo != "org/repo" || got.Head != head || got.Path != "source.go" || !got.KickAt.Equal(since) { + t.Fatalf("verified edit not observed: %+v", got) + } + for _, name := range []string{"bash", "read", "claim", "review_request"} { + if got := ObserveCodeWorkTranscript(strings.NewReader(transcript(name, "true", args)), dir, since, now); got != nil { + t.Fatalf("%s invented source work: %+v", name, got) + } + } + for _, success := range []string{"false", "null"} { + if got := ObserveCodeWorkTranscript(strings.NewReader(transcript("edit", success, args)), dir, since, now); got != nil { + t.Fatalf("unsuccessful/unknown result invented source work: %+v", got) + } + } + relative, _ := json.Marshal(map[string]string{"path": "source.go"}) + if got := ObserveCodeWorkTranscript(strings.NewReader(transcript("edit", "true", relative)), dir, since, now); got != nil { + t.Fatal("a guessed current directory attributed an edit") + } + codeWorkTestGit(t, dir, "checkout", "--", "source.go") + if err := os.Chtimes(file, start, start); err != nil { + t.Fatal(err) + } + if got := ObserveCodeWorkTranscript(strings.NewReader(transcript("edit", "true", args)), dir, since, now); got != nil { + t.Fatal("a successful receipt without actual source changes invented work") + } +} + +func TestCodeWorkToolPaths(t *testing.T) { + dir := t.TempDir() + file := filepath.Join(dir, "source.go") + added := filepath.Join(dir, "added.go") + patch := "*** Begin Patch\n*** Update File: " + file + "\n*** Add File: " + added + + "\n*** Update File: relative.go\n*** Delete File: " + file + "\n*** End Patch" + args := func(value any) json.RawMessage { + t.Helper() + data, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + return data + } + for _, tc := range []struct { + name string + tool string + args json.RawMessage + want []string + }{ + {"edit path", "edit", args(map[string]string{"path": file}), []string{file}}, + {"edit file_path", "Edit", args(map[string]string{"file_path": file}), []string{file}}, + {"create path", "create", args(map[string]string{"path": file}), []string{file}}, + {"write file_path", "Write", args(map[string]string{"file_path": file}), []string{file}}, + {"malformed edit", "edit", json.RawMessage("{"), nil}, + {"relative edit", "edit", args(map[string]string{"path": "source.go"}), nil}, + {"patch string", "apply_patch", args(patch), []string{file, added}}, + {"patch input", "apply_patch", args(map[string]string{"input": patch}), []string{file, added}}, + {"patch field", "apply_patch", args(map[string]string{"patch": patch}), []string{file, added}}, + {"malformed patch", "apply_patch", json.RawMessage("{"), nil}, + {"shell is not edit proof", "bash", args(map[string]string{"path": file}), nil}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := sourceEditPaths(tc.tool, tc.args); !reflect.DeepEqual(got, tc.want) { + t.Fatalf("source paths=%v want=%v", got, tc.want) + } + }) + } +} + +func TestCodeWorkTranscriptRejectsInvalidReceipts(t *testing.T) { + dir, file, head, start, now := codeWorkTestWorktree(t) + since := now.Add(-2 * codeWorkFreshWindow) + args := map[string]string{"path": file} + request := func(at time.Time, id string) string { + return codeWorkTestEvent(t, "tool.execution_start", at, map[string]any{ + "toolCallId": id, "toolName": "edit", "arguments": args, + }) + } + result := func(at time.Time, receipt map[string]any) string { + return codeWorkTestEvent(t, "tool.execution_complete", at, receipt) + } + receipt := map[string]any{"toolCallId": "edit-1", "success": true} + complete := result(now, receipt) + assistant := codeWorkTestEvent(t, "assistant.message", start, map[string]any{ + "toolRequests": []map[string]any{ + {"toolCallId": "", "name": "edit", "arguments": args}, + {"toolCallId": "edit-1", "name": "edit", "arguments": args}, + }, + }) + stale := now.Add(-codeWorkFreshWindow - time.Second) + for _, tc := range []struct { + name string + transcript string + since time.Time + want bool + }{ + {"assistant request", assistant + complete, since, true}, + {"unknown kick", assistant + complete, time.Time{}, false}, + {"missing request id", request(start, "") + complete, since, false}, + {"missing result id", request(start, "edit-1") + result(now, map[string]any{"success": true}), since, false}, + {"error despite success", request(start, "edit-1") + result(now, map[string]any{"toolCallId": "edit-1", "success": true, "error": "edit denied"}), since, false}, + {"missing timestamp", request(start, "edit-1") + result(time.Time{}, receipt), since, false}, + {"before kick", request(since.Add(-time.Second), "edit-1") + result(since.Add(-time.Second), receipt), since, false}, + {"future result", request(start, "edit-1") + result(now.Add(time.Second), receipt), since, false}, + {"stale receipt", request(stale.Add(-time.Second), "edit-1") + result(stale, receipt), since, false}, + {"corrupt record", "{\n" + assistant + complete, since, false}, + } { + t.Run(tc.name, func(t *testing.T) { + got := ObserveCodeWorkTranscript(strings.NewReader(tc.transcript), dir, tc.since, now) + if (got != nil) != tc.want { + t.Fatalf("observed=%+v want source work=%v", got, tc.want) + } + if got != nil && (got.Repo != "org/repo" || got.Head != head || got.Path != "source.go" || + got.Source != crux.CodeWorkSource || !got.KickAt.Equal(since) || !got.At.Equal(now) || !got.ObservedAt.Equal(now)) { + t.Fatalf("receipt provenance lost: %+v", got) + } + }) + } +} + +func TestScanCodeWorkUsesOnlyUnambiguousCurrentSession(t *testing.T) { + dir, file, head, start, now := codeWorkTestWorktree(t) + home := t.TempDir() + t.Setenv("HOME", home) + since := now.Add(-2 * codeWorkFreshWindow) + target := kickTranscriptTarget{agentName: "fixer", backend: "copilot", workDir: dir, since: since} + path := filepath.Join(home, ".copilot", "session-state", "current", "events.jsonl") + if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + t.Fatal(err) + } + transcript := codeWorkTestEvent(t, "tool.execution_start", start, map[string]any{ + "toolCallId": "edit-1", "toolName": "edit", "arguments": map[string]string{"path": file}, + }) + codeWorkTestEvent(t, "tool.execution_complete", now, map[string]any{"toolCallId": "edit-1", "success": true}) + if err := os.WriteFile(path, []byte(transcript), 0600); err != nil { + t.Fatal(err) + } + cache := &transcriptSessionCache{sessions: map[string]time.Time{ + "current": now, + "older": start, + "before": since.Add(-time.Second), + "stale": now.Add(-codeWorkFreshWindow - time.Second), + "future": now.Add(time.Second), + }} + got := scanCodeWork(target, cache, now) + if got == nil || got.Repo != "org/repo" || got.Head != head || !got.KickAt.Equal(since) || + got.Path != "source.go" || got.Source != crux.CodeWorkSource || !got.At.Equal(now) || !got.ObservedAt.Equal(now) { + t.Fatalf("current cached session lost verified source work: %+v", got) + } + cache.sessions["tied"] = now + if got := scanCodeWork(target, cache, now); got != nil { + t.Fatalf("tied sessions invented an owner: %+v", got) + } + cache.sessions = map[string]time.Time{"missing": now} + if got := scanCodeWork(target, cache, now); got != nil { + t.Fatalf("missing transcript invented source work: %+v", got) + } + cache.sessions = nil + if got := scanCodeWork(target, cache, now); got != nil { + t.Fatalf("empty session cache invented source work: %+v", got) + } + cache.sessions = map[string]time.Time{"current": now} + if err := os.Truncate(path, codeWorkTranscriptLimit+1); err != nil { + t.Fatal(err) + } + if got := scanCodeWork(target, cache, now); got != nil { + t.Fatalf("oversized transcript was accepted: %+v", got) + } + if got := scanCodeWork(target, nil, now); got != nil { + t.Fatalf("missing cache invented source work: %+v", got) + } + target.backend = "claude" + if got := scanCodeWork(target, cache, now); got != nil { + t.Fatalf("unsupported backend invented source work: %+v", got) + } + target.backend, target.since = "copilot", time.Time{} + if got := scanCodeWork(target, cache, now); got != nil { + t.Fatalf("unknown kick invented source work: %+v", got) + } +} + +func codeWorkTestWorktree(t *testing.T) (string, string, string, time.Time, time.Time) { + t.Helper() + dir := t.TempDir() + codeWorkTestGit(t, dir, "init", "--quiet", "-b", "fixture") + codeWorkTestGit(t, dir, "config", "user.name", "Activity Test") + codeWorkTestGit(t, dir, "config", "user.email", "activity@example.invalid") + codeWorkTestGit(t, dir, "remote", "add", "origin", "https://github.com/org/repo.git") + file := filepath.Join(dir, "source.go") + if err := os.WriteFile(file, []byte("package before\n"), 0600); err != nil { + t.Fatal(err) + } + codeWorkTestGit(t, dir, "add", "source.go") + codeWorkTestGit(t, dir, "commit", "--quiet", "-s", "-m", "fixture") + head := codeWorkTestGit(t, dir, "rev-parse", "HEAD") + now := time.Now().UTC() + start := now.Add(-time.Second) + if err := os.WriteFile(file, []byte("package after\n"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(file, start, start); err != nil { + t.Fatal(err) + } + return dir, file, head, start, now +} + +func codeWorkTestGit(t *testing.T, dir string, args ...string) string { + t.Helper() + command := exec.Command("git", append([]string{"-C", dir}, args...)...) + output, err := command.CombinedOutput() + if err != nil { + t.Fatalf("fixture git %v: %v: %s", args, err, output) + } + return strings.TrimSpace(string(output)) +} + +func codeWorkTestEvent(t *testing.T, kind string, at time.Time, data map[string]any) string { + t.Helper() + event, err := json.Marshal(map[string]any{"type": kind, "timestamp": at.Format(time.RFC3339Nano), "data": data}) + if err != nil { + t.Fatal(err) + } + return string(event) + "\n" +} + +func TestCodeWorkSnapshotsAndCurrentKickIsolation(t *testing.T) { + now := time.Now().UTC() + m := &Manager{agents: map[string]*AgentProcess{"fixer": {Name: "fixer", LastKick: &now}}} + agent := m.agents["fixer"] + observation := &crux.CodeWork{Repo: "org/repo", Head: "head", KickAt: now, At: now} + m.applyTranscriptActivityResultsLocked([]transcriptActivityResult{{name: "fixer", since: now.Add(-time.Second), codeWork: observation}}, now) + if agent.CodeWork != nil { + t.Fatal("a previous kick's source observation was accepted") + } + m.applyTranscriptActivityResultsLocked([]transcriptActivityResult{{name: "fixer", since: now, codeWork: observation}}, now) + snapshot := agent.snapshot() + snapshot.CodeWork.Head = "changed-copy" + if agent.CodeWork.Head != "head" { + t.Fatal("snapshot code-work evidence aliased live runtime state") + } +} diff --git a/src/crux/agent/manager.go b/src/crux/agent/manager.go index 66755a2533..147b93d4d3 100644 --- a/src/crux/agent/manager.go +++ b/src/crux/agent/manager.go @@ -221,6 +221,7 @@ type AgentProcess struct { // LastTranscriptActivity is the newest events.jsonl mtime seen under this // agent's own Copilot session-state tree. LastTranscriptActivity time.Time + CodeWork *crux.CodeWork BusyCondition string BusyConditionMessage string Paused bool diff --git a/src/crux/agent/manager_pane_signals.go b/src/crux/agent/manager_pane_signals.go index ecea740e34..4a7b1f57a8 100644 --- a/src/crux/agent/manager_pane_signals.go +++ b/src/crux/agent/manager_pane_signals.go @@ -85,6 +85,7 @@ func (a *AgentProcess) snapshot() crux.Process { KicksUndeliverable: a.KicksUndeliverable, BusySince: a.BusySince, LastTranscriptActivity: a.LastTranscriptActivity, + CodeWork: cloneCodeWork(a.CodeWork), BusyCondition: a.BusyCondition, BusyConditionMessage: a.BusyConditionMessage, Paused: a.Paused, diff --git a/src/crux/code_work.go b/src/crux/code_work.go new file mode 100644 index 0000000000..fbb9f7019c --- /dev/null +++ b/src/crux/code_work.go @@ -0,0 +1,18 @@ +package crux + +import "time" + +// CodeWork is an observed successful file edit, verified against a dirty +// Git worktree and its actual origin/head. It is not a task intention or a +// generic PR write. The host binds it to the matching dispatch's PR. +type CodeWork struct { + Repo string `json:"repo"` + Head string `json:"head"` + Path string `json:"path"` + Source string `json:"source"` + At time.Time `json:"at"` + ObservedAt time.Time `json:"observed_at"` + KickAt time.Time `json:"kick_at"` +} + +const CodeWorkSource = "successful-edit+verified-git-worktree" diff --git a/src/crux/process.go b/src/crux/process.go index 04d55d8401..d37b33d7a7 100644 --- a/src/crux/process.go +++ b/src/crux/process.go @@ -27,6 +27,7 @@ type Process struct { KicksUndeliverable int BusySince time.Time LastTranscriptActivity time.Time + CodeWork *CodeWork BusyCondition string BusyConditionMessage string Paused bool diff --git a/src/crux/pushbroker/pushbroker.go b/src/crux/pushbroker/pushbroker.go index 8f16252174..112edd1ce8 100644 --- a/src/crux/pushbroker/pushbroker.go +++ b/src/crux/pushbroker/pushbroker.go @@ -1,4 +1,4 @@ -// Package pushbroker performs the trusted, credentialed post-step for sandboxed agents. +// Package pushbroker provides trusted Git inspection and credentialed post-steps for sandboxed agents. package pushbroker import ( @@ -165,6 +165,14 @@ func (b *Broker) rejectHostileWorkspaceConfig(ctx context.Context) error { } remote := strings.ToLower(b.remote()) want := expectedRemoteURL(b.Repo) + offenders := workspaceConfigOffenders(out, remote, &want) + if len(offenders) == 0 { + return nil + } + return fmt.Errorf("pushbroker: refusing to run git in a workspace whose repository config sets %s; a sandbox workspace may only carry the keys a fresh clone writes", strings.Join(offenders, ", ")) +} + +func workspaceConfigOffenders(out []byte, remote string, expectedURL *string) []string { var offenders []string // The record layout is "\x00\n\x00", so splitting on // NUL yields alternating scope and key/value elements. @@ -177,17 +185,14 @@ func (b *Broker) rejectHostileWorkspaceConfig(ctx context.Context) error { } key = strings.ToLower(key) if workspaceConfigKeyAllowed(key, remote) { - if (key == "remote."+remote+".url" || key == "remote."+remote+".pushurl") && !sameRemoteURL(value, want) { + if expectedURL != nil && (key == "remote."+remote+".url" || key == "remote."+remote+".pushurl") && !sameRemoteURL(value, *expectedURL) { offenders = append(offenders, key+"="+value) } continue } offenders = append(offenders, key) } - if len(offenders) == 0 { - return nil - } - return fmt.Errorf("pushbroker: refusing to run git in a workspace whose repository config sets %s; a sandbox workspace may only carry the keys a fresh clone writes", strings.Join(offenders, ", ")) + return offenders } func workspaceConfigKeyAllowed(key, remote string) bool { diff --git a/src/crux/pushbroker/workspace_observation.go b/src/crux/pushbroker/workspace_observation.go new file mode 100644 index 0000000000..81bee2e99d --- /dev/null +++ b/src/crux/pushbroker/workspace_observation.go @@ -0,0 +1,220 @@ +package pushbroker + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" +) + +const workspaceObservationOutputLimit = 64 << 10 + +var errWorkspaceObservation = errors.New("pushbroker: workspace file observation unavailable") + +// WorkspaceFileObservation is read-only evidence of a changed regular file +// against an observed head and origin. It grants no broker mutation authority. +type WorkspaceFileObservation struct { + Path string + Head string + Origin string +} + +// ObserveWorkspaceFile never runs diff, filters, hooks, remote helpers or +// mutation commands. Unchanged/ignored files return nil; unsupported config, +// normalization, unstable metadata and failed reads remain unverifiable. +func ObserveWorkspaceFile(ctx context.Context, path string) (*WorkspaceFileObservation, error) { + observation, err := observeWorkspaceFile(ctx, path, workspaceObservationRunner{}) + if err != nil && ctx.Err() != nil { + return nil, ctx.Err() + } + return observation, err +} + +func observeWorkspaceFile(ctx context.Context, path string, runner CommandRunner) (*WorkspaceFileObservation, error) { + info, err := os.Lstat(path) + if err != nil || !filepath.IsAbs(path) || !info.Mode().IsRegular() { + return nil, errWorkspaceObservation + } + canonicalPath, err := filepath.EvalSymlinks(path) + if err != nil { + return nil, errWorkspaceObservation + } + dir := filepath.Dir(canonicalPath) + for { + if ctx.Err() != nil { + return nil, errWorkspaceObservation + } + if _, err := os.Lstat(filepath.Join(dir, ".git")); err == nil { + break + } else if !os.IsNotExist(err) || filepath.Dir(dir) == dir { + return nil, errWorkspaceObservation + } + dir = filepath.Dir(dir) + } + expectedRoot := dir + env := workspaceObservationEnv(os.Environ(), expectedRoot) + git := func(args ...string) ([]byte, error) { + return runner.Run(ctx, dir, env, "git", append([]string{"--literal-pathspecs"}, args...)...) + } + config, err := git("config", "--list", "-z", "--show-scope") + if err != nil || len(workspaceConfigOffenders(config, DefaultRemote, nil)) != 0 { + return nil, errWorkspaceObservation + } + root, err := git("rev-parse", "--show-toplevel") + if err != nil { + return nil, errWorkspaceObservation + } + canonicalRoot, err := filepath.EvalSymlinks(strings.TrimSpace(string(root))) + if err != nil || canonicalRoot != expectedRoot { + return nil, errWorkspaceObservation + } + relative, err := filepath.Rel(canonicalRoot, canonicalPath) + if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) { + return nil, errWorkspaceObservation + } + relative = filepath.ToSlash(relative) + dir = canonicalRoot + head, err := git("rev-parse", "--verify", "HEAD") + if err != nil { + return nil, errWorkspaceObservation + } + origin, err := git("remote", "get-url", DefaultRemote) + if err != nil || len(bytes.TrimSpace(head)) == 0 || len(bytes.TrimSpace(origin)) == 0 { + return nil, errWorkspaceObservation + } + tree, err := git("ls-tree", "--full-tree", "-z", strings.TrimSpace(string(head)), "--", relative) + if err != nil { + return nil, errWorkspaceObservation + } + if len(tree) == 0 { + files, err := git("ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", relative) + if err != nil { + return nil, errWorkspaceObservation + } + if !slices.Contains(splitNUL(files), relative) { + return nil, nil + } + } else { + records := splitNUL(tree) + if len(records) != 1 { + return nil, errWorkspaceObservation + } + metadata, name, ok := strings.Cut(records[0], "\t") + fields := strings.Fields(metadata) + if !ok || name != relative || len(fields) != 3 || fields[1] != "blob" || + (fields[0] != "100644" && fields[0] != "100755") { + return nil, errWorkspaceObservation + } + // --no-filters is essential: even a config change after the allowlist + // read must not execute a clean/process filter as the observer's UID. + hash, err := git("hash-object", "--no-filters", "--", canonicalPath) + if err != nil { + return nil, errWorkspaceObservation + } + if strings.TrimSpace(string(hash)) == fields[2] { + return nil, nil + } + if !workspaceObservationNormalizationSafe(config) { + return nil, errWorkspaceObservation + } + attributes, err := git("check-attr", "-z", "filter", "text", "eol", "ident", "working-tree-encoding", "crlf", "--", relative) + if err != nil || !workspaceObservationAttributesSafe(attributes, relative) { + return nil, errWorkspaceObservation + } + } + // Bind the result to stable actual metadata, not an earlier worker's head, + // a replacement object, an inherited GIT_DIR, or a changing source path. + for _, check := range []struct { + args []string + want []byte + }{ + {[]string{"rev-parse", "--show-toplevel"}, root}, + {[]string{"rev-parse", "--verify", "HEAD"}, head}, + {[]string{"remote", "get-url", DefaultRemote}, origin}, + {[]string{"config", "--list", "-z", "--show-scope"}, config}, + } { + got, err := git(check.args...) + if err != nil || !bytes.Equal(got, check.want) { + return nil, errWorkspaceObservation + } + } + after, err := os.Lstat(path) + resolved, resolveErr := filepath.EvalSymlinks(path) + if ctx.Err() != nil || err != nil || resolveErr != nil || resolved != canonicalPath || !after.Mode().IsRegular() || + !os.SameFile(info, after) || info.Size() != after.Size() || !info.ModTime().Equal(after.ModTime()) { + return nil, errWorkspaceObservation + } + return &WorkspaceFileObservation{Path: relative, Head: strings.TrimSpace(string(head)), Origin: strings.TrimSpace(string(origin))}, nil +} + +func workspaceObservationEnv(env []string, root string) []string { + env = slices.DeleteFunc(PushEnv(env), func(entry string) bool { + return strings.HasPrefix(entry, "GIT_") || strings.HasPrefix(entry, pushTokenEnvVar+"=") + }) + // The manager inspects an agent-owned checkout. Trust only this discovered + // canonical worktree, never a global safe.directory wildcard. + overrides := append(workspaceConfigOverrides(DefaultRemote, ""), + [2]string{"core.attributesFile", os.DevNull}, [2]string{"safe.directory", root}) + env = append(env, configEnv(overrides)...) + return append(env, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_SYSTEM="+os.DevNull, "GIT_CONFIG_GLOBAL="+os.DevNull, + "GIT_TERMINAL_PROMPT=0", "GIT_OPTIONAL_LOCKS=0", "GIT_NO_REPLACE_OBJECTS=1", + "GIT_NO_LAZY_FETCH=1", "GIT_ALLOW_PROTOCOL=", "GIT_ATTR_NOSYSTEM=1") +} + +func workspaceObservationNormalizationSafe(config []byte) bool { + fields := strings.Split(string(config), "\x00") + for i := 0; i+1 < len(fields); i += 2 { + key, value, _ := strings.Cut(fields[i+1], "\n") + switch strings.ToLower(key) { + case "core.autocrlf": + if value != "false" && value != "0" { + return false + } + case "core.eol": + return false + } + } + return true +} + +func workspaceObservationAttributesSafe(out []byte, path string) bool { + fields := splitNUL(out) + const attributeCount = 6 + const fieldsPerAttribute = 3 + if len(fields) != attributeCount*fieldsPerAttribute { + return false + } + for i := 0; i < len(fields); i += fieldsPerAttribute { + if fields[i] != path || (fields[i+2] != "unspecified" && fields[i+2] != "unset") { + return false + } + } + return true +} + +type workspaceObservationRunner struct{} + +func (workspaceObservationRunner) Run(ctx context.Context, dir string, env []string, name string, args ...string) ([]byte, error) { + command := exec.CommandContext(ctx, name, args...) + command.Dir, command.Env = dir, env + var output workspaceObservationOutput + command.Stdout, command.Stderr = &output, io.Discard + err := command.Run() + return output.buffer.Bytes(), err +} + +type workspaceObservationOutput struct { + buffer bytes.Buffer +} + +func (out *workspaceObservationOutput) Write(p []byte) (int, error) { + if len(p) > workspaceObservationOutputLimit-out.buffer.Len() { + return 0, errWorkspaceObservation + } + return out.buffer.Write(p) +} diff --git a/src/crux/pushbroker/workspace_observation_test.go b/src/crux/pushbroker/workspace_observation_test.go new file mode 100644 index 0000000000..f52ee796a1 --- /dev/null +++ b/src/crux/pushbroker/workspace_observation_test.go @@ -0,0 +1,387 @@ +package pushbroker + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +type workspaceObservationTestRunner func(context.Context, string, []string, string, ...string) ([]byte, error) + +func (run workspaceObservationTestRunner) Run(ctx context.Context, dir string, env []string, name string, args ...string) ([]byte, error) { + return run(ctx, dir, env, name, args...) +} + +func workspaceObservationTestFile(t *testing.T, name string) (string, string) { + t.Helper() + dir := initRepo(t) + runGit(t, dir, "remote", "add", "origin", "https://github.com/org/repo.git") + writeCommit(t, dir, name, "before\n") + path := filepath.Join(dir, name) + if err := os.WriteFile(path, []byte("after\n"), 0600); err != nil { + t.Fatal(err) + } + return dir, path +} + +func TestWorkspaceObservationEnvironment(t *testing.T) { + root := t.TempDir() + env := workspaceObservationEnv([]string{ + "KEEP=ordinary", "GITHUB_TOKEN=secret", "GH_TOKEN=secret", "HIVE_PUSH_TOKEN=secret", + "SSH_ASKPASS=helper", "GIT_DIR=elsewhere", "GIT_CONFIG_COUNT=1", + "GIT_CONFIG_KEY_0=core.fsmonitor", "GIT_CONFIG_VALUE_0=helper", "GIT_TRACE=secret", + "GIT_EXTERNAL_DIFF=helper", "GIT_OBJECT_DIRECTORY=elsewhere", "GIT_NO_REPLACE_OBJECTS=0", + }, root) + for _, entry := range env { + if strings.Contains(entry, "secret") || strings.Contains(entry, "helper") && !strings.Contains(entry, "credential.helper") || + strings.Contains(entry, "elsewhere") { + t.Fatalf("untrusted inherited environment survived: %q", entry) + } + } + for _, want := range []string{ + "KEEP=ordinary", "GIT_CONFIG_COUNT=6", "GIT_CONFIG_KEY_0=core.hooksPath", "GIT_CONFIG_VALUE_0=" + os.DevNull, + "GIT_CONFIG_KEY_1=core.fsmonitor", "GIT_CONFIG_VALUE_1=false", "GIT_CONFIG_KEY_2=credential.helper", + "GIT_CONFIG_VALUE_2=", "GIT_CONFIG_KEY_3=commit.gpgsign", "GIT_CONFIG_VALUE_3=false", + "GIT_CONFIG_KEY_4=core.attributesFile", "GIT_CONFIG_VALUE_4=" + os.DevNull, + "GIT_CONFIG_KEY_5=safe.directory", "GIT_CONFIG_VALUE_5=" + root, + "GIT_NO_REPLACE_OBJECTS=1", "GIT_NO_LAZY_FETCH=1", "GIT_ALLOW_PROTOCOL=", + "GIT_CONFIG_SYSTEM=" + os.DevNull, "GIT_CONFIG_GLOBAL=" + os.DevNull, + "GIT_OPTIONAL_LOCKS=0", "GIT_TERMINAL_PROMPT=0", "GIT_ATTR_NOSYSTEM=1", + } { + if !slices.Contains(env, want) { + t.Errorf("missing read-only environment entry %q", want) + } + } +} + +func TestWorkspaceObservationOutputBoundAndCancellation(t *testing.T) { + var out workspaceObservationOutput + if _, err := io.Copy(&out, strings.NewReader(strings.Repeat("x", workspaceObservationOutputLimit))); err != nil { + t.Fatal(err) + } + if _, err := out.Write([]byte("one byte too many")); !errors.Is(err, errWorkspaceObservation) || out.buffer.Len() != workspaceObservationOutputLimit { + t.Fatalf("output cap bypassed: bytes=%d error=%v", out.buffer.Len(), err) + } + _, path := workspaceObservationTestFile(t, "source.go") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if got, err := ObserveWorkspaceFile(ctx, path); got != nil || !errors.Is(err, context.Canceled) { + t.Fatalf("cancellation lost: observation=%+v error=%v", got, err) + } + if got, err := ObserveWorkspaceFile(context.Background(), path+".missing"); got != nil || !errors.Is(err, errWorkspaceObservation) { + t.Fatalf("missing source was attributed: observation=%+v error=%v", got, err) + } + if got, err := ObserveWorkspaceFile(context.Background(), filepath.Dir(path)); got != nil || err == nil { + t.Fatalf("directory was attributed: observation=%+v error=%v", got, err) + } +} + +func TestWorkspaceObservationUnknownPathsAndNormalization(t *testing.T) { + t.Run("source outside a repository", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "source.go") + if err := os.WriteFile(path, []byte("unbound source\n"), 0600); err != nil { + t.Fatal(err) + } + if got, err := ObserveWorkspaceFile(context.Background(), path); got != nil || !errors.Is(err, errWorkspaceObservation) { + t.Fatalf("repository-free source was attributed: observation=%+v error=%v", got, err) + } + }) + t.Run("unavailable new-file evidence", func(t *testing.T) { + dir, _ := workspaceObservationTestFile(t, "source.go") + path := filepath.Join(dir, "added.go") + if err := os.WriteFile(path, []byte("new source\n"), 0600); err != nil { + t.Fatal(err) + } + queried := false + runner := workspaceObservationTestRunner(func(ctx context.Context, dir string, env []string, name string, args ...string) ([]byte, error) { + if slices.Contains(args, "ls-files") { + queried = true + return []byte("sensitive-output"), errors.New("sensitive-output") + } + return (workspaceObservationRunner{}).Run(ctx, dir, env, name, args...) + }) + got, err := observeWorkspaceFile(context.Background(), path, runner) + if !queried || got != nil || !errors.Is(err, errWorkspaceObservation) || strings.Contains(err.Error(), "sensitive-output") { + t.Fatalf("missing new-file evidence was attributed or disclosed: observation=%+v error=%v queried=%v", got, err, queried) + } + }) + t.Run("normalization cannot prove raw changes", func(t *testing.T) { + dir, path := workspaceObservationTestFile(t, "source.go") + runGit(t, dir, "config", "core.autocrlf", "true") + if got, err := ObserveWorkspaceFile(context.Background(), path); got != nil || !errors.Is(err, errWorkspaceObservation) { + t.Fatalf("unsupported normalized content was attributed: observation=%+v error=%v", got, err) + } + }) +} + +func TestWorkspaceObservationNormalizationPolicy(t *testing.T) { + for _, tc := range []struct { + config string + want bool + }{ + {"local\x00core.autocrlf\nfalse\x00", true}, + {"local\x00core.autocrlf\n0\x00", true}, + {"local\x00core.autocrlf\ntrue\x00", false}, + {"local\x00core.autocrlf\ninput\x00", false}, + {"worktree\x00core.eol\nlf\x00", false}, + } { + if got := workspaceObservationNormalizationSafe([]byte(tc.config)); got != tc.want { + t.Errorf("normalization support=%v want=%v for %q", got, tc.want, tc.config) + } + } + var attributes []byte + for _, key := range []string{"filter", "text", "eol", "ident", "working-tree-encoding", "crlf"} { + attributes = append(attributes, []byte("source.go\x00"+key+"\x00unspecified\x00")...) + } + for _, tc := range []struct { + name string + out []byte + want bool + }{ + {"unspecified", attributes, true}, + {"explicit unset", bytes.ReplaceAll(attributes, []byte("unspecified"), []byte("unset")), true}, + {"different path", bytes.ReplaceAll(attributes, []byte("source.go"), []byte("other.go")), false}, + {"active filter", bytes.Replace(attributes, []byte("unspecified"), []byte("driver"), 1), false}, + {"incomplete", nil, false}, + } { + if got := workspaceObservationAttributesSafe(tc.out, "source.go"); got != tc.want { + t.Errorf("%s: attributes supported=%v want=%v", tc.name, got, tc.want) + } + } +} + +func TestWorkspaceObservationSharedPolicyPreservesPushRemoteBinding(t *testing.T) { + expected := "https://github.com/org/repo.git" + for _, origin := range []string{expected, "git@github.com:org/repo.git", "https://github.com/other/repo.git"} { + config := []byte("local\x00remote.origin.url\n" + origin + "\x00") + if offenders := workspaceConfigOffenders(config, DefaultRemote, nil); len(offenders) != 0 { + t.Fatalf("read-only observation invented an origin: %v", offenders) + } + offenders := workspaceConfigOffenders(config, DefaultRemote, &expected) + if (len(offenders) != 0) != (origin != expected) { + t.Fatalf("broker's existing exact HTTPS binding changed for %q: %v", origin, offenders) + } + } +} + +func TestWorkspaceObservationLiteralPathAndReadOnlyState(t *testing.T) { + dir, path := workspaceObservationTestFile(t, "literal*.go") + writeCommit(t, dir, "literal-other.go", "other before\n") + if err := os.WriteFile(path, []byte("before\n"), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "literal-other.go"), []byte("other after\n"), 0600); err != nil { + t.Fatal(err) + } + if got, err := ObserveWorkspaceFile(context.Background(), path); got != nil || err != nil { + t.Fatalf("literal path borrowed a sibling's changes: observation=%+v error=%v", got, err) + } + if err := os.WriteFile(path, []byte("actual change\n"), 0600); err != nil { + t.Fatal(err) + } + indexPath := filepath.Join(dir, ".git", "index") + indexBefore, err := os.ReadFile(indexPath) + if err != nil { + t.Fatal(err) + } + head := strings.TrimSpace(runGitOutput(t, dir, "rev-parse", "HEAD")) + got, err := ObserveWorkspaceFile(context.Background(), path) + if err != nil || got == nil || got.Head != head || got.Path != "literal*.go" || got.Origin != "https://github.com/org/repo.git" { + t.Fatalf("actual literal source lost provenance: observation=%+v error=%v", got, err) + } + indexAfter, err := os.ReadFile(indexPath) + if err != nil || !bytes.Equal(indexBefore, indexAfter) { + t.Fatalf("read-only observation rewrote the index: %v", err) + } + if after := strings.TrimSpace(runGitOutput(t, dir, "rev-parse", "HEAD")); after != head { + t.Fatal("read-only observation changed HEAD") + } +} + +func TestWorkspaceObservationIgnoresReplacementObjects(t *testing.T) { + dir, path := workspaceObservationTestFile(t, "source.go") + before := strings.TrimSpace(runGitOutput(t, dir, "rev-parse", "HEAD")) + runGit(t, dir, "add", "source.go") + runGit(t, dir, "commit", "-s", "-m", "actual current head") + head := strings.TrimSpace(runGitOutput(t, dir, "rev-parse", "HEAD")) + runGit(t, dir, "replace", head, before) + if got, err := ObserveWorkspaceFile(context.Background(), path); got != nil || err != nil { + t.Fatalf("replacement objects invented current-head source work: observation=%+v error=%v", got, err) + } + if err := os.WriteFile(path, []byte("actually changed\n"), 0600); err != nil { + t.Fatal(err) + } + if got, err := ObserveWorkspaceFile(context.Background(), path); err != nil || got == nil || got.Head != head { + t.Fatalf("actual HEAD replaced: observation=%+v error=%v", got, err) + } +} + +func TestWorkspaceObservationNestedStagedAndMetadataPaths(t *testing.T) { + dir, path := workspaceObservationTestFile(t, "nested/source.go") + if got, err := ObserveWorkspaceFile(context.Background(), path); err != nil || got == nil || got.Path != "nested/source.go" { + t.Fatalf("nested file lost root-relative provenance: observation=%+v error=%v", got, err) + } + if err := os.WriteFile(filepath.Join(dir, ".gitattributes"), []byte("nested/source.go text=auto\n"), 0600); err != nil { + t.Fatal(err) + } + if got, err := ObserveWorkspaceFile(context.Background(), path); got != nil || err == nil { + t.Fatalf("nested attributes were checked against a guessed path: observation=%+v error=%v", got, err) + } + added := filepath.Join(dir, "nested", "staged.go") + if err := os.WriteFile(added, []byte("new source\n"), 0600); err != nil { + t.Fatal(err) + } + runGit(t, dir, "add", "nested/staged.go") + if got, err := ObserveWorkspaceFile(context.Background(), added); err != nil || got == nil || got.Path != "nested/staged.go" { + t.Fatalf("actual staged source creation lost: observation=%+v error=%v", got, err) + } + if got, err := ObserveWorkspaceFile(context.Background(), filepath.Join(dir, ".git", "config")); got != nil { + t.Fatalf("Git administration invented source work: observation=%+v error=%v", got, err) + } +} + +func TestWorkspaceObservationAgentOwnedWorktree(t *testing.T) { + dir, path := workspaceObservationTestFile(t, "nested/source.go") + runner := workspaceObservationTestRunner(func(ctx context.Context, dir string, env []string, name string, args ...string) ([]byte, error) { + env = append(env, "GIT_TEST_ASSUME_DIFFERENT_OWNER=1") + return (workspaceObservationRunner{}).Run(ctx, dir, env, name, args...) + }) + got, err := observeWorkspaceFile(context.Background(), path, runner) + if err != nil || got == nil || got.Path != "nested/source.go" { + t.Fatalf("canonical agent-owned checkout cannot be observed: observation=%+v error=%v", got, err) + } + linked := filepath.Join(t.TempDir(), "linked") + runGit(t, dir, "worktree", "add", "-b", "linked-fixture", linked) + linkedPath := filepath.Join(linked, "nested", "source.go") + if err := os.WriteFile(linkedPath, []byte("linked source change\n"), 0600); err != nil { + t.Fatal(err) + } + got, err = observeWorkspaceFile(context.Background(), linkedPath, runner) + if err != nil || got == nil || got.Path != "nested/source.go" { + t.Fatalf("linked worktree lost its actual repository binding: observation=%+v error=%v", got, err) + } +} + +func TestWorkspaceObservationConfigChangeCannotRunFilters(t *testing.T) { + for _, key := range []string{"filter.race.clean", "filter.race.process", "core.fsmonitor", "diff.race.textconv"} { + t.Run(key, func(t *testing.T) { + dir, path := workspaceObservationTestFile(t, "source.go") + marker := filepath.Join(dir, "helper-ran") + script := filepath.Join(dir, "helper") + if err := os.WriteFile(script, []byte("#!/bin/sh\n: > '"+marker+"'\n"), 0700); err != nil { + t.Fatal(err) + } + injected := false + runner := workspaceObservationTestRunner(func(ctx context.Context, dir string, env []string, name string, args ...string) ([]byte, error) { + if slices.Contains(args, "hash-object") { + injected = true + runGit(t, dir, "config", key, script) + if err := os.WriteFile(filepath.Join(dir, ".gitattributes"), []byte("source.go filter=race diff=race\n"), 0600); err != nil { + t.Fatal(err) + } + } + return (workspaceObservationRunner{}).Run(ctx, dir, env, name, args...) + }) + if got, err := observeWorkspaceFile(context.Background(), path, runner); got != nil || err == nil || !injected { + t.Fatalf("changing hostile config was accepted: observation=%+v error=%v injected=%v", got, err, injected) + } + if _, err := os.Stat(marker); !os.IsNotExist(err) { + t.Fatalf("observer executed changing workspace config: %v", err) + } + }) + } +} + +func TestWorkspaceObservationFailuresAndUnstableMetadata(t *testing.T) { + _, path := workspaceObservationTestFile(t, "source.go") + type step struct { + args []string + out []byte + } + var steps []step + recorder := workspaceObservationTestRunner(func(ctx context.Context, dir string, env []string, name string, args ...string) ([]byte, error) { + out, err := (workspaceObservationRunner{}).Run(ctx, dir, env, name, args...) + steps = append(steps, step{args: slices.Clone(args), out: bytes.Clone(out)}) + return out, err + }) + if got, err := observeWorkspaceFile(context.Background(), path, recorder); err != nil || got == nil { + t.Fatalf("baseline collection failed: observation=%+v error=%v", got, err) + } + replay := func(t *testing.T, change func(int, []byte) ([]byte, error)) { + t.Helper() + index := 0 + runner := workspaceObservationTestRunner(func(_ context.Context, _ string, _ []string, _ string, args ...string) ([]byte, error) { + if index >= len(steps) || !slices.Equal(args, steps[index].args) { + t.Fatalf("unexpected observation command: %v", args) + } + i := index + index++ + return change(i, bytes.Clone(steps[i].out)) + }) + got, err := observeWorkspaceFile(context.Background(), path, runner) + if got != nil || !errors.Is(err, errWorkspaceObservation) || strings.Contains(err.Error(), "sensitive-output") { + t.Fatalf("failed/unstable evidence escaped or disclosed output: observation=%+v error=%v", got, err) + } + } + for i := range steps { + t.Run(strings.Join(steps[i].args, " ")+"/failure", func(t *testing.T) { + replay(t, func(at int, out []byte) ([]byte, error) { + if at == i { + return []byte("sensitive-output"), errors.New("sensitive-output") + } + return out, nil + }) + }) + } + for _, tc := range []struct { + name string + at int + out []byte + }{ + {"unsafe config", 0, []byte("local\x00core.fsmonitor\nsensitive-output\x00")}, + {"missing root", 1, []byte(filepath.Join(filepath.Dir(path), "absent"))}, + {"outside root", 1, []byte(t.TempDir())}, + {"empty head", 2, nil}, + {"empty origin", 3, nil}, + {"bad tree record", 4, []byte("invalid\x00")}, + {"wrong path", 4, []byte("100644 blob abc\tother.go\x00")}, + {"symlink tree", 4, []byte("120000 blob abc\tsource.go\x00")}, + {"multiple tree records", 4, append(bytes.Clone(steps[4].out), steps[4].out...)}, + {"missing attributes", 6, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + replay(t, func(at int, out []byte) ([]byte, error) { + if at == tc.at { + return tc.out, nil + } + return out, nil + }) + }) + } + for i := len(steps) - 4; i < len(steps); i++ { + t.Run(strings.Join(steps[i].args, " ")+"/changed", func(t *testing.T) { + replay(t, func(at int, out []byte) ([]byte, error) { + if at == i { + return append(out, []byte("changed")...), nil + } + return out, nil + }) + }) + } + t.Run("source changed during observation", func(t *testing.T) { + replay(t, func(at int, out []byte) ([]byte, error) { + if at == len(steps)-1 { + if err := os.WriteFile(path, []byte("a concurrent different edit\n"), 0600); err != nil { + t.Fatal(err) + } + } + return out, nil + }) + }) +} diff --git a/src/crux/runtime/code_work.go b/src/crux/runtime/code_work.go new file mode 100644 index 0000000000..dd18b21eb9 --- /dev/null +++ b/src/crux/runtime/code_work.go @@ -0,0 +1,16 @@ +package runtime + +import ( + "io" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/crux/agent" +) + +// ObserveCodeWorkTranscript exposes the runtime's read-only successful-edit +// collector without coupling consumers to the agent implementation. Unsupported +// transcripts and unverifiable worktrees return nil. +func ObserveCodeWorkTranscript(r io.Reader, workDir string, since, now time.Time) *crux.CodeWork { + return agent.ObserveCodeWorkTranscript(r, workDir, since, now) +} diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index f53613dd29..78ee568d5b 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -24,6 +24,6 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1662` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1663` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1664` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1663` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1664` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1665` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index f621a7fc82..05b5567c16 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -3,6 +3,21 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page for how auth levels and `pkg/:` source citations are read and checked. Edit this file for routes in this area and run `src/scripts/check-api-reference-citations.sh --fix` to resync citations. +`GET /api/stage-tracker` adds independent PR `ci_activity`, `review_activity` +and `code_activity` observations, also copied to `linked_prs[]`. Each is +`{head, state, caption, actor?, source, observed_at?, since?, blocker?, url?, active?}`. +These are display evidence, **not merge authorization**. An absent timestamp +means unknown freshness; a different head invalidates the observation. +CI is classified only against the resolved required set from the existing +check snapshot. Review assignment comes from dispatch, current work additionally +requires its actual worker, and approval/findings require verified current-head +review evidence. Authors and claimants are not inferred reviewers. +`display_column` may be `30` (source repair or explicit owner/adoption wait) +or `50` (CI and re-review), without changing native stage identities, counts, +filters or routing. Consumers must not turn either display field into a gate. +The monitor renders CI and Review concurrently on one shared PR row; see +[Reading the tracks](../streaming-the-activity-monitor.md#reading-the-tracks). + | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/audit` | Read-write role | Audit Log — `{"entries": [...]}` envelope, newest first, capped at 200; response shape and the serve-time `user_name` field in [audit-log.md](../audit-log.md#get-apiaudit) | `pkg/dashboard/api.go:62` | @@ -65,4 +80,42 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:377` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:378` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:379` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1669` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1670` | +### Activity observation provenance + +The CI snapshot retains real check/node IDs, head, App ID and transition times. +Its `required_checks` entries retain forge policy's context/App binding: +with `app_known: true`, `app_id: null` or `-1` is an observed any-App rule, not +permission to replace a pinned producer. `required_source` distinguishes actual protection/branch/rules +reads from config fallback; failed actual policy reads do not make the activity +track's `required_known` true. Context-name-only fallback cannot establish an +App binding and remains unknown, rather than treating missing detail as an +explicit any-App rule. Unordered or producer-unknown duplicates remain +ambiguous, never synthetic positional IDs. + +For REST check-run snapshots, an absent required name also checks the actual +head's legacy commit statuses before claiming it is missing. Explicit any-App +rules collect statuses even when a check run exists: a check cannot hide a +same-name failing/pending status, or turn a failed status read green. +`statuses_known` +and `statuses_observed_at` distinguish a complete status read from denied, +partial or wrong-head reads; those remain unknown, not missing or passing. +Status observations retain `kind: "commit_status"` and actual IDs/URLs/times. +An unbound status cannot establish a pinned App's success. Canonical protection +facts keep their existing name-set contract; display ambiguity does not become +a new merge/DCO authorization rule. + +Real check IDs order retries consistently, including queued runs with no start +time. Start time never changes the ordering rule depending on its comparison +partner. Conflicting equal-identity snapshots remain ambiguous for display; +canonical selection remains one observation per producer and does not let +missing IDs erase an observed blocker. +REST check-run and status pages must finish successfully; malformed or partial +collections cannot establish absence or passing CI. + +Source repair activity is derived from the assigned actor's fresh +`codeWork` runtime observation plus current-round PR scope, not administrative +PR writes. Push and same-head retry observations do not inherit an old fixer, +owner or worker observation timestamp. Review completion uses the dispatch +ledger's own agent/review-head/decision receipt and aggregate participation; +another agent's same-perspective bundle verdict cannot settle that assignment. diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 1cde2373be..8c3676ea0f 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -24,17 +24,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)). Also `startedAt` (RFC3339 process start — changes on every pod roll even when the build does not, so the dashboard can say "Restarted" vs "Upgraded") and, until the first status is published, `startupPhase`/`startupPhaseLabel` (the boot phase a fresh pod is in) ([#15788](https://github.com/hivecommons/hive/issues/15788)) | `pkg/dashboard/api.go:44` | | `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:45` | | `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:69` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1642` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1643` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1644` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1650` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`) | `pkg/dashboard/server.go:1655` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1656` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1657` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1658` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1659` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1660` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1661` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1643` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1644` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1645` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1651` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`) | `pkg/dashboard/server.go:1656` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1657` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1658` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1659` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1660` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1661` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1662` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index e8cd28b67c..0bcb80eda2 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -6,7 +6,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:46` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1725` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1726` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:82` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:83` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:84` | diff --git a/src/docs/scale-envelope.md b/src/docs/scale-envelope.md index 58fe965a78..d778a423ab 100644 --- a/src/docs/scale-envelope.md +++ b/src/docs/scale-envelope.md @@ -34,7 +34,7 @@ ones to: 2. **Truncation must preserve the prioritization signal, not cut an arbitrary slice.** This holds today and is easy to assume backwards: - Issues are sorted by actionable rank tier, then **oldest first** within each tier before any cap is applied - (`RankActionableIssues`, `src/pkg/github/client.go:5075-5085`, descending `AgeMinutes` within each tier). + (`RankActionableIssues`, `src/pkg/github/client.go:5096-5106`, descending `AgeMinutes` within each tier). - PRs are sorted by **review class then oldest-first within class** (`SortPullRequestsForReview`, `src/pkg/github/review_priority.go:334`; fixes → refactors/docs → tests). diff --git a/src/docs/streaming-the-activity-monitor.md b/src/docs/streaming-the-activity-monitor.md index 0991db6750..41272618ab 100644 --- a/src/docs/streaming-the-activity-monitor.md +++ b/src/docs/streaming-the-activity-monitor.md @@ -2,11 +2,66 @@ An unattended, 24/7 Twitch stream of the hive dashboard's **Activity Monitor** (the stage tracker: every tracked issue and PR walking Open → Actionable → -Claimed → PR in progress → CI / Review → Merge queue). The first stream is +Claimed → PR in progress → parallel **CI** and **Review** tracks → Merge queue). The first stream is hive's own hosted spoke on `hive-oke`, channel [`twitch.tv/hivecommons`](https://www.twitch.tv/hivecommons). The stream is listed alongside the other community links in [Community and support](community.md). +### Reading the tracks + +CI and Review are separate columns on the same PR row, not serial steps. +Native stage `050` remains the aggregate CI / Review stage for API consumers, +stage filters, counts and routing. Both tracks can work at once; green CI does +not imply review approval, and approval does not imply green CI or admission. +Required-check evidence comes from the existing GitHub check snapshot and +required-set resolver. Missing runs, unknown required sets, optional checks +and skipped checks do not manufacture a passing or failing required verdict. +Legacy commit statuses also count as observed required contexts for an +explicit any-App rule. A failed or partial status read leaves absence unknown; +an unbound status cannot prove a pinned App passed. Real retry IDs, not mixed +pairwise start-time comparisons, keep the result independent of API ordering. + +Observed source repair is shown in **PR in progress**: a current-head fix +assignment names its actual fixer, but only a verified fresh source edit says +**Fixing** and returns an otherwise CI/Review repair there. Assignment alone +stays activity unknown, rather than moving CI-only work back to coding. +Author-wait stages `071`/`072` explicitly say waiting for the owner, and adopted +repair `074` retains its provenance without claiming the owner is coding. +An unassigned `070` says waiting for a fixer; CI-only retries stay in CI. +A recorded new-head push returns the row to CI and re-review, invalidating +old-head observations. Review findings alone never animate author code work. +Human decisions still belong to their human gates. +Default sorting and linked-PR ordering continue to use the native route, +not the display projection. Repair's displayed since-time comes from its +recorded assignment/transition, never an invented return date. + +Track tooltips disclose the head, evidence source, observation time, state +time and blocker where known. A `?` means stale or missing observation time; +unknown activity has no spinner. Review assignment is read from dispatch, not +the PR author, claimant, scanner or Prow approval labels. Verified current-head +review evidence and the current aggregate supply approval/findings; missing +reviewer identity is left unknown. An assignment is not proof of execution, +and activity visibility is not a throughput or latency promise. Tracker +freshness and `/api/status` freshness remain separate; their counts are not +silently reconciled. +A worker observation is conservative: its current-round PR scope must match +the head-bound assignment. Source work additionally requires a successful edit +tool receipt, a real changed file in the matching Git origin/head worktree and +fresh event/observation times within two minutes. A comment, claim, label, +review request or investigation intention is never source-work proof. +Verification uses the existing Crux pushbroker's workspace config policy through +a credential-free, read-only inspector. Hooks, fsmonitor, diff/textconv/clean +filters and remote helpers cannot run during observation; inherited `GIT_*` +settings cannot retarget the inspected repository. Inspection has a single +two-second deadline and bounded output, rechecks actual origin/head/path, and +leaves unsafe configuration, unsupported content normalization or changing +metadata unknown rather than claiming active fixing. +The existing cached runtime transcript scan currently observes supported +Copilot absolute-path edit/create/patch completions; unsupported backends, +relative paths, oversized/partial transcripts and unverifiable changes remain +assigned with activity unknown. Paused agents and CI-only pollers do not prove +current coding. These are read-only observations, not scheduling authority. + Everything lives in [`src/deploy/stream/`](../deploy/stream/README.md): a container that renders the dashboard in a virtual display and pushes it to Twitch, and the Kubernetes manifests that run it next to the hive it watches. diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index 442f0f5554..2ab315d0c7 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -863,12 +863,13 @@ type FrontendAgent struct { // the prompt. The SPA renders this as "Waiting on CI" instead of // "Working" so a stalled-on-CI agent no longer looks indistinguishable // from one making progress. - AwaitingCI bool `json:"awaitingCI,omitempty"` - Paused bool `json:"paused"` - PausedAt string `json:"pausedAt,omitempty"` - PausedReason string `json:"pausedReason,omitempty"` - PausedTrigger string `json:"pausedTrigger,omitempty"` - PausedBy string `json:"pausedBy,omitempty"` + AwaitingCI bool `json:"awaitingCI,omitempty"` + CodeWork *crux.CodeWork `json:"codeWork,omitempty"` + Paused bool `json:"paused"` + PausedAt string `json:"pausedAt,omitempty"` + PausedReason string `json:"pausedReason,omitempty"` + PausedTrigger string `json:"pausedTrigger,omitempty"` + PausedBy string `json:"pausedBy,omitempty"` // OperatorStopped is true when the agent was stopped explicitly (not by a // crash), so the governor will not revive it. OperatorStopped bool `json:"operatorStopped,omitempty"` diff --git a/src/pkg/dashboard/stage_tracker.go b/src/pkg/dashboard/stage_tracker.go index 29dae0631d..1520e3ec1c 100644 --- a/src/pkg/dashboard/stage_tracker.go +++ b/src/pkg/dashboard/stage_tracker.go @@ -276,14 +276,19 @@ type StageTrackerHop struct { // StageTrackerItem is one open issue or PR on the tracker. type StageTrackerItem struct { - Preparation *StageTrackerPreparation `json:"preparation,omitempty"` - Superseded *github.ReviewQueueSuperseded `json:"superseded,omitempty"` - Repo string `json:"repo"` - Number int `json:"number"` - Kind string `json:"kind"` - Title string `json:"title"` - URL string `json:"url,omitempty"` - Author string `json:"author,omitempty"` + CIActivity *StageTrackerActivity `json:"ci_activity,omitempty"` + ReviewActivity *StageTrackerActivity `json:"review_activity,omitempty"` + CodeActivity *StageTrackerActivity `json:"code_activity,omitempty"` + // DisplayColumn is presentation only; native stages, filters and merge gates remain unchanged. + DisplayColumn int `json:"display_column,omitempty"` + Preparation *StageTrackerPreparation `json:"preparation,omitempty"` + Superseded *github.ReviewQueueSuperseded `json:"superseded,omitempty"` + Repo string `json:"repo"` + Number int `json:"number"` + Kind string `json:"kind"` + Title string `json:"title"` + URL string `json:"url,omitempty"` + Author string `json:"author,omitempty"` // Head is the PR head SHA the lane last evaluated ("" for issues), so // a "waiting for a verdict" caption can name the revision it waits on. Head string `json:"head,omitempty"` @@ -680,6 +685,10 @@ type StageTrackerLinkedIssue struct { // StageTrackerLinkedPR is one covering PR nested under an issue row. type StageTrackerLinkedPR struct { + CIActivity *StageTrackerActivity `json:"ci_activity,omitempty"` + ReviewActivity *StageTrackerActivity `json:"review_activity,omitempty"` + CodeActivity *StageTrackerActivity `json:"code_activity,omitempty"` + DisplayColumn int `json:"display_column,omitempty"` HumanAttention *StageTrackerHumanAttention `json:"human_attention,omitempty"` Preparation *StageTrackerPreparation `json:"preparation,omitempty"` BaseRef string `json:"base_ref,omitempty"` diff --git a/src/pkg/dashboard/stage_tracker_activity.go b/src/pkg/dashboard/stage_tracker_activity.go new file mode 100644 index 0000000000..455547218e --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_activity.go @@ -0,0 +1,479 @@ +package dashboard + +import ( + "slices" + "strings" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/evidence" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" +) + +// StageTrackerActivity keeps independent observations separate from the lane's +// native stage and next mover. Worker activity requires assignment AND worker; +// CI activity comes only from observed required checks. +type StageTrackerActivity struct { + Head string `json:"head"` + State string `json:"state"` + Caption string `json:"caption"` + Actor string `json:"actor,omitempty"` + Source string `json:"source"` + ObservedAt *time.Time `json:"observed_at,omitempty"` + Since *time.Time `json:"since,omitempty"` + Blocker string `json:"blocker,omitempty"` + URL string `json:"url,omitempty"` + Active bool `json:"active,omitempty"` +} + +const trackerActivityFreshWindow = 2 * time.Minute + +func trackerUnknownActivity(head, caption string) *StageTrackerActivity { + return &StageTrackerActivity{Head: head, State: "unknown", Caption: caption, Source: "unavailable"} +} + +func stageTrackerCIActivity(pr github.PullRequest, now time.Time) *StageTrackerActivity { + out := trackerUnknownActivity(pr.HeadSHA, "CI unknown · required checks not observed") + a := pr.CIActivity + if a == nil || pr.HeadSHA == "" || !strings.EqualFold(a.Head, pr.HeadSHA) { + return out + } + out.Source, out.ObservedAt = a.Source, a.ObservedAt + if a.RequiredSource != "" { + out.Source += "+required-" + a.RequiredSource + } + if a.StatusesKnown { + out.Source += "+github-commit-statuses" + } + if !a.RequiredKnown || a.RequiredSource == "" || len(a.RequiredChecks) == 0 || len(a.Required) == 0 { + return out + } + type requiredObservation struct { + name string + checks []github.PRActivityCheck + } + var observations []requiredObservation + for _, name := range a.Required { + found := false + for _, binding := range a.RequiredChecks { + if binding.Name == name { + scoped := *a + scoped.RequiredChecks = []github.PRRequiredCheck{binding} + checks := scoped.ChecksForRequired(name) + var runs, statuses []github.PRActivityCheck + for _, check := range checks { + if check.Kind == "commit_status" { + statuses = append(statuses, check) + } else { + runs = append(runs, check) + } + } + if len(statuses) > 0 && binding.AppKnown && (binding.AppID == nil || *binding.AppID == -1) { + observations = append(observations, requiredObservation{name, statuses}) + if len(runs) > 0 { + observations = append(observations, requiredObservation{name, runs}) + } + } else { + observations = append(observations, requiredObservation{name, checks}) + } + found = true + } + } + if !found { + return out + } + } + out.State, out.Caption = "passing", "CI passed" + running := false + for _, observation := range observations { + name := observation.name + check := github.PRActivityCheck{} + ok := len(observation.checks) > 0 + if ok { + check = observation.checks[0] + } + state := "unknown" + switch { + case len(observation.checks) > 1: + state = "unknown" + case !ok: + if a.StatusesKnown { + state = "missing" + } + case check.State == "queued" || check.State == "waiting" || check.State == "pending" || check.State == "requested": + state = "queued" + case check.State == "in_progress": + state = "running" + running = true + case check.State == "completed": + switch check.Conclusion { + case "success": + state = "passing" + case "neutral", "skipped": + state = "skipped" + case "failure", "timed_out", "cancelled", "action_required", "startup_failure", "stale": + state = "failing" + } + } + // A red required check leads, then missing/unknown, then running/queued. + rank := map[string]int{"passing": 0, "queued": 1, "running": 2, "skipped": 3, "unknown": 4, "missing": 5, "failing": 6} + if rank[state] >= rank[out.State] { + out.State, out.Since, out.URL = state, check.Since, check.URL + out.ObservedAt = a.ObservedAt + if check.Kind == "commit_status" { + out.ObservedAt = a.StatusesObservedAt + } + if state != "passing" { + out.Blocker = name + } + } + } + if out.State == "passing" && a.NeedsCommitStatusEvidence() && !a.StatusesKnown { + out.State, out.Blocker = "unknown", "commit statuses not observed" + } + switch out.State { + case "failing": + out.Caption = "CI failing · " + out.Blocker + case "running": + out.Caption = "CI running" + case "queued": + out.Caption = "CI queued" + case "missing": + out.Caption = "CI waiting · " + out.Blocker + " not observed" + case "unknown": + out.Caption = "CI unknown · " + out.Blocker + case "skipped": + out.Caption = "CI skipped · " + out.Blocker + } + out.Active = running && a.ObservedAt != nil && !a.ObservedAt.After(now) && now.Sub(*a.ObservedAt) <= trackerActivityFreshWindow + if running && out.State != "running" { + out.Caption += " · others running" + } + return out +} + +func trackerHeadMatches(repo string, number int, head, observedRepo string, observedNumber int, observedHead string) bool { + return number == observedNumber && head != "" && strings.EqualFold(head, observedHead) && strings.EqualFold(repo, observedRepo) +} + +func trackerLatestBundleVerdicts(bundle *evidence.Bundle) []evidence.Verdict { + latest := map[string]evidence.Verdict{} + for _, verdict := range bundle.Verdicts { + key := verdict.Perspective + "\x00" + verdict.Backend + "\x00" + verdict.Model + if previous, ok := latest[key]; !ok || verdict.RecordedAt.After(previous.RecordedAt) || + (verdict.RecordedAt.Equal(previous.RecordedAt) && previous.Verdict == "approve" && verdict.Verdict != "approve") { + latest[key] = verdict + } + } + keys := make([]string, 0, len(latest)) + for key := range latest { + keys = append(keys, key) + } + slices.Sort(keys) + out := make([]evidence.Verdict, 0, len(keys)) + for _, key := range keys { + out = append(out, latest[key]) + } + return out +} + +func trackerBundleApproves(bundle *evidence.Bundle, agg *review.Aggregate) bool { + latest := trackerLatestBundleVerdicts(bundle) + if len(latest) == 0 || len(agg.Perspectives) == 0 { + return false + } + perspectives := map[string]bool{} + for _, verdict := range latest { + if verdict.Verdict != "approve" || verdict.Perspective == "" || verdict.RecordedAt.IsZero() { + return false + } + perspectives[verdict.Perspective] = true + } + for perspective, verdict := range agg.Perspectives { + if verdict != review.Verdict("approve") || !perspectives[string(perspective)] { + return false + } + } + return true +} + +// The normal worker map has one seat per PR. Tracks instead inspect each agent, +// so a reviewer and fixer on the same PR cannot overwrite each other's evidence. +func trackerAssignedWorker(status *StatusPayload, repo string, number int, agent string, since, now time.Time) *time.Time { + if status == nil || agent == "" { + return nil + } + + qualify := stageTrackerRepoQualifier(status) + for _, worker := range status.Agents { + action := worker.LastAction + if strings.EqualFold(worker.Name, agent) && worker.Busy == "working" && !worker.Paused && !worker.AwaitingCI && action != nil && + action.Current && agentCausedAuditActions[action.Action] && action.Number == number && strings.EqualFold(qualify(action.Repo), repo) { + if at, err := time.Parse(time.RFC3339Nano, action.At); err == nil && !at.Before(since) && !at.After(now) && now.Sub(at) <= trackerActivityFreshWindow { + return &at + } + } + } + return nil +} + +func trackerAssignedCodeWorker(status *StatusPayload, repo string, number int, head, agent string, since, now time.Time) *crux.CodeWork { + if status == nil || agent == "" || head == "" { + return nil + } + qualify := stageTrackerRepoQualifier(status) + for _, worker := range status.Agents { + observation := worker.CodeWork + action := worker.LastAction + if !strings.EqualFold(worker.Name, agent) || worker.Busy != "working" || worker.Paused || worker.AwaitingCI || + action == nil || !action.Current || !agentCausedAuditActions[action.Action] || + action.Number != number || !strings.EqualFold(qualify(action.Repo), repo) || + observation == nil || observation.Source != crux.CodeWorkSource || observation.Path == "" || + !strings.EqualFold(observation.Repo, repo) || !strings.EqualFold(observation.Head, head) || + observation.At.IsZero() || observation.At.Before(since) || observation.At.After(now) || + observation.KickAt.IsZero() || observation.KickAt.Before(since) || observation.At.Before(observation.KickAt) || + observation.ObservedAt.IsZero() || observation.ObservedAt.Before(observation.At) || observation.ObservedAt.After(now) || + now.Sub(observation.At) > trackerActivityFreshWindow || now.Sub(observation.ObservedAt) > trackerActivityFreshWindow { + continue + } + at, err := time.Parse(time.RFC3339Nano, action.At) + if err != nil || at.Before(observation.KickAt) || at.After(now) { + continue + } + return observation + } + return nil +} + +func stageTrackerReviewActivity(pr github.PullRequest, bundle *evidence.Bundle, agg *review.Aggregate, dispatch review.DispatchState, status *StatusPayload, now time.Time) *StageTrackerActivity { + out := trackerUnknownActivity(pr.HeadSHA, "Review unknown · current-head evidence unavailable") + if agg != nil && !trackerHeadMatches(pr.Repo, pr.Number, pr.HeadSHA, agg.Repo, agg.Number, agg.HeadSHA) { + agg = nil + } + qualify := stageTrackerRepoQualifier(status) + if bundle != nil && trackerHeadMatches(pr.Repo, pr.Number, pr.HeadSHA, bundle.Repo, bundle.Number, bundle.HeadSHA) { + out.Source, out.ObservedAt = "verified-review-bundle", timePtr(bundle.UpdatedAt) + for _, verdict := range trackerLatestBundleVerdicts(bundle) { + if !verdict.RecordedAt.IsZero() && (out.Since == nil || verdict.RecordedAt.After(*out.Since)) { + at := verdict.RecordedAt + out.Since = &at + } + } + for _, posted := range bundle.PostedReviews { + if strings.EqualFold(posted.Head, pr.HeadSHA) { + out.URL = posted.URL + } + } + if agg != nil && trackerHeadMatches(pr.Repo, pr.Number, pr.HeadSHA, agg.Repo, agg.Number, agg.HeadSHA) && len(bundle.Verdicts) > 0 { + switch string(agg.Verdict) { + case "approve": + if agg.MergeEligible && trackerBundleApproves(bundle, agg) { + out.State, out.Caption = "approved", "Review approved" + } else { + out.Caption = "Review unknown · bundle and aggregate do not establish approval" + } + case "changes_requested", "reject": + out.State, out.Caption = "changes_requested", "Review findings · awaiting author" + out.Blocker = stageTrackerFixerExhaustedSummary(agg) + case "requires_human": + out.State, out.Caption = "human_decision", "Review findings · human decision" + out.Blocker = agg.DecisionQuestion + } + } + if out.State == "unknown" && (agg == nil || string(agg.Verdict) != "approve") { + for _, verdict := range trackerLatestBundleVerdicts(bundle) { + if verdict.Verdict == "changes_requested" || verdict.Verdict == "reject" { + out.State, out.Caption = "changes_requested", "Review findings · awaiting author" + if len(verdict.Findings) > 0 { + out.Blocker = verdict.Findings[0].Summary + } + break + } + } + } + if out.State != "unknown" && agg != nil { + var confirmed time.Time + for _, recent := range dispatch.Recent { + if recent.Agent != "" && !recent.Decision && !recent.Confirmed.IsZero() && !recent.Confirmed.After(now) && + trackerHeadMatches(pr.Repo, pr.Number, pr.HeadSHA, qualify(recent.Repo), recent.Number, recent.HeadSHA) && + recent.Confirmed.After(confirmed) { + for _, receipt := range agg.ReportReceipts { + if receipt.Agent == recent.Agent && receipt.Perspective == recent.Perspective && + receipt.Head == recent.Head && !receipt.Decided && !receipt.ReceivedAt.IsZero() && + !receipt.ReceivedAt.Before(recent.Confirmed) && !receipt.ReceivedAt.After(now) { + confirmed, out.Actor = recent.Confirmed, recent.Agent + } + } + } + } + if out.Actor != "" { + out.Caption += " · " + out.Actor + } + } + } + for _, wait := range dispatch.Waits { + if trackerHeadMatches(pr.Repo, pr.Number, pr.HeadSHA, qualify(wait.Repo), wait.Number, wait.HeadSHA) && out.State == "unknown" { + out.State, out.Caption, out.Source = "unassigned", "Review queued · unassigned", "review-dispatch-wait" + out.Since, out.ObservedAt, out.Blocker = timePtr(wait.FirstAt), timePtr(wait.LastAt), wait.Reason + } + } + hadApproval := out.State == "approved" + approvalAt := out.Since + for _, pending := range dispatch.Pending { + if !trackerHeadMatches(pr.Repo, pr.Number, pr.HeadSHA, qualify(pending.Repo), pending.Number, pending.HeadSHA) || + pending.Dispatched.IsZero() || pending.Dispatched.After(now) || now.Sub(pending.Dispatched) > review.DefaultPendingReviewTTL { + continue + } + if out.State == "human_decision" { + continue + } + settled := false + if agg != nil && !agg.RecordedAt.After(now) { + currentAggregate := *agg + currentAggregate.ReportReceipts = nil + for _, receipt := range agg.ReportReceipts { + if !receipt.ReceivedAt.After(now) { + currentAggregate.ReportReceipts = append(currentAggregate.ReportReceipts, receipt) + } + } + currentPending := pending + currentPending.Repo = qualify(pending.Repo) + settled = review.PendingReviewCompleted(currentPending, review.Artifact{Items: []review.Aggregate{currentAggregate}}) + } + if settled { + continue + } + out.State, out.Caption, out.Actor, out.Source = "assigned", "Review assigned", pending.Agent, "review-dispatch" + if pending.Agent == "" { + out.State, out.Caption = "unassigned", "Review queued · unassigned" + } + if pending.Decision { + out.Caption = "Review adjudication assigned" + if pending.Agent == "" { + out.Caption = "Review adjudication queued · unassigned" + } + } + out.Since, out.ObservedAt = timePtr(pending.Dispatched), timePtr(dispatch.GeneratedAt) + workerAt := trackerAssignedWorker(status, pr.Repo, pr.Number, pending.Agent, pending.Dispatched, now) + out.Active = workerAt != nil + if out.Active { + out.State, out.Caption = "reviewing", "Review working" + out.Source, out.ObservedAt = "review-dispatch+current-worker", workerAt + if pending.Decision { + out.State, out.Caption = "adjudicating", "Review adjudication working" + } + } + if out.Actor != "" { + out.Caption += " · " + out.Actor + } + if hadApproval { + if approvalAt != nil && pending.Dispatched.After(*approvalAt) { + out.Caption += " · re-review after approval" + } else { + out.Caption += " · another assignment not completed" + } + } + if out.Active { + break + } + } + return out +} + +func stageTrackerApplyCodeActivity(it *StageTrackerItem, dispatch review.DispatchState, status *StatusPayload, now time.Time) { + activityCaption := it.CodeActivity != nil && it.CodeActivity.Caption != "" && + (it.Caption == it.CodeActivity.Caption || strings.HasPrefix(it.Caption, it.CodeActivity.Caption+" · ")) + it.DisplayColumn = 0 + out := trackerUnknownActivity(it.Head, "Code activity unknown") + qualify := stageTrackerRepoQualifier(status) + if it.Stage == trackerNumberNeedsAuthor || it.Stage == trackerNumberReturned { + out.State, out.Caption, out.Actor, out.Source = "waiting_owner", "Waiting for owner · not observed coding", it.Author, "native-author-wait" + if it.Author != "" { + out.Caption = "Waiting for @" + it.Author + " · not observed coding" + } + out.Since = it.StageSince + it.DisplayColumn = trackerNumberPRInProgress + } + if it.Stage == trackerNumberAdopted { + out.State, out.Caption, out.Source = "adopted", "Adopted repair · activity unknown", "native-adoption" + out.Since = it.StageSince + it.DisplayColumn = trackerNumberPRInProgress + } + if it.Stage == trackerNumberFixing { + out.State, out.Caption, out.Source = "waiting_fixer", "Waiting for fixer · no code work observed", "native-fix-request" + out.Since = it.StageSince + it.DisplayColumn = trackerNumberReviewPending + } + for _, fix := range dispatch.Fixes { + if !trackerHeadMatches(it.Repo, it.Number, it.Head, qualify(fix.Repo), fix.Number, fix.HeadSHA) || + fix.Dispatched.IsZero() || fix.Dispatched.After(now) || now.Sub(fix.Dispatched) > review.DefaultPendingFixTTL { + continue + } + out.State, out.Caption, out.Actor, out.Source = "assigned", "Fix task assigned · activity unknown", fix.Agent, "fix-dispatch" + out.Since, out.ObservedAt = timePtr(fix.Dispatched), timePtr(dispatch.GeneratedAt) + // A dispatch and PR administration are not source-work evidence. + // Bind an observed successful, worktree-verified edit to the exact + // actor/repo/head assignment; unsupported instrumentation is unknown. + if codeWork := trackerAssignedCodeWorker(status, it.Repo, it.Number, it.Head, fix.Agent, fix.Dispatched, now); codeWork != nil { + out.State, out.Caption, out.Active = "fixing", "Fixing · "+fix.Agent, true + out.Source, out.ObservedAt = "fix-dispatch+"+codeWork.Source, timePtr(codeWork.At) + it.DisplayColumn = trackerNumberPRInProgress + } + if status != nil { + for _, worker := range status.Agents { + action := worker.LastAction + if strings.EqualFold(worker.Name, fix.Agent) && worker.Busy == "working" && !worker.Paused && worker.AwaitingCI && + action != nil && action.Current && agentCausedAuditActions[action.Action] && action.Number == it.Number && strings.EqualFold(qualify(action.Repo), it.Repo) { + at, err := time.Parse(time.RFC3339Nano, action.At) + if err != nil || at.Before(fix.Dispatched) || at.After(now) || now.Sub(at) > trackerActivityFreshWindow { + continue + } + out.State, out.Caption = "waiting_ci", "Fix task waiting on CI · not observed coding" + out.Source, out.ObservedAt = "fix-dispatch+current-worker-ci-wait", &at + if it.Stage != trackerNumberNeedsAuthor && it.Stage != trackerNumberReturned && it.Stage != trackerNumberAdopted { + it.DisplayColumn = trackerNumberReviewPending + } + break + } + } + } + break + } + if it.Rework != nil && it.Rework.State == reworkStateInProgress && !out.Active { + out.State, out.Caption, out.Actor, out.Source = "claimed", "Fix task claimed · activity unknown", it.Rework.Actor, "contributor-fix-claim" + out.Since = it.Rework.Since + } + if it.Push != nil && (it.Push.State == pushStatePushed || it.Push.State == pushStateChecking) { + // Current-head work observed after the push can coexist with checks; + // a persistent push marker must not hide a later repair. + workAfterPush := out.Active && (it.Push.State == pushStateChecking || it.Push.Since == nil || + (out.ObservedAt != nil && out.ObservedAt.After(*it.Push.Since))) + if !workAfterPush { + it.DisplayColumn = trackerNumberReviewPending + out = &StageTrackerActivity{Head: it.Head, State: "pushed", Caption: "New head pushed · CI and re-review", + Source: "recorded-push", Since: it.Push.Since} + if it.Push.State == pushStateChecking { + out.State, out.Caption, out.Source = "waiting_ci", "CI retry · no new head observed", "recorded-ci-retry" + } + } + } + // Human decisions and superseded originals remain their native gates. + if it.Stage == trackerNumberNeedsDecision || it.Stage >= trackerNumberAwaitingMerge || it.Superseded != nil { + it.DisplayColumn = 0 + } + if out.State == "waiting_fixer" && strings.HasPrefix(it.Caption, "Fixing paused") { + out.Blocker = strings.Replace(it.Caption, "Fixing paused", "Fix task blocked", 1) + out.Source += "+fix-dispatch-status" + } + it.CodeActivity = out + // Replace generic or previously projected activity, not independent + // native facts such as a foreign bot conflict, hold or rebase episode. + if it.Stage == trackerNumberFixing && it.Superseded == nil && + (it.Caption == "" || strings.HasPrefix(it.Caption, "Fixing") || activityCaption || out.Active) { + it.Caption = out.Caption + if out.Actor != "" && !out.Active { + it.Caption += " · " + out.Actor + } + } +} diff --git a/src/pkg/dashboard/stage_tracker_activity.test.js b/src/pkg/dashboard/stage_tracker_activity.test.js new file mode 100644 index 0000000000..b0be4119a1 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_activity.test.js @@ -0,0 +1,182 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const root = path.join(__dirname, 'static-src', 'js'); +const strip = fs.readFileSync(path.join(root, 'tracker-row-strip.js'), 'utf8'); +const anchor = fs.readFileSync(path.join(root, 'tracker-row-anchor.js'), 'utf8'); +function fn(source, name) { + const match = source.match(new RegExp('function ' + name + '\\([^]*?\\n \\}')); + assert.ok(match, name); + return match[0]; +} +const esc = text => String(text).replaceAll('&', '&').replaceAll('<', '<').replaceAll('"', '"'); +const globals = ` +const STAGE_TRACKER_PATH = [0, 10, 20, 30, 50, 80]; +const STAGE_TRACKER_TERMINAL = 110; +const STAGE_TRACKER_PR_COLUMN = 30, STAGE_TRACKER_MERGE_COLUMN = 80; +const STAGE_TRACKER_NEEDS_DECISION = 85, STAGE_TRACKER_ISSUE_NEEDS_DECISION = 45; +const STAGE_TRACKER_ISSUE_DECISION_COLUMN = 10, STAGE_TRACKER_TRIAGE_NEEDED = 15, STAGE_TRACKER_POSSIBLY_EXISTS = 17; +const STAGE_TRACKER_PRE_MERGE_SOAK = 95; +`; +const track = new Function('esc', fn(strip, 'stageTrackerActivityTrackHtml') + ';return stageTrackerActivityTrackHtml;')(esc); +const getAnchor = new Function(globals + anchor + ';return stageTrackerAnchor;')(); +const header = new Function('esc', 'stageTrackerIcon', globals + fn(strip, 'stageTrackerHeaderHtml') + ';return stageTrackerHeaderHtml;')(esc, () => ''); +const now = Date.parse('2026-11-02T21:00:00Z'); +const activity = (state, caption, active = false) => ({ + head: 'head', state, caption, active, source: state === 'fixing' ? 'fix-dispatch+successful-edit+verified-git-worktree' : 'observed-test-source', + observed_at: new Date(now).toISOString(), since: new Date(now - 60000).toISOString(), +}); +const stages = [{ number: 70, branch_from: 50 }, { number: 71, branch_from: 50 }, { number: 72, branch_from: 50 }, { number: 74, branch_from: 50 }, { number: 85, branch_from: 80 }]; + +test('header has visibly separate aligned CI and Review columns without serial stages', () => { + const html = header([]); + assert.equal((html.match(/
  • CI<\/span><\/li>
  • Review/); +}); + +test('both tracks can be active on one PR and preserve their actual actors and sources', () => { + const item = { kind: 'pr', head: 'head', ci_activity: activity('running', 'CI running', true), review_activity: activity('reviewing', 'Review working · reviewer', true) }; + const html = ['ci', 'review'].map(kind => track(item, kind, {}, false, now)).join(''); + assert.equal((html.match(/data-motion="active"/g) || []).length, 2); + assert.match(html, /data-track="ci"/); + assert.match(html, /data-track="review"/); + assert.match(html, /reviewer/); + assert.match(html, /observed-test-source/); + assert.match(html, /since 2026-11-02T20:59:00.000Z/); +}); + +test('CI green/review findings and review approved/CI red remain independent', () => { + const item = { head: 'head', ci_activity: activity('passing', 'CI passed'), review_activity: activity('changes_requested', 'Review findings · awaiting author') }; + assert.match(track(item, 'ci', {}, false, now), /ham-activity-track done/); + assert.match(track(item, 'review', {}, false, now), /data-activity-state="changes_requested"/); + item.ci_activity = activity('failing', 'CI failing · build'); + item.review_activity = activity('approved', 'Review approved'); + assert.match(track(item, 'ci', {}, false, now), /data-activity-state="failing"/); + assert.match(track(item, 'review', {}, false, now), /ham-activity-track done/); +}); + +test('unassigned, old-head, stale, cached unknown timestamps never fabricate working', () => { + const item = { head: 'head', author: 'not-a-reviewer', review_activity: activity('unassigned', 'Review queued · unassigned') }; + assert.doesNotMatch(track(item, 'review', {}, false, now), /not-a-reviewer|data-motion/); + item.review_activity = activity('reviewing', 'Review working · reviewer', true); + item.head = 'new-head'; + assert.doesNotMatch(track(item, 'review', {}, false, now), /reviewer|data-motion/); + item.head = 'head'; + assert.doesNotMatch(track(item, 'review', {}, false, now + 300000), /data-motion/); + assert.match(track(item, 'review', {}, false, now + 300000), /stale/); + delete item.review_activity.observed_at; + assert.doesNotMatch(track(item, 'review', {}, false, now), /data-motion/); + assert.match(track(item, 'review', {}, false, now), /observation time unknown/); +}); + +test('repair display projection returns to PR progress then current-head tracks; native gates stay intact', () => { + const item = { kind: 'pr', head: 'head', stage: 70, display_column: 30, code_activity: activity('fixing', 'Fixing · fixer', true) }; + assert.equal(getAnchor(item.stage, stages, item.kind, item), 30); + assert.equal(item.stage, 70); + item.display_column = 50; + assert.equal(getAnchor(item.stage, stages, item.kind, item), 50); + for (const stage of [71, 72, 74]) assert.equal(getAnchor(stage, stages, 'pr', { head: 'head', display_column: 30, code_activity: activity('waiting_owner', 'Waiting owner') }), 30); + assert.equal(getAnchor(70, stages, 'pr', { head: 'new-head', display_column: 30, code_activity: activity('fixing', 'Fixing · fixer', true) }), 50, 'an old-head projection cannot return a new head to coding'); + assert.equal(getAnchor(85, stages, 'pr'), 80); + assert.equal(getAnchor(110, stages, 'pr', { display_column: 30 }), 110); + assert.equal(getAnchor(50, stages, 'pr'), 50, 'CI retry does not return to coding'); + assert.equal(getAnchor(70, stages, 'pr'), 50, '070 without source observation does not manufacture coding'); +}); + +test('linked PRs carry independent evidence and hidden issue columns stay aligned', () => { + const layout = fs.readFileSync(path.join(root, 'tracker-row-layout.js'), 'utf8'); + const linked = new Function('stageTrackerLinkedPROpen', 'STAGE_TRACKER_TERMINAL', fn(layout, 'stageTrackerLinkedPRItem') + ';return stageTrackerLinkedPRItem;')(() => true, 110); + const lp = { number: 7, head: 'head', stage: 70, display_column: 30, ci_activity: activity('running', 'CI running', true), review_activity: activity('reviewing', 'Review working · reviewer', true), code_activity: activity('fixing', 'Fixing · fixer', true) }; + const item = linked({ repo: 'org/repo', number: 1, linked_prs: [lp, { number: 8 }] }, lp); + assert.equal(item.number, 7); + assert.equal(item.display_column, 30); + assert.equal(item.review_activity, lp.review_activity); + assert.deepEqual(item.siblings, [8]); + assert.equal(track(item, 'ci', {}, true, now), '
  • '); + const render = fs.readFileSync(path.join(root, 'tracker-row-render.js'), 'utf8'); + assert.match(render, /ci_activity: lp.ci_activity \|\| null, review_activity: lp.review_activity \|\| null/); +}); + +test('real source repair can show three concurrent activities without naming a generic worker as reviewer', () => { + const row = fs.readFileSync(path.join(root, 'tracker-row.js'), 'utf8'); + const definitions = globals + ` +const STAGE_TRACKER_HUMAN_GATED = 85, STAGE_TRACKER_READY_FOR_HUMAN_MERGE = 90, STAGE_TRACKER_ADOPTED_BY_HIVE = 74; +const STAGE_TRACKER_ACTIVE_WORD = {70: 'Fixing'}; +const STAGE_TRACKER_MOTION_ACTIVE = 'active', STAGE_TRACKER_MOTION_STATIC = 'static'; +function stageTrackerSentinelInLane() { return false; } +function stageTrackerActorKind() { return ''; } +function stageTrackerActorTip() { return ''; } +function stageTrackerMotion() { return 'active'; } +function stageTrackerIcon(n, cls) { return ''; } +` + anchor + fn(row, 'stageTrackerSegments') + fn(strip, 'stageTrackerActivityTrackHtml') + fn(strip, 'stageTrackerStripItems'); + const render = new Function('esc', definitions + ';return stageTrackerStripItems;')(esc); + const item = { kind: 'pr', stage: 70, head: 'head', display_column: 30, + ci_activity: activity('running', 'CI running', true), + review_activity: activity('reviewing', 'Review working · reviewer', true), + code_activity: activity('fixing', 'Fixing · fixer', true), + }; + const html = render(item, [{ number: 30, short: 'PR in progress' }, { number: 50, short: 'CI / Review' }, { number: 70, short: 'Fixing', branch_from: 50 }], null, now, {}); + assert.equal((html.match(/
  • ]*>Fixing · fixer/); + assert.match(html, /data-track="review"[^]*Review working · reviewer/); + item.code_activity.observed_at = new Date(now - 300000).toISOString(); + const stale = render(item, stages, null, now, {}); + assert.match(stale, /Fix task assigned · activity unknown/); + assert.equal((stale.match(/data-motion="active"/g) || []).length, 2, 'stale coding cannot spin beside live CI and review'); + item.code_activity.observed_at = new Date(now).toISOString(); + item.code_activity.source = 'fix-dispatch+current-worker'; + const administration = render(item, stages, null, now, {}); + assert.match(administration, /Fix task assigned · activity unknown/); + assert.equal((administration.match(/data-motion="active"/g) || []).length, 2, 'cached generic PR administration cannot animate coding'); +}); + +test('stale activity is visibly unknown and old green observations cannot look live', () => { + const item = { kind: 'pr', head: 'head', review_activity: activity('reviewing', 'Review working · reviewer', true) }; + const html = track(item, 'review', {}, false, now + 300000); + assert.match(html, /activity unknown · last observed reviewing/); + assert.doesNotMatch(html, /Review working|data-motion/); + item.review_activity = activity('approved', 'Review approved'); + assert.doesNotMatch(track(item, 'review', {}, false, now + 300000), /ham-activity-track done/); +}); + +test('current-head evidence links are accessible and never retained across a new head', () => { + const item = { kind: 'pr', head: 'head', ci_activity: {...activity('failing', 'CI failing · build'), url: 'https://github.com/org/repo/actions/runs/1'} }; + assert.match(track(item, 'ci', {state: 'active'}, false, now), /aria-label="Open current-head CI evidence"/); + assert.match(track(item, 'ci', {state: 'active'}, false, now), /aria-current="step"/); + item.head = 'new-head'; + assert.doesNotMatch(track(item, 'ci', {}, false, now), /href=|actions\/runs\/1/); +}); + +test('a fix request or CI-only wait is visible without manufacturing source work', () => { + const item = { kind: 'pr', head: 'head', stage: 70, display_column: 50, + code_activity: activity('waiting_fixer', 'Waiting for fixer · no code work observed') }; + const waiting = track(item, 'review', {state:'active'}, false, now); + assert.match(waiting, /ham-track-code-note">Waiting for fixer/); + assert.doesNotMatch(waiting, /data-motion/); + item.code_activity = activity('waiting_ci', 'Fix task waiting on CI · not observed coding'); + assert.match(track(item, 'ci', {}, false, now), /waiting on CI · not observed coding/); + assert.equal(getAnchor(70, stages, 'pr', item), 50); +}); + +test('linked movement uses current-head repair evidence while native sort stays unchanged', () => { + const motion = fs.readFileSync(path.join(root, 'tracker-motion.js'), 'utf8'); + const map = new Function('stageTrackerLinkedSorted', 'stageTrackerItemKey', globals + 'const STAGE_TRACKER_CAP_COLUMN = 7;' + + anchor + fn(motion, 'stageTrackerColIndex') + fn(motion, 'stageTrackerColMap') + ';return stageTrackerColMap;')( + item => item.linked_prs || [], item => item.kind + '#' + item.number); + const moves = new Function(fn(motion, 'stageTrackerColMoves') + ';return stageTrackerColMoves;')(); + const pr = {number:7, stage:70, head:'head', display_column:30, code_activity:activity('fixing','Fixing · fixer',true)}; + const items = [{number:1, kind:'issue', linked_prs:[pr]}]; + const fixed = map(items, stages); + assert.equal(fixed['issue#1'], 3); + assert.equal(fixed['pr#7'], 3); + assert.equal(getAnchor(70, stages, 'pr', pr, false), 50, 'default native sorting is unchanged'); + assert.deepEqual(moves(null, fixed), {}, 'the first observation cannot manufacture a bounce'); + pr.head = 'new-head'; + pr.display_column = 50; + pr.code_activity = {head:'new-head',state:'pushed'}; + const pushed = map(items, stages); + assert.deepEqual(moves(fixed, pushed), {'issue#1':{from:3,to:4}, 'pr#7':{from:3,to:4}}); +}); diff --git a/src/pkg/dashboard/stage_tracker_activity_test.go b/src/pkg/dashboard/stage_tracker_activity_test.go new file mode 100644 index 0000000000..f4365e235e --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_activity_test.go @@ -0,0 +1,319 @@ +package dashboard + +import ( + "os/exec" + "testing" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/evidence" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" +) + +func TestStageTrackerActivityRequiredCI(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name, state, conclusion, want string + known bool + }{ + {"running", "in_progress", "", "running", true}, + {"queued retry", "queued", "", "queued", true}, + {"failure", "completed", "failure", "failing", true}, + {"success", "completed", "success", "passing", true}, + {"conditional skip", "completed", "skipped", "skipped", true}, + {"unknown required set", "completed", "failure", "unknown", false}, + } { + t.Run(tc.name, func(t *testing.T) { + pr := github.PullRequest{HeadSHA: "head", CIActivity: &github.PRCIActivity{ + Head: "head", Source: "github-check-runs", ObservedAt: &now, RequiredKnown: tc.known, Required: []string{"build"}, StatusesKnown: true, + RequiredSource: "protection", RequiredChecks: []github.PRRequiredCheck{{Name: "build", AppKnown: true}}, + Checks: []github.PRActivityCheck{{Name: "build", State: tc.state, Conclusion: tc.conclusion}, + {Name: "tide", State: "queued"}, {Name: "optional", State: "completed", Conclusion: "failure"}}, + }} + got := stageTrackerCIActivity(pr, now) + if got.State != tc.want || got.Active != (tc.want == "running") { + t.Fatalf("activity = %+v, want %s", got, tc.want) + } + pr.CIActivity.Head = "old-head" + if got := stageTrackerCIActivity(pr, now); got.State != "unknown" || got.Active { + t.Fatalf("old head leaked: %+v", got) + } + }) + } + pr := github.PullRequest{HeadSHA: "head", CIActivity: &github.PRCIActivity{Head: "head", RequiredKnown: true, Required: []string{"missing"}, + RequiredSource: "protection", RequiredChecks: []github.PRRequiredCheck{{Name: "missing", AppKnown: true}}, StatusesKnown: true}} + if got := stageTrackerCIActivity(pr, now); got.State != "missing" { + t.Fatalf("missing run became a verdict: %+v", got) + } + pr.CIActivity.Checks = []github.PRActivityCheck{{Name: "missing", State: "in_progress"}} + for _, at := range []time.Time{now.Add(-trackerActivityFreshWindow - time.Second), now.Add(time.Second)} { + pr.CIActivity.ObservedAt = &at + if got := stageTrackerCIActivity(pr, now); got.Active { + t.Fatalf("stale or future CI manufactured current activity: %+v", got) + } + } +} + +func trackerActivityFixture(now time.Time) (github.PullRequest, review.DispatchState, *StatusPayload) { + pr := github.PullRequest{Repo: "org/repo", Number: 7, Author: "author", HeadSHA: "head"} + dispatch := review.DispatchState{GeneratedAt: now, Pending: []review.PendingReview{ + {Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Agent: "reviewer", Dispatched: now}, + }} + status := &StatusPayload{Agents: []FrontendAgent{ + {Name: "reviewer", Busy: "working", LastAction: &FrontendAgentLastAction{Repo: pr.Repo, Number: pr.Number, Action: github.AuditActionAgentCommentCreated, Current: true, At: now.Format(time.RFC3339Nano)}}, + {Name: "fixer", Busy: "working", LastAction: &FrontendAgentLastAction{Repo: pr.Repo, Number: pr.Number, Action: github.AuditActionAgentCommentCreated, Current: true, At: now.Format(time.RFC3339Nano)}}, + }} + status.Agents[1].CodeWork = &crux.CodeWork{Repo: pr.Repo, Head: pr.HeadSHA, Path: "source.go", + Source: crux.CodeWorkSource, At: now, ObservedAt: now, KickAt: now} + return pr, dispatch, status +} + +func TestStageTrackerActivityParallelAndReviewHead(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + pr, dispatch, status := trackerActivityFixture(now) + pr.CIActivity = &github.PRCIActivity{Head: pr.HeadSHA, Source: "github-check-runs", ObservedAt: &now, RequiredKnown: true, + RequiredSource: "protection", RequiredChecks: []github.PRRequiredCheck{{Name: "build", AppKnown: true}}, + StatusesKnown: true, StatusesObservedAt: &now, + Required: []string{"build"}, Checks: []github.PRActivityCheck{{Name: "build", State: "in_progress"}}} + ci := stageTrackerCIActivity(pr, now) + rev := stageTrackerReviewActivity(pr, nil, nil, dispatch, status, now) + if !ci.Active || !rev.Active || rev.Actor != "reviewer" { + t.Fatalf("tracks not parallel: CI=%+v Review=%+v", ci, rev) + } + dispatch.Pending = nil + dispatch.Waits = []review.ReviewWaitRecord{{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, FirstAt: now, LastAt: now}} + if got := stageTrackerReviewActivity(pr, nil, nil, dispatch, status, now); got.State != "unassigned" || got.Actor != "" || got.Active { + t.Fatalf("unassigned reviewer invented: %+v", got) + } + bundle := &evidence.Bundle{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, UpdatedAt: now, + Verdicts: []evidence.Verdict{{Perspective: "quality", Verdict: "changes_requested", RecordedAt: now}}} + agg := &review.Aggregate{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Verdict: review.Verdict("changes_requested")} + dispatch.Waits = nil + pr.CIActivity.Checks[0].State, pr.CIActivity.Checks[0].Conclusion = "completed", "success" + pr.CIActivity.StatusesKnown = false + if stageTrackerCIActivity(pr, now).State != "unknown" || stageTrackerReviewActivity(pr, bundle, agg, dispatch, status, now).State != "changes_requested" { + t.Fatal("an uncollected any-App status side invented green CI or hid review findings") + } + pr.CIActivity.StatusesKnown = true + if stageTrackerCIActivity(pr, now).State != "passing" || stageTrackerReviewActivity(pr, bundle, agg, dispatch, status, now).State != "changes_requested" { + t.Fatal("green CI suppressed review findings") + } + pr.CIActivity.Checks[0].Conclusion = "failure" + agg.Verdict, agg.MergeEligible = review.Verdict("approve"), true + agg.Perspectives = map[review.Perspective]review.Verdict{"quality": "approve"} + bundle.Verdicts[0].Verdict = "approve" + if stageTrackerCIActivity(pr, now).State != "failing" || stageTrackerReviewActivity(pr, bundle, agg, dispatch, status, now).State != "approved" { + t.Fatal("review approval suppressed CI failure") + } + pr.HeadSHA = "new-head" + if got := stageTrackerReviewActivity(pr, bundle, agg, dispatch, status, now); got.State != "unknown" || got.Actor != "" { + t.Fatalf("old review survived new push: %+v", got) + } +} + +func TestStageTrackerCodeActivityPreservesNativeNonCodingFacts(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + for _, caption := range []string{ + "Conflicting with the base branch; bot-authored PR (@automation[bot]) — the hive does not fix bot PRs", + "Rebasing · attempt 1/2", + "On hold · waiting for a human", + } { + t.Run(caption, func(t *testing.T) { + it := StageTrackerItem{Kind: "pr", Repo: "org/repo", Number: 7, Head: "head", Stage: trackerNumberFixing, Caption: caption} + stageTrackerApplyCodeActivity(&it, review.DispatchState{}, nil, now) + stageTrackerApplyCodeActivity(&it, review.DispatchState{}, nil, now) + if it.Caption != caption || it.CodeActivity == nil || it.CodeActivity.Active || + it.CodeActivity.State != "waiting_fixer" || it.DisplayColumn != trackerNumberReviewPending { + t.Fatalf("native fact was replaced or invented source work: %+v", it) + } + }) + } +} + +func TestStageTrackerActivitySourceRepairAndWaits(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + pr, dispatch, status := trackerActivityFixture(now) + it := StageTrackerItem{Repo: pr.Repo, Number: pr.Number, Kind: "pr", Author: pr.Author, Head: pr.HeadSHA, Stage: trackerNumberFixing} + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.DisplayColumn != trackerNumberReviewPending || it.CodeActivity.Active || it.CodeActivity.State != "waiting_fixer" { + t.Fatalf("070 manufactured fixing: %+v", it.CodeActivity) + } + dispatch.Fixes = []review.PendingFix{{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Agent: "fixer", Dispatched: now}} + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.Stage != trackerNumberFixing || it.DisplayColumn != trackerNumberPRInProgress || !it.CodeActivity.Active || it.CodeActivity.Actor != "fixer" { + t.Fatalf("repair failed to return visually: %+v", it) + } + if !stageTrackerReviewActivity(pr, nil, nil, dispatch, status, now).Active { + t.Fatal("fixer hid concurrent reviewer") + } + it.Head = "new-head" + it.Push = &StageTrackerPush{State: pushStatePushed, Since: &now} + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.DisplayColumn != trackerNumberReviewPending || it.CodeActivity.Active || it.CodeActivity.State != "pushed" { + t.Fatalf("new push failed to return to tracks: %+v", it.CodeActivity) + } + dispatch.Fixes[0].HeadSHA = it.Head + resumed := now.Add(time.Second) + status.Agents[1].LastAction.At = resumed.Format(time.RFC3339Nano) + status.Agents[1].CodeWork.Head, status.Agents[1].CodeWork.At, status.Agents[1].CodeWork.ObservedAt = it.Head, resumed, resumed + stageTrackerApplyCodeActivity(&it, dispatch, status, resumed) + if it.DisplayColumn != trackerNumberPRInProgress || !it.CodeActivity.Active { + t.Fatal("a persistent push marker hid later current-head source work") + } + status.Agents[1].LastAction.At = now.Format(time.RFC3339Nano) + it.Push = nil + dispatch.Fixes = nil + for _, stage := range []int{trackerNumberNeedsAuthor, trackerNumberReturned, trackerNumberAdopted, trackerNumberNeedsDecision} { + it.Stage = stage + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.CodeActivity.Active || (stage == trackerNumberNeedsDecision && it.DisplayColumn != 0) || + (stage != trackerNumberNeedsDecision && it.DisplayColumn != trackerNumberPRInProgress) { + t.Fatalf("owner/adoption/human gate manufactured coding at %d: %+v", stage, it) + } + } + dispatch.Fixes = []review.PendingFix{{Repo: pr.Repo, Number: pr.Number, HeadSHA: it.Head, Agent: "fixer", Dispatched: now}} + it.Stage = trackerNumberFixing + stageTrackerApplyCodeActivity(&it, dispatch, status, resumed.Add(trackerActivityFreshWindow)) + if !it.CodeActivity.Active { + t.Fatal("source work at the existing inclusive freshness boundary was discarded") + } + stageTrackerApplyCodeActivity(&it, dispatch, status, resumed.Add(trackerActivityFreshWindow+time.Second)) + if it.CodeActivity.Active || it.DisplayColumn != trackerNumberReviewPending { + t.Fatal("stale worker manufactured active coding") + } +} + +func TestStageTrackerActivityJavaScript(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node unavailable") + } + if output, err := exec.Command(node, "--test", "stage_tracker_activity.test.js").CombinedOutput(); err != nil { + t.Fatalf("activity JavaScript: %v\n%s", err, output) + } +} + +func TestStageTrackerActivityLinkedPRsPreserveCountsAndHeads(t *testing.T) { + items := []StageTrackerItem{ + {Repo: "org/repo", Kind: "issue", Number: 1, LinkedPRs: []StageTrackerLinkedPR{{Number: 7}, {Number: 8}}}, + {Repo: "org/repo", Kind: "pr", Number: 7, Head: "head-7", Stage: trackerNumberFixing, DisplayColumn: trackerNumberPRInProgress, + CIActivity: &StageTrackerActivity{Head: "head-7", State: "running"}, ReviewActivity: &StageTrackerActivity{Head: "head-7", State: "reviewing"}}, + {Repo: "org/repo", Kind: "pr", Number: 8, Head: "head-8", Stage: trackerNumberReviewPending, + CIActivity: &StageTrackerActivity{Head: "head-8", State: "passing"}, ReviewActivity: &StageTrackerActivity{Head: "head-8", State: "changes_requested"}}, + } + issues, prs := stageTrackerOpenCounts(items) + stageTrackerResolveLinkedPRs(items, func(string, int) bool { return true }) + gotIssues, gotPRs := stageTrackerOpenCounts(items) + if issues != gotIssues || prs != gotPRs || issues != 1 || prs != 2 { + t.Fatalf("parallel tracks changed item counts: before=%d/%d after=%d/%d", issues, prs, gotIssues, gotPRs) + } + linked := items[0].LinkedPRs + if len(linked) != 2 || linked[0].CIActivity != items[1].CIActivity || linked[1].ReviewActivity != items[2].ReviewActivity || + linked[0].DisplayColumn != trackerNumberPRInProgress || linked[0].Head == linked[1].Head { + t.Fatalf("linked tracks merged unrelated heads: %+v", linked) + } +} +func TestStageTrackerActivityApprovalRequiresConsistentBundle(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + pr, dispatch, status := trackerActivityFixture(now) + dispatch.Pending = nil + agg := &review.Aggregate{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, + Verdict: "approve", MergeEligible: true, Perspectives: map[review.Perspective]review.Verdict{"quality": "approve", "security": "approve"}} + bundle := &evidence.Bundle{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, UpdatedAt: now, + Verdicts: []evidence.Verdict{ + {Perspective: "quality", Backend: "backend", Model: "model", Verdict: "approve", RecordedAt: now}, + {Perspective: "security", Backend: "backend", Model: "model", Verdict: "changes_requested", RecordedAt: now}, + }} + if got := stageTrackerReviewActivity(pr, bundle, agg, dispatch, status, now); got.State != "unknown" { + t.Fatalf("conflicting bundle became approval: %+v", got) + } + bundle.Verdicts = bundle.Verdicts[:1] + if got := stageTrackerReviewActivity(pr, bundle, agg, dispatch, status, now); got.State != "unknown" { + t.Fatalf("missing perspective became approval: %+v", got) + } + bundle.Verdicts = append(bundle.Verdicts, evidence.Verdict{ + Perspective: "security", Backend: "backend", Model: "model", Verdict: "changes_requested", RecordedAt: now.Add(-time.Minute)}, + evidence.Verdict{Perspective: "security", Backend: "backend", Model: "model", Verdict: "approve", RecordedAt: now}) + dispatch.Recent = []review.RecentReview{{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Perspective: "quality", Agent: "actual-reviewer", Confirmed: now}} + agg.ReportReceipts = []review.ReportReceipt{{Perspective: "quality", Agent: "actual-reviewer", ReceivedAt: now}} + if got := stageTrackerReviewActivity(pr, bundle, agg, dispatch, status, now); got.State != "approved" || got.Actor != "actual-reviewer" { + t.Fatalf("latest same-head approvals did not supersede findings: %+v", got) + } + bundle.Verdicts = append(bundle.Verdicts, evidence.Verdict{ + Perspective: "security", Backend: "backend", Model: "model", Verdict: "reject", RecordedAt: now}) + if got := stageTrackerReviewActivity(pr, bundle, agg, dispatch, status, now); got.State != "unknown" { + t.Fatalf("equal-time conflicting verdict became approval: %+v", got) + } + agg.HeadSHA = "old-head" + if got := stageTrackerReviewActivity(pr, bundle, agg, dispatch, status, now); got.State != "changes_requested" { + t.Fatalf("old aggregate hid current bundle findings: %+v", got) + } +} + +func TestStageTrackerActivityCIRetryAndMixedChecks(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + pr, dispatch, status := trackerActivityFixture(now) + pr.CIActivity = &github.PRCIActivity{Head: pr.HeadSHA, Source: "github-check-runs", ObservedAt: &now, + RequiredSource: "protection", RequiredChecks: []github.PRRequiredCheck{{Name: "build", AppKnown: true}, {Name: "lint", AppKnown: true}}, + RequiredKnown: true, Required: []string{"build", "lint"}, Checks: []github.PRActivityCheck{ + {Name: "build", State: "completed", Conclusion: "failure"}, {Name: "lint", State: "in_progress"}, + }} + if got := stageTrackerCIActivity(pr, now); got.State != "failing" || !got.Active { + t.Fatalf("failing required check hid simultaneous running CI: %+v", got) + } + pr.CIActivity.Checks = append(pr.CIActivity.Checks, github.PRActivityCheck{Name: "build", State: "completed", Conclusion: "success"}) + if got := stageTrackerCIActivity(pr, now); got.State != "unknown" { + t.Fatalf("ambiguous check apps manufactured success: %+v", got) + } + dispatch.Fixes = []review.PendingFix{{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Agent: "fixer", Dispatched: now}} + status.Agents[1].AwaitingCI = true + it := StageTrackerItem{Repo: pr.Repo, Kind: "pr", Number: pr.Number, Head: pr.HeadSHA, Stage: trackerNumberFixing} + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.DisplayColumn != trackerNumberReviewPending || it.CodeActivity.Active || it.CodeActivity.State != "waiting_ci" { + t.Fatalf("CI polling regressed into coding: %+v", it) + } + it.Push = &StageTrackerPush{State: pushStateChecking, Sha: it.Head} + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.DisplayColumn != trackerNumberReviewPending || it.CodeActivity.Active || it.CodeActivity.Source != "recorded-ci-retry" { + t.Fatalf("same-head retry invented coding or a new push: %+v", it) + } + it.Push = nil + status.Agents[1].AwaitingCI = false + status.Agents[1].LastAction.At = now.Add(-time.Second).Format(time.RFC3339Nano) + status.Agents[1].CodeWork.At = now.Add(-time.Second) + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.CodeActivity.Active { + t.Fatal("an action before fix assignment manufactured observed coding") + } + status.Agents[1].Paused = true + status.Agents[1].LastAction.At = now.Format(time.RFC3339Nano) + status.Agents[1].CodeWork.At = now + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.CodeActivity.Active { + t.Fatal("a paused fixer manufactured observed coding") + } + status.Agents[1].Paused = false + status.Agents[1].LastAction.Action = "" + status.Agents[1].CodeWork = nil + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.CodeActivity.Active { + t.Fatal("a missing action kind manufactured observed coding") + } +} + +func TestStageTrackerActivitySelectsObservedReviewer(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + pr, dispatch, status := trackerActivityFixture(now) + dispatch.Pending = append([]review.PendingReview{ + {Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Agent: "idle-reviewer", Dispatched: now}, + }, dispatch.Pending...) + if got := stageTrackerReviewActivity(pr, nil, nil, dispatch, status, now); !got.Active || got.Actor != "reviewer" { + t.Fatalf("an idle assignment hid another head's active reviewer: %+v", got) + } + dispatch.Pending = dispatch.Pending[1:] + dispatch.Pending[0].Decision = true + if got := stageTrackerReviewActivity(pr, nil, nil, dispatch, status, now); got.State != "adjudicating" { + t.Fatalf("adjudication was described as an independent reviewer: %+v", got) + } +} diff --git a/src/pkg/dashboard/stage_tracker_actor_icon_test.go b/src/pkg/dashboard/stage_tracker_actor_icon_test.go index e87ea2d259..ad10e0fc6a 100644 --- a/src/pkg/dashboard/stage_tracker_actor_icon_test.go +++ b/src/pkg/dashboard/stage_tracker_actor_icon_test.go @@ -27,22 +27,24 @@ const detour = (html) => (/([^<]*)< const litTitle = (html) => (/
  • ]*title="([^"]*)"/.exec(strip(html)) || [])[1] || ''; const since = new Date(now - 10 * 3600000).toISOString(); const pr = (n, extra) => Object.assign({ repo: 'hivecommons/docs', number: n, kind: 'pr', title: 'docs: resync', url: 'https://x/' + n, stage: 70, stage_since: since, caption: 'Fixing', author: 'alice', author_kind: 'human' }, extra || {}); +const fixing = (n, extra, actor) => pr(n, Object.assign({head:'head', display_column:30, + code_activity:{head:'head',state:'fixing',caption:'Fixing · '+actor,actor,source:'fix-dispatch+successful-edit+verified-git-worktree',active:true,observed_at:new Date(now).toISOString()}}, extra)); // hive → honeycomb. -let row = stageTrackerRowHtml(pr(501, { author: 'hive-bot', author_kind: 'hive', stage_actor: { kind: 'hive', login: 'fixer', why: 'fixer commented · 3m ago' } }), stages, ctx); +let row = stageTrackerRowHtml(fixing(501, { author: 'hive-bot', author_kind: 'hive', stage_actor: { kind: 'hive', login: 'fixer', why: 'fixer commented · 3m ago' } }, 'fixer'), stages, ctx); assert.strictEqual(actorSvg(row)[1], 'Next move: hive', row); assert.ok(actorSvg(row)[2].includes(STAGE_TRACKER_ICONS.hive), 'hive draws the honeycomb'); -assert.strictEqual(detour(row), 'Fixing', 'an agent on it: the pill stays Fixing'); -assert.ok(litTitle(row).includes('Next move: hive @fixer — fixer commented · 3m ago'), litTitle(row)); +assert.strictEqual(detour(row), 'Fixing · fixer', 'an observed assigned fixer is named'); +assert.ok(litTitle(row).includes('fix-dispatch+successful-edit+verified-git-worktree'), litTitle(row)); // clanker → robot head. -row = stageTrackerRowHtml(pr(502, { author_kind: 'clanker', stage_actor: { kind: 'clanker', login: 'acme-agent', why: '@acme-agent must push a fix' } }), stages, ctx); +row = stageTrackerRowHtml(fixing(502, { author_kind: 'clanker', stage_actor: { kind: 'clanker', login: 'acme-agent', why: '@acme-agent must push a fix' } }, 'acme-agent'), stages, ctx); assert.strictEqual(actorSvg(row)[1], 'Next move: clanker'); assert.ok(actorSvg(row)[2].includes(STAGE_TRACKER_ICONS.clanker)); -assert.strictEqual(detour(row), 'Fixing'); +assert.strictEqual(detour(row), 'Fixing · acme-agent'); // human → the person glyph "Needs human decision" uses. -row = stageTrackerRowHtml(pr(503, { stage_actor: { kind: 'human', login: 'alice', why: '@alice must push a fix' } }), stages, ctx); +row = stageTrackerRowHtml(fixing(503, { stage_actor: { kind: 'human', login: 'alice', why: '@alice must push a fix' } }, 'alice'), stages, ctx); assert.strictEqual(actorSvg(row)[1], 'Next move: human'); assert.ok(actorSvg(row)[2].includes(STAGE_TRACKER_ICONS.human), 'human draws the person glyph'); const decision = stageTrackerRowHtml(pr(509, { stage: 85, stage_actor: { kind: 'human' } }), stages, ctx); @@ -51,75 +53,75 @@ assert.strictEqual(actorSvg(decision)[2], actorSvg(row)[2], 'same glyph as the N // bot → cog, and the pill reads the state instead of an active Fixing (docs#500). const botWhy = 'bot-authored PR (@github-actions[bot]) — the hive does not fix bot PRs; it waits for the bot\'s next run to replace it (superseded by #497)'; row = stageTrackerRowHtml(pr(500, { author: 'github-actions[bot]', author_kind: '', modifiers: ['stalled', 'regressed', 'needs-rebase'], caption: 'Conflicting with the base branch; ' + botWhy, stage_actor: { kind: 'bot', login: 'github-actions[bot]', why: botWhy } }), stages, ctx); -assert.strictEqual(actorSvg(row)[1], 'Next move: bot', row); -assert.ok(actorSvg(row)[2].includes(STAGE_TRACKER_ICONS.bot), 'bot draws the cog'); -assert.ok(!actorSvg(row)[2].includes(STAGE_TRACKER_ICONS.clanker), 'a bot is not drawn as a clanker'); -assert.strictEqual(detour(row), 'Conflicting · bot PR', 'nobody is fixing: the pill says the state in plain words'); -assert.ok(litTitle(row).includes('Next move: bot @github-actions[bot] — bot-authored PR'), litTitle(row)); -assert.ok(text(row).includes('Conflicting · bot PR'), 'the compact caption carries the same words: ' + text(row)); +assert.strictEqual(actorSvg(row).length, 0, 'the next mover is not observed fixing'); +assert.ok(text(row).includes('Waiting for fixer'), 'native 070 cannot fabricate coding'); +assert.ok(tooltip(row).includes('bot-authored PR'), tooltip(row)); +assert.ok(!strip(row).includes('data-motion="active"')); // none is not abandonment evidence for an author-owned external PR. row = stageTrackerRowHtml(pr(504, { author_kind: '', stage_actor: { kind: 'none', why: 'the PR is red and no agent or author is on it' } }), stages, ctx); assert.strictEqual(actorSvg(row).length, 0, 'no invented live actor: ' + strip(row)); -assert.strictEqual(detour(row), 'CI failing · author-owned'); -assert.ok(litTitle(row).includes('Author-owned PR @alice — current work activity is unknown'), litTitle(row)); +assert.ok(text(row).includes('Waiting for fixer')); +assert.ok(tooltip(row).includes('Author-owned PR @alice — current work activity is unknown'), tooltip(row)); assert.ok(!tooltip(row).includes('no one is working'), tooltip(row)); row = stageTrackerRowHtml(pr(504, { author:'', author_kind:'', stage_actor:{kind:'none'} }),stages,ctx); -assert.strictEqual(detour(row),'CI failing · owner unknown'); -assert.ok(litTitle(row).includes('ownership and current work activity are unknown')); +assert.ok(text(row).includes('Waiting for fixer')); +assert.ok(tooltip(row).includes('ownership and current work activity are unknown')); row = stageTrackerRowHtml(pr(504, {author:'',author_kind:'',stage_actor:{kind:'none'}, claimant:{kind:'person',login:'recorded-owner',source:'assignee'}}),stages,ctx); -assert.strictEqual(detour(row),'CI failing · owner recorded'); -assert.ok(litTitle(row).includes('Recorded PR owner @recorded-owner — current work activity is unknown')); +assert.ok(text(row).includes('Waiting for fixer')); +assert.ok(tooltip(row).includes('Recorded PR owner @recorded-owner — current work activity is unknown')); -// No stage_actor (older server): the stage-table heuristic still applies and the word stays Fixing. +// An older payload has no activity evidence: a stage-table heuristic cannot show fixing. row = stageTrackerRowHtml(pr(505, { author_kind: 'clanker' }), stages, ctx); -assert.strictEqual(actorSvg(row)[1], 'Next move: clanker', 'legacy payloads keep the author-kind fallback'); -assert.strictEqual(detour(row), 'Fixing'); -assert.ok(litTitle(row).includes(' · Next move: clanker'), litTitle(row)); +assert.strictEqual(actorSvg(row).length, 0, 'legacy author-kind is not activity evidence'); +assert.ok(text(row).includes('Waiting for fixer')); +assert.strictEqual(litTitle(row), ''); // The server word wins over the heuristic: a hive stage with none → no icon. row = stageTrackerRowHtml(pr(506, { stage: 50, caption: 'CI running', stage_actor: { kind: 'none', why: 'CI is still running' } }), stages, ctx); assert.strictEqual(actorSvg(row).length, 0, strip(row)); -assert.ok(strip(row).includes('CI / Review'), 'a path column keeps its name'); -assert.ok(litTitle(row).includes('Author-owned PR @alice — current work activity is unknown')); +assert.ok(strip(row).includes('CI unknown') && strip(row).includes('Review unknown'), 'missing evidence remains unknown in both tracks'); +assert.strictEqual(litTitle(row), '', 'an aggregate stage alone does not fabricate a reviewer or working chevron'); // An issue riding its one covering PR takes the PR's actor. const lp = { number: 500, title: 'docs: resync', url: 'https://x/500', author: 'github-actions[bot]', author_kind: '', stage: 70, stage_since: since, modifiers: ['needs-rebase'], stage_actor: { kind: 'bot', login: 'github-actions[bot]', why: botWhy } }; row = stageTrackerRowHtml({ repo: 'hivecommons/docs', number: 496, kind: 'issue', title: 'Resync', url: 'https://x/496', stage: 40, stage_since: since, linked_prs: [lp] }, stages, ctx); -assert.strictEqual(actorSvg(row)[1], 'Next move: bot', 'single covering PR: the issue strip carries the PR actor: ' + row); -assert.strictEqual(detour(row), 'Conflicting · bot PR'); +assert.strictEqual(actorSvg(row).length, 0, 'a covering PR does not invent observed coding'); +assert.ok(text(row).includes('Waiting for fixer')); // Sub-rows carry their own actor: one with an agent, one with nobody. row = stageTrackerRowHtml({ repo: 'hivecommons/docs', number: 497, kind: 'issue', title: 'Two', url: 'https://x/497', stage: 40, stage_since: since, linked_prs: [ - Object.assign({}, lp, { number: 510, stage_actor: { kind: 'hive', login: 'fixer', why: 'fixer is on it' } }), + Object.assign({}, lp, { number: 510, head:'head', display_column:30, + code_activity:{head:'head',state:'fixing',caption:'Fixing · fixer',actor:'fixer',source:'fix-dispatch+successful-edit+verified-git-worktree',active:true,observed_at:new Date(now).toISOString()}, + stage_actor: { kind: 'hive', login: 'fixer', why: 'fixer is on it' } }), Object.assign({}, lp, { number: 511, author:'hive-bot', author_kind:'hive', modifiers: [], stage_actor: { kind: 'none', why: 'no agent is on it' } }), ] }, stages, ctx); const subRows = subs(row); assert.strictEqual(subRows.length, 2); -assert.ok(subRows[0].includes('aria-label="Next move: hive"') && subRows[0].includes('Fixing'), subRows[0]); -assert.ok(!subRows[1].includes('ham-actor-ico') && subRows[1].includes('Red · nobody on it') && subRows[1].includes(STAGE_TRACKER_NOBODY_LEAD + ' — no agent is on it'), subRows[1]); +assert.ok(subRows[0].includes('aria-label="Next move: hive"') && subRows[0].includes('Fixing · fixer'), subRows[0]); +assert.ok(!subRows[1].includes('ham-actor-ico') && subRows[1].includes('Waiting for fixer'), subRows[1]); const externalLP={...lp,author:'clubanderson',author_kind:'',modifiers:[],stage_actor:{kind:'none',why:'author kind unknown'}}; row=stageTrackerRowHtml({repo:'hivecommons/docs',number:600,kind:'issue',stage:40,author:'issue-filer',linked_prs:[externalLP]},stages,ctx); -assert.strictEqual(detour(row),'CI failing · author-owned'); -assert.ok(litTitle(row).includes('Author-owned PR @clubanderson'),litTitle(row)); -assert.ok(!litTitle(row).includes('@issue-filer')); +assert.ok(text(row).includes('Waiting for fixer')); +assert.ok(tooltip(row).includes('Author-owned PR @clubanderson'),tooltip(row)); +assert.ok(!tooltip(row).includes('Author-owned PR @issue-filer')); for(const kind of ['human','hive']){ row=stageTrackerRowHtml({repo:'hivecommons/docs',number:600,kind:'issue',stage:40,author:'issue-filer',author_kind:kind, linked_prs:[{...externalLP,author:''}]},stages,ctx); - assert.strictEqual(detour(row),'CI failing · owner unknown','an unknown inline PR author never inherits the issue filer'); - assert.ok(litTitle(row).includes('ownership and current work activity are unknown'),litTitle(row)); - assert.ok(!litTitle(row).includes('@issue-filer'),litTitle(row)); + assert.ok(text(row).includes('Waiting for fixer')); + assert.ok(tooltip(row).includes('ownership and current work activity are unknown'),tooltip(row)); + assert.ok(!tooltip(row).includes('Author-owned PR @issue-filer'),tooltip(row)); } row=stageTrackerRowHtml({repo:'hivecommons/docs',number:600,kind:'issue',stage:40,author:'issue-filer', claimant:{kind:'person',login:'issue-holder',source:'assignee'},linked_prs:[{...externalLP,author:'', claimant:{kind:'person',login:'pr-holder',source:'assignee'}}]},stages,ctx); -assert.strictEqual(detour(row),'CI failing · owner recorded'); -assert.ok(litTitle(row).includes('Recorded PR owner @pr-holder'),litTitle(row)); -assert.ok(!litTitle(row).includes('@issue-holder'),litTitle(row)); +assert.ok(text(row).includes('Waiting for fixer')); +assert.ok(tooltip(row).includes('Recorded PR owner @pr-holder'),tooltip(row)); +assert.ok(!tooltip(row).includes('Recorded PR owner @issue-holder'),tooltip(row)); row=stageTrackerRowHtml({repo:'hivecommons/docs',number:601,kind:'issue',stage:40,linked_prs:[externalLP,{...externalLP,number:512}]},stages,ctx); for(const sub of subs(row)){ - assert.ok(sub.includes('CI failing · author-owned'),sub); + assert.ok(sub.includes('Waiting for fixer'),sub); assert.ok(sub.includes('current work activity is unknown'),sub); assert.ok(!sub.includes('nobody on it'),sub); } @@ -134,7 +136,9 @@ func TestStageTrackerLinkedDrawnUnderJS(t *testing.T) { html := indexHTML(t) runStageTrackerRowActionsScript(t, stageTrackerRowsPreludeJS(t, html)+"\n"+stageTrackerActorIconJS(t, html)+stageTrackerRowsFixtureJS+` const since = new Date(now - 3600000).toISOString(); -const lp = (n, under, extra) => Object.assign({ number: n, title: 'fix', url: 'https://x/' + n, author: 'hive-bot', author_kind: 'hive', stage: 70, stage_since: since, drawn_under: under, stage_actor: { kind: 'hive', login: 'fixer', why: 'fixer is on it' } }, extra || {}); +const lp = (n, under, extra) => Object.assign({ number: n, title: 'fix', url: 'https://x/' + n, author: 'hive-bot', author_kind: 'hive', stage: 70, stage_since: since, drawn_under: under, head:'head', display_column:30, + code_activity:{head:'head',state:'fixing',caption:'Fixing · fixer',actor:'fixer',source:'fix-dispatch+successful-edit+verified-git-worktree',active:true,observed_at:new Date(now).toISOString()}, + stage_actor: { kind: 'hive', login: 'fixer', why: 'fixer is on it' } }, extra || {}); const issue = (n, prs) => ({ repo: 'hivecommons/hive', number: n, kind: 'issue', title: 'Issue ' + n, url: 'https://x/' + n, stage: 40, stage_since: since, caption: 'open PR #14921 covers it', linked_prs: prs }); const elsewhere = (row) => Array.from(row.matchAll(/]*title="([^"]*)"[^>]*>([^<]*)<\/a>/g)).map(m => ({ title: m[1], text: m[2] })); @@ -143,7 +147,7 @@ let row = stageTrackerRowHtml(issue(14910, [lp(14921, 14910)]), stages, ctx); assert.deepStrictEqual(prCol(row).length, 1, 'owner: the PR sits in the PR column: ' + row); assert.ok(prCol(row)[0].includes('#14921')); assert.strictEqual(strips(row).length, 1); -assert.ok(row.includes('Fixing') && row.includes('aria-label="Next move: hive"'), row); +assert.ok(row.includes('Fixing · fixer') && row.includes('aria-label="Next move: hive"'), row); assert.deepStrictEqual(elsewhere(row), [], 'owner carries no elsewhere chip'); // The other issue does not redraw the PR: its own strip (040 Covered by PR) and a chip pointing at the owner row. @@ -265,7 +269,7 @@ assert.ok(header.startsWith('
  • ]*>([\s\S]*?)<\/li>/.exec(s) || ['', ''])[1])); -assert.deepStrictEqual(subWords, ['Fixing · fixer', 'CI / Review · @alice'], JSON.stringify(subWords)); +assert.deepStrictEqual(subWords, ['Fixing · fixer', ''], JSON.stringify(subWords)); +assert.ok(subs(covered)[1].includes('CI unknown') && subs(covered)[1].includes('Review unknown'), 'the PR owner is not an assigned reviewer'); +assert.ok(subs(covered)[1].includes('Held by: @alice'), 'ownership stays available without implying review activity'); console.log('claimant chevron ok'); `) } diff --git a/src/pkg/dashboard/stage_tracker_collection_test.go b/src/pkg/dashboard/stage_tracker_collection_test.go new file mode 100644 index 0000000000..410ac03276 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_collection_test.go @@ -0,0 +1,265 @@ +package dashboard + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/crux/cruxtest" + cruxruntime "github.com/hivecommons/hive/crux/runtime" + "github.com/hivecommons/hive/pkg/config" + "github.com/hivecommons/hive/pkg/evidence" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" +) + +func TestStageTrackerGraphQLCollectionPreservesRequiredProducer(t *testing.T) { + requiredFailure := `{"__typename":"CheckRun","databaseId":101,"name":"build","status":"COMPLETED","conclusion":"FAILURE","startedAt":"2026-11-02T21:00:00Z","completedAt":"2026-11-02T21:01:00Z","checkSuite":{"app":{"databaseId":11},"commit":{"oid":"head"}}}` + optionalSuccess := `{"__typename":"CheckRun","databaseId":202,"name":"build","status":"COMPLETED","conclusion":"SUCCESS","startedAt":"2026-11-02T21:00:00Z","checkSuite":{"app":{"databaseId":22},"commit":{"oid":"head"}}}` + cases := []struct { + name, first, second, app, want string + denied bool + }{ + {"required first", requiredFailure, optionalSuccess, "11", "failing", false}, + {"required last", optionalSuccess, requiredFailure, "11", "failing", false}, + {"any app null", requiredFailure, optionalSuccess, "null", "unknown", false}, + {"any app explicit", optionalSuccess, requiredFailure, "-1", "unknown", false}, + {"unknown run identity", strings.Replace(requiredFailure, `"databaseId":101`, `"databaseId":null`, 1), strings.Replace(optionalSuccess, `"databaseId":22`, `"databaseId":11`, 1), "11", "unknown", false}, + {"unknown producer", strings.Replace(requiredFailure, `"databaseId":11`, `"databaseId":null`, 1), optionalSuccess, "11", "unknown", false}, + {"equal identity conflicting result", requiredFailure, strings.Replace(strings.Replace(optionalSuccess, `"databaseId":202`, `"databaseId":101`, 1), `"databaseId":22`, `"databaseId":11`, 1), "11", "unknown", false}, + {"wrong head cannot replace failure", requiredFailure, strings.Replace(strings.Replace(optionalSuccess, `"databaseId":22`, `"databaseId":11`, 1), `"oid":"head"`, `"oid":"old-head"`, 1), "11", "failing", false}, + {"real ID orders retry", requiredFailure, strings.Replace(optionalSuccess, `"databaseId":22`, `"databaseId":11`, 1), "11", "passing", false}, + {"queued newer ID has no start time", requiredFailure, strings.Replace(strings.Replace(strings.Replace(optionalSuccess, `"databaseId":22`, `"databaseId":11`, 1), `"status":"COMPLETED"`, `"status":"QUEUED"`, 1), `"startedAt":"2026-11-02T21:00:00Z"`, `"startedAt":null`, 1), "11", "queued", false}, + {"unbound single producer", optionalSuccess, optionalSuccess, "null", "passing", false}, + {"missing binding detail", optionalSuccess, optionalSuccess, "missing", "unknown", false}, + {"reader denied names-only fallback", requiredFailure, optionalSuccess, "11", "unknown", true}, + {"reader denied", requiredFailure, optionalSuccess, "11", "unknown", true}, + } + cyclic := []string{ + `{"__typename":"CheckRun","databaseId":101,"name":"build","status":"COMPLETED","conclusion":"SUCCESS","startedAt":"2026-11-02T12:05:00Z","checkSuite":{"app":{"databaseId":11},"commit":{"oid":"head"}}}`, + `{"__typename":"CheckRun","databaseId":102,"name":"build","status":"QUEUED","startedAt":null,"checkSuite":{"app":{"databaseId":11},"commit":{"oid":"head"}}}`, + `{"__typename":"CheckRun","databaseId":103,"name":"build","status":"COMPLETED","conclusion":"FAILURE","startedAt":"2026-11-02T12:04:00Z","checkSuite":{"app":{"databaseId":11},"commit":{"oid":"head"}}}`, + } + for i, order := range [][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}} { + cases = append(cases, struct { + name, first, second, app, want string + denied bool + }{fmt.Sprintf("cyclic ordering %d", i), cyclic[order[0]] + "," + cyclic[order[1]], cyclic[order[2]], "11", "failing", false}) + } + for i, count := 0, len(cases); i < count; i++ { + reversed := cases[i] + reversed.name += " reversed" + reversed.first, reversed.second = reversed.second, reversed.first + cases = append(cases, reversed) + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/graphql": + fmt.Fprintf(w, `{"data":{"repository":{"pullRequests":{"pageInfo":{"hasNextPage":false},"nodes":[{"number":7,"headRefOid":"head","baseRefOid":"base","baseRefName":"v5","headRefName":"repair","updatedAt":"2026-11-02T21:00:00Z","mergeable":"MERGEABLE","mergeStateStatus":"CLEAN","commits":{"nodes":[{"commit":{"oid":"head","statusCheckRollup":{"contexts":{"nodes":[%s,%s]}}}}]}}]}}}}`, tc.first, tc.second) + case strings.HasSuffix(r.URL.Path, "/protection/required_status_checks"): + if tc.denied { + http.Error(w, `{"message":"Resource not accessible by integration"}`, http.StatusForbidden) + } else if tc.app == "missing" { + fmt.Fprint(w, `{"contexts":["build"],"checks":[{"context":"build"}]}`) + } else { + fmt.Fprintf(w, `{"contexts":["build"],"checks":[{"context":"build","app_id":%s}]}`, tc.app) + } + case strings.Contains(r.URL.Path, "/branches/") || strings.Contains(r.URL.Path, "/rules/"): + if strings.Contains(tc.name, "names-only") { + fmt.Fprint(w, `{"protected":true,"protection":{"required_status_checks":{"contexts":["build"]}}}`) + } else { + http.Error(w, `{"message":"Resource not accessible by integration"}`, http.StatusForbidden) + } + case strings.HasSuffix(r.URL.Path, "/pulls"): + fmt.Fprint(w, `[{"number":7,"state":"open","title":"Repair source","user":{"login":"person"},"updated_at":"2026-11-02T21:00:00Z","head":{"sha":"head","ref":"repair","repo":{"full_name":"org/repo"}},"base":{"sha":"base","ref":"v5","repo":{"full_name":"org/repo"}}}]`) + case strings.HasSuffix(r.URL.Path, "/pulls/7"): + fmt.Fprint(w, `{"number":7,"state":"open","mergeable":true,"mergeable_state":"clean","head":{"sha":"head"},"base":{"ref":"v5"}}`) + case strings.HasSuffix(r.URL.Path, "/commits/head/check-runs"): + t.Error("GraphQL check evidence unexpectedly fell back to REST") + fmt.Fprint(w, `{"check_runs":[]}`) + case strings.HasSuffix(r.URL.Path, "/commits/v5/check-runs"): + fmt.Fprint(w, `{"check_runs":[]}`) + default: + fmt.Fprint(w, `[]`) + } + })) + defer srv.Close() + client := github.NewClientForTest(srv.URL, "org", []string{"org/repo"}, slog.New(slog.NewTextHandler(io.Discard, nil))) + client.SetGraphQLPRBatchConfig(func() bool { return true }, func() int { return 50 }) + if _, err := client.EnumerateActionable(context.Background()); err != nil { + t.Fatal(err) + } + prs := []github.PullRequest{{Repo: "org/repo", Number: 7, HeadSHA: "head", BaseRef: "v5", UpdatedAt: time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC)}} + client.EnrichCIStatus(context.Background(), prs) + bytes, err := json.Marshal(prs[0]) + if err != nil { + t.Fatal(err) + } + var projected github.PullRequest + if err := json.Unmarshal(bytes, &projected); err != nil { + t.Fatal(err) + } + if projected.CIActivity == nil || projected.CIActivity.Source != "github-graphql-cache" { + t.Fatalf("current-head GraphQL collection provenance was lost: %+v", projected.CIActivity) + } + got := stageTrackerCIActivity(projected, time.Now()) + if got.State != tc.want { + t.Fatalf("collection/cache/dedup/serialization/projection = %+v, want %s; evidence %+v", got, tc.want, projected.CIActivity) + } + if strings.HasPrefix(tc.name, "cyclic ordering") && projected.CIStatus != "failure" { + t.Fatalf("GraphQL collection changed canonical CI with input order: %s", projected.CIStatus) + } + if !tc.denied && (projected.CIActivity == nil || len(projected.CIActivity.RequiredChecks) != 1) { + t.Fatal("required context/app binding was lost") + } + if (tc.denied || tc.app == "missing") && projected.CIActivity.RequiredKnown { + t.Fatal("reader denial was called observed required policy") + } + stale := time.Now().Add(-trackerActivityFreshWindow - time.Second) + projected.CIActivity.ObservedAt = &stale + if activity := stageTrackerCIActivity(projected, time.Now()); activity.Active { + t.Fatal("a stale serialized collection snapshot manufactured active CI") + } + if got.State == "failing" { + expectedID := int64(101) + if strings.HasPrefix(tc.name, "cyclic ordering") { + expectedID = 103 + } + found := false + for _, check := range projected.CIActivity.Checks { + if check.ID == expectedID && check.AppID != nil && *check.AppID == 11 && check.Head == "head" && check.Since != nil { + found = true + } + } + if !found { + t.Fatal("real check ID/app/head/transition time was lost") + } + } + }) + } +} + +func TestStageTrackerSuccessfulSourceEditCollectionThroughProjection(t *testing.T) { + resetAgentLastActions(t) + dir := t.TempDir() + git := func(args ...string) string { + output, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput() + if err != nil { + t.Fatalf("fixture git %v: %v: %s", args, err, output) + } + return strings.TrimSpace(string(output)) + } + git("init", "--quiet", "-b", "fixture") + git("config", "user.name", "Activity Test") + git("config", "user.email", "activity@example.invalid") + git("remote", "add", "origin", "https://github.com/org/repo.git") + file := filepath.Join(dir, "source.go") + if err := os.WriteFile(file, []byte("package before\n"), 0600); err != nil { + t.Fatal(err) + } + git("add", "source.go") + git("commit", "--quiet", "-s", "-m", "fixture") + now := time.Now().UTC() + kick := now.Add(-time.Minute) + editAt := now.Add(-time.Second) + if err := os.WriteFile(file, []byte("package after\n"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(file, editAt, editAt); err != nil { + t.Fatal(err) + } + args, _ := json.Marshal(map[string]string{"path": file}) + transcript := fmt.Sprintf("{\"type\":\"tool.execution_start\",\"timestamp\":%q,\"data\":{\"toolCallId\":\"edit\",\"toolName\":\"edit\",\"arguments\":%s}}\n{\"type\":\"tool.execution_complete\",\"timestamp\":%q,\"data\":{\"toolCallId\":\"edit\",\"success\":true}}\n", editAt.Format(time.RFC3339Nano), args, now.Format(time.RFC3339Nano)) + observation := cruxruntime.ObserveCodeWorkTranscript(strings.NewReader(transcript), dir, kick, now) + if observation == nil { + t.Fatal("actual successful source edit was not collected") + } + proc := &crux.Process{Name: "fixer", Config: config.AgentConfig{Backend: "copilot", Enabled: true}, + State: crux.StateRunning, LastKick: &kick, CodeWork: observation, OutputBuffer: cruxtest.NewRingBuffer(10)} + RecordAgentLastAction(github.AuditRecord{Repo: "org/repo", Target: 7, Agent: "fixer", Action: github.AuditActionAgentCommentCreated}, now) + worker := buildOneAgent(t, proc) + dispatch := review.DispatchState{GeneratedAt: now, Fixes: []review.PendingFix{ + {Repo: "org/repo", Number: 7, HeadSHA: git("rev-parse", "HEAD"), Agent: "fixer", Dispatched: kick}, + }} + it := StageTrackerItem{Kind: "pr", Repo: "org/repo", Number: 7, Head: dispatch.Fixes[0].HeadSHA, Stage: trackerNumberFixing} + stageTrackerApplyCodeActivity(&it, dispatch, &StatusPayload{Agents: []FrontendAgent{worker}}, now) + if !it.CodeActivity.Active || it.DisplayColumn != trackerNumberPRInProgress { + t.Fatalf("producer/process/frontend/assignment/projection lost actual source work: %+v", it.CodeActivity) + } + newKick := now + proc.LastKick = &newKick + worker = buildOneAgent(t, proc) + if worker.CodeWork != nil { + t.Fatal("a new round retained previous-round source evidence") + } +} + +func TestStageTrackerCollectedReviewReceiptDoesNotSettleAnotherAgent(t *testing.T) { + now := time.Now().UTC() + pr, dispatch, status := trackerActivityFixture(now) + status.Agents[0].Name = "B" + dispatch.Pending = []review.PendingReview{ + {Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Perspective: review.PerspectiveCorrectness, Head: "alpha", Agent: "A", Dispatched: now}, + {Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Perspective: review.PerspectiveCorrectness, Head: "beta", Agent: "B", Dispatched: now}, + } + dir := t.TempDir() + writeReport := func(agent, head string) { + t.Helper() + path := filepath.Join(dir, review.ReportFilePrefix(pr.Repo, pr.Number)+agent+".json") + report := fmt.Sprintf(`{"lane":"review-swarm","kind":"review","findings":[],"prs_opened":[],"beads_filed":[],"summary":"Review complete","perspective":"correctness","verdict":"approve","repo":%q,"number":%d,"head_sha":%q,"head":%q,"reporter_agent":%q}`, + pr.Repo, pr.Number, pr.HeadSHA, head, agent) + if err := os.WriteFile(path, []byte(report), 0600); err != nil { + t.Fatal(err) + } + if err := os.Chtimes(path, now, now); err != nil { + t.Fatal(err) + } + } + collect := func() review.Aggregate { + t.Helper() + artifact, err := review.Collect(dir, review.AggregateOptions{}) + if err != nil { + t.Fatal(err) + } + raw, err := json.Marshal(artifact) + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(raw, &artifact); err != nil { + t.Fatal(err) + } + aggregate, ok := artifact.AggregateFor(pr.Repo, pr.Number, pr.HeadSHA) + if !ok { + t.Fatal("collected current-head report was lost") + } + return aggregate + } + writeReport("A", "alpha") + aggregate := collect() + bundle := &evidence.Bundle{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, UpdatedAt: now, + Verdicts: []evidence.Verdict{{Perspective: "correctness", Verdict: "approve", RecordedAt: now}}} + if got := stageTrackerReviewActivity(pr, bundle, &aggregate, dispatch, status, time.Now()); !got.Active || got.Actor != "B" { + t.Fatalf("A's collected same-perspective report hid B: %+v", got) + } + writeReport("B", "beta") + aggregate = collect() + if !review.PendingReviewCompleted(dispatch.Pending[1], review.Artifact{Items: []review.Aggregate{aggregate}}) { + t.Fatal("B's own collected receipt did not settle B") + } + if got := stageTrackerReviewActivity(pr, bundle, &aggregate, dispatch, status, time.Now()); got.Active { + t.Fatalf("B's completed assignment remained active: %+v", got) + } +} diff --git a/src/pkg/dashboard/stage_tracker_decided.go b/src/pkg/dashboard/stage_tracker_decided.go index efed608cde..a4a56167ae 100644 --- a/src/pkg/dashboard/stage_tracker_decided.go +++ b/src/pkg/dashboard/stage_tracker_decided.go @@ -9,6 +9,7 @@ import ( "github.com/hivecommons/hive/pkg/delegatedecision" "github.com/hivecommons/hive/pkg/github/automerge" + "github.com/hivecommons/hive/pkg/review" stageengineprstage "github.com/hivecommons/hive/pkg/stageengine/prstage" "github.com/hivecommons/hive/pkg/stagelabels" ) @@ -202,11 +203,11 @@ func stageTrackerDecided(it StageTrackerItem, sweep automerge.SweepState, now ti d.Effect = decidedEffectPending target := verb.Stage // Decision wins over a stale park label: a row still wearing 085 - // after a recorded direction sits where the hive really is — 070 - // Fixing — not on the ask it already answered (hivecommons/hive#15096 N13). + // after a recorded direction becomes a native 070 repair request, + // not evidence of coding or an unanswered ask (hivecommons/hive#15096 N13). if target == stagelabels.None && verdict == string(delegatedecision.VerdictDirection) && it.Stage == stagelabels.NeedsDecision.Number() { target = stagelabels.Fixing - d.Text = "Fixing · hive is addressing " + stageTrackerReviewerPossessive(it) + " review" + d.Text = "Fix requested · awaiting repair of " + stageTrackerReviewerPossessive(it) + " review" } if target != stagelabels.None { d.StageBefore, d.Stage, d.stage = it.Stage, target.Number(), target @@ -324,6 +325,8 @@ func stageTrackerProjectDecided(it *StageTrackerItem, d *StageTrackerDecided, sw it.Reason = "" if stage == stagelabels.Fixing { it.MergeGate = nil + stageTrackerApplyCodeActivity(it, review.DispatchState{}, nil, now) + it.Caption = it.CodeActivity.Caption } else { it.MergeGate = stageTrackerMergeGate(it.Repo, it.Number, stage, stagelabels.Record{}, false, sweep, now) } diff --git a/src/pkg/dashboard/stage_tracker_decided_test.go b/src/pkg/dashboard/stage_tracker_decided_test.go index f7c2471d9c..3c295d2cb0 100644 --- a/src/pkg/dashboard/stage_tracker_decided_test.go +++ b/src/pkg/dashboard/stage_tracker_decided_test.go @@ -183,7 +183,7 @@ func TestStageTrackerDecidedProjection(t *testing.T) { if pr.DecisionNeeded != nil || contains(pr.Modifiers, modNeedsHuman) || pr.MergeGate != nil { t.Fatalf("stale 085 ask survived the decision: %+v", pr) } - if pr.Caption != "Fixing · hive is addressing @hanthor's review" { + if pr.Caption != "Waiting for fixer · no code work observed" || pr.CodeActivity == nil || pr.CodeActivity.Active || pr.DisplayColumn != trackerNumberReviewPending { t.Fatalf("caption %q", pr.Caption) } if !strings.HasPrefix(pr.Decided.Title, "You chose Let hive decide · hive decided: direction given (") { diff --git a/src/pkg/dashboard/stage_tracker_decided_ui_test.go b/src/pkg/dashboard/stage_tracker_decided_ui_test.go index 002cec590d..a4921a9cc3 100644 --- a/src/pkg/dashboard/stage_tracker_decided_ui_test.go +++ b/src/pkg/dashboard/stage_tracker_decided_ui_test.go @@ -78,7 +78,7 @@ const decidedPending = { action: 'let-hive-decide', verdict: 'adopt-supersede', const original = (over) => Object.assign({ number: 15029, title: 'fix: tracker pill', url: 'u29', stage: 90, author: 'Karibhou', author_kind: 'clanker', modifiers: ['untrusted-author'], human_merge_reason_text: 'untrusted author', manual_merge: true }, over || {}); const issueOf = (prs, over) => Object.assign({ repo: 'hivecommons/hive', number: 15023, kind: 'issue', title: 'Pill contradicts itself', url: 'u23', stage: prs[0].stage, linked_prs: prs }, over || {}); const subHtml = (row, n) => subs(row).find(s => s.includes('pr#' + n + '"')) || ''; -const pill = (html) => text((/
  • /.exec(html) || ['', ''])[0]).replace(/&/g, '&'); +const pill = (html) => text((/
  • /.exec(html) || /([\s\S]*?)<\/li>/.exec(html) || ['', ''])[0]).replace(/&/g, '&'); // ── 1. deciding: the 090 row with the job in flight ───────────────────── // Before the verdict there is no decided projection: the row keeps its @@ -202,8 +202,8 @@ for (const a of ['adopted', 'directed', 'closed', 'merged', 'queued-for-merge', const chipTip = (/class="ham-badge ham-adopted-from"[^>]*title="([^"]*)"/.exec(cp) || [])[1] || ''; assert.ok(chipTip.includes('#15029 is superseded and still open; it closes when this merges.'), 'the chip tooltip names the superseded state: ' + chipTip); assert.ok(!text(cp).includes('untrusted author'), 'the copy is hive-authored'); - assert.strictEqual((row.match(/aria-current="step"/g) || []).length, 1, 'exactly one active chevron: the copy'); - assert.ok(pill(row).includes('CI / Review'), 'the active pill follows the copy: ' + pill(row)); + assert.strictEqual((row.match(/aria-current="step"/g) || []).length, 2, 'one current copy phase, represented by the parallel CI and Review tracks'); + assert.ok(row.includes('data-track="ci"') && row.includes('data-track="review"'), 'the current phase follows the copy as two independent tracks'); assert.ok(!/Approving/.test(row)); // The same muted line without superseded_by (an older payload): adopted_by // with a live copy in the list is enough. diff --git a/src/pkg/dashboard/stage_tracker_fixing_column.test.js b/src/pkg/dashboard/stage_tracker_fixing_column.test.js index 88e8bff696..1c8702ba4f 100644 --- a/src/pkg/dashboard/stage_tracker_fixing_column.test.js +++ b/src/pkg/dashboard/stage_tracker_fixing_column.test.js @@ -38,7 +38,7 @@ const src = [ pick(/const STAGE_TRACKER_TERMINAL = \d+;/, 'STAGE_TRACKER_TERMINAL'), pick(/const STAGE_TRACKER_REPAIR_STAGE_WHY = [^\n]*\n/, 'STAGE_TRACKER_REPAIR_STAGE_WHY'), pick(/function stageTrackerUnderRepair\(stage, reason\) \{[\s\S]*?\n \}\n/, 'stageTrackerUnderRepair'), - pick(/function stageTrackerAnchor\(stage, stages, kind, item\) \{[\s\S]*?\n \}\n/, 'stageTrackerAnchor'), + pick(/function stageTrackerAnchor\(stage, stages, kind, item, presentation\) \{[\s\S]*?\n \}\n/, 'stageTrackerAnchor'), ].join('\n'); const lifted = new Function(src + '; return { anchor: stageTrackerAnchor, underRepair: stageTrackerUnderRepair };')(); @@ -98,8 +98,9 @@ const STAGE_COLUMN = { }; const REPAIR_STAGES = [70, 71, 72, 74]; -function expectedColumn(stage, gate, train, reason) { +function expectedColumn(stage, gate, train, reason, presentation = true) { if (stage >= COLUMN.DONE) return COLUMN.DONE; + if (presentation && [71, 72, 74].includes(stage) && !gate && !train) return COLUMN.PR; // 085 is the decision park: it rides no train but the person decides at the gate. if (stage > COLUMN.PR && stage !== 85 && (REPAIR_STAGES.indexOf(stage) >= 0 || /^(required-)?check-failing:|^ci-red$/.test(reason))) return COLUMN.REVIEW; if (stage > COLUMN.PR && (gate === 'merging' || gate === 'merge-failed')) return COLUMN.MERGE_GATE; @@ -116,6 +117,7 @@ test('ratchet: every state lands in the column its current state earns', () => { const want = expectedColumn(stage, gate, train, reason); const label = 'stage ' + stage + ' gate ' + gate + ' train ' + train + ' reason ' + JSON.stringify(reason); assert.strictEqual(lifted.anchor(stage, STAGES, 'pr', item), want, label); + assert.strictEqual(lifted.anchor(stage, STAGES, 'pr', item, false), expectedColumn(stage, gate, train, reason, false), label + ' native sort/count mapping'); // A row under repair never lands past CI / Review, whatever else it carries. if (lifted.underRepair(stage, reason) && stage > COLUMN.PR && stage !== 85 && stage < COLUMN.DONE) assert.ok(lifted.anchor(stage, STAGES, 'pr', item) <= COLUMN.REVIEW, label + ' promoted while under repair'); cases++; diff --git a/src/pkg/dashboard/stage_tracker_links.go b/src/pkg/dashboard/stage_tracker_links.go index 5b66a5b902..68761b3bd5 100644 --- a/src/pkg/dashboard/stage_tracker_links.go +++ b/src/pkg/dashboard/stage_tracker_links.go @@ -327,6 +327,8 @@ func stageTrackerResolveLinkedPRs(items []StageTrackerItem, open func(repo strin lp.Adoption = pr.Adoption lp.Presence = pr.Presence lp.Rework = pr.Rework + lp.CIActivity, lp.ReviewActivity, lp.CodeActivity = pr.CIActivity, pr.ReviewActivity, pr.CodeActivity + lp.DisplayColumn = pr.DisplayColumn lp.Push = pr.Push lp.Takeover = pr.Takeover lp.Supersedes = pr.Supersedes diff --git a/src/pkg/dashboard/stage_tracker_motion_test.go b/src/pkg/dashboard/stage_tracker_motion_test.go index a20c91e16e..172e70d097 100644 --- a/src/pkg/dashboard/stage_tracker_motion_test.go +++ b/src/pkg/dashboard/stage_tracker_motion_test.go @@ -298,17 +298,17 @@ const col = (kind, stage) => stageTrackerColIndex({ kind, stage }, stages); // Column index follows the drawn anchor: shared columns and detours collapse. assert.strictEqual(col('issue', 0), 0); assert.strictEqual(col('issue', 10), 1); assert.strictEqual(col('issue', 15), 1); assert.strictEqual(col('issue', 20), 2); assert.strictEqual(col('pr', 30), 3); assert.strictEqual(col('pr', 40), 3); -assert.strictEqual(col('pr', 50), 4); assert.strictEqual(col('pr', 60), 4, '060 reviewed is pre-admission: CI / Review, not the merge gate'); assert.strictEqual(col('pr', 70), 4); assert.strictEqual(col('pr', 71), 4); -assert.strictEqual(col('pr', 80), 5); assert.strictEqual(col('pr', 85), 5); assert.strictEqual(col('pr', 90), 5); assert.strictEqual(col('pr', 95), 5); assert.strictEqual(col('pr', 100), 5); +assert.strictEqual(col('pr', 50), 4); assert.strictEqual(col('pr', 60), 4, '060 reviewed is pre-admission: CI / Review, not the merge gate'); assert.strictEqual(col('pr', 70), 4); assert.strictEqual(col('pr', 71), 3, 'native owner wait is PR in progress, not observed coding'); +assert.strictEqual(col('pr', 80), 6); assert.strictEqual(col('pr', 85), 6); assert.strictEqual(col('pr', 90), 6); assert.strictEqual(col('pr', 95), 6); assert.strictEqual(col('pr', 100), 6); assert.strictEqual(col('issue', 45), 1, 'an issue parked on a person lights Actionable'); assert.strictEqual(col('issue', 110), STAGE_TRACKER_CAP_COLUMN, 'merged is the cap column'); -assert.strictEqual(STAGE_TRACKER_CAP_COLUMN, STAGE_TRACKER_PATH.length); +assert.strictEqual(STAGE_TRACKER_CAP_COLUMN, STAGE_TRACKER_PATH.length + 1); const P = (n, stage) => ({ kind: 'pr', repo: 'a/b', number: n, stage }); const I = (n, stage, linked) => ({ kind: 'issue', repo: 'a/b', number: n, stage, linked_prs: linked }); // Column map: plain items, an issue riding its single covering PR, nested PRs keyed on their own. assert.deepStrictEqual(stageTrackerColMap([P(1, 50), I(2, 20), I(3, 20, [{ number: 9, stage: 30 }]), I(4, 20, [{ number: 7, stage: 50 }, { number: 8, stage: 80 }])], stages), - { 'a/b/pr#1': 4, 'a/b/issue#2': 2, 'a/b/issue#3': 3, 'a/b/pr#9': 3, 'a/b/issue#4': 2, 'a/b/pr#7': 4, 'a/b/pr#8': 5 }); + { 'a/b/pr#1': 4, 'a/b/issue#2': 2, 'a/b/issue#3': 3, 'a/b/pr#9': 3, 'a/b/issue#4': 2, 'a/b/pr#7': 4, 'a/b/pr#8': 6 }); assert.deepStrictEqual(stageTrackerColMap(null, stages), {}); assert.deepStrictEqual(stageTrackerColMap([{ kind: 'pr', repo: 'a/b', number: 0 }, null], stages), {}, 'items without a number are skipped'); @@ -319,17 +319,17 @@ assert.deepStrictEqual(stageTrackerColMoves(null, first), {}, 'no previous paylo assert.deepStrictEqual(stageTrackerColMoves(first, first), {}, 'same payload → nothing'); const second = stageTrackerColMap([P(1, 80), P(2, 50), I(3, 10), P(4, 30), I(5, 20, [{ number: 6, stage: 50 }])], stages); assert.deepStrictEqual(stageTrackerColMoves(first, second), { - 'a/b/pr#1': { from: 4, to: 5 }, 'a/b/pr#2': { from: 5, to: 4 }, + 'a/b/pr#1': { from: 4, to: 6 }, 'a/b/pr#2': { from: 6, to: 4 }, 'a/b/issue#5': { from: 3, to: 4 }, 'a/b/pr#6': { from: 3, to: 4 }, }, 'advance, regress, covered issue + its PR; #3 unchanged and new #4 are not moves'); assert.deepStrictEqual(stageTrackerColMoves(stageTrackerColMap([P(1, 50)], stages), stageTrackerColMap([P(1, 70)], stages)), {}, '050 → 070 shares the Review column'); -assert.deepStrictEqual(stageTrackerColMoves(stageTrackerColMap([P(1, 100)], stages), stageTrackerColMap([P(1, 110)], stages)), { 'a/b/pr#1': { from: 5, to: 6 } }, 'merge queue → merged moves to the cap'); +assert.deepStrictEqual(stageTrackerColMoves(stageTrackerColMap([P(1, 100)], stages), stageTrackerColMap([P(1, 110)], stages)), { 'a/b/pr#1': { from: 6, to: 7 } }, 'merge queue → merged moves to the cap'); assert.deepStrictEqual(stageTrackerColMoves({ 'a/b/pr#1': 4 }, { 'c/d/pr#1': 5 }), {}, 'same number in another repo is another PR'); // Row builder attribute: only the moved key gets the stamp. const ctx = { moves: stageTrackerColMoves(first, second) }; -assert.strictEqual(stageTrackerMoveAttrs('a/b/pr#1', ctx), ' data-ham-prev-col="4" data-ham-col="5"'); -assert.strictEqual(stageTrackerMoveAttrs('a/b/pr#2', ctx), ' data-ham-prev-col="5" data-ham-col="4"'); +assert.strictEqual(stageTrackerMoveAttrs('a/b/pr#1', ctx), ' data-ham-prev-col="4" data-ham-col="6"'); +assert.strictEqual(stageTrackerMoveAttrs('a/b/pr#2', ctx), ' data-ham-prev-col="6" data-ham-col="4"'); assert.strictEqual(stageTrackerMoveAttrs('a/b/issue#3', ctx), ''); assert.strictEqual(stageTrackerMoveAttrs('a/b/pr#1', {}), ''); assert.strictEqual(stageTrackerMoveAttrs('a/b/pr#1', null), ''); @@ -338,11 +338,11 @@ assert.strictEqual(stageTrackerMoveAttrs('a/b/pr#1', null), ''); stageTrackerNoteMoves({ items: [P(1, 50)], stages }); assert.deepStrictEqual(_stageTrackerMoves, {}); stageTrackerNoteMoves({ items: [P(1, 80)], stages }); -assert.deepStrictEqual(_stageTrackerMoves, { 'a/b/pr#1': { from: 4, to: 5 } }); +assert.deepStrictEqual(_stageTrackerMoves, { 'a/b/pr#1': { from: 4, to: 6 } }); stageTrackerNoteMoves({ items: [P(1, 80)], stages }); assert.deepStrictEqual(_stageTrackerMoves, {}, 'an unchanged payload clears the pending moves'); stageTrackerNoteMoves({ items: [P(1, 50)], stages }); -assert.deepStrictEqual(_stageTrackerMoves, { 'a/b/pr#1': { from: 5, to: 4 } }, 'regression is a move too'); +assert.deepStrictEqual(_stageTrackerMoves, { 'a/b/pr#1': { from: 6, to: 4 } }, 'regression is a move too'); // Setting: default F (wash), persisted, unknown values fall back, None disables, // reduced motion turns every other choice into the crossfade. @@ -431,6 +431,7 @@ func TestStageTrackerMotionRowStamp(t *testing.T) { jsConstLine(t, html, "STAGE_TRACKER_MOTION_HUMAN_MODS"), jsFunc(t, html, "stageTrackerMotion"), jsFunc(t, html, "stageTrackerShortAgo"), + jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), jsFunc(t, html, "stageTrackerStageWord"), @@ -487,7 +488,7 @@ const ctx = { nowMs: now, stages, moves: stageTrackerColMoves(stageTrackerColMap const ols = html => Array.from(html.matchAll(/
      ]*)>/g)).map(m => m[1]); assert.deepStrictEqual(ols(stageTrackerRowHtml(next[0], stages, ctx)), [' data-ham-prev-col="1" data-ham-col="2"'], 'the moved issue strip is stamped'); assert.deepStrictEqual(ols(stageTrackerRowHtml(next[2], stages, ctx)), [''], 'an unmoved strip carries nothing'); -assert.deepStrictEqual(ols(stageTrackerRowHtml(next[1], stages, ctx)), ['', ' data-ham-prev-col="4" data-ham-col="5"', ''], 'only the nested PR that moved is stamped (sub-rows sort furthest first)'); +assert.deepStrictEqual(ols(stageTrackerRowHtml(next[1], stages, ctx)), ['', ' data-ham-prev-col="4" data-ham-col="6"', ''], 'only the nested PR that moved is stamped (sub-rows sort furthest first)'); assert.deepStrictEqual(ols(stageTrackerRowHtml(next[0], stages, { nowMs: now })), [''], 'no moves in ctx → no stamp'); ` cmd := exec.Command(node, "-e", script) @@ -564,6 +565,7 @@ func TestStageTrackerMotionPreviewSample(t *testing.T) { jsFunc(t, html, "stageTrackerHeaderHtml"), jsFunc(t, html, "stageTrackerHoldLabels"), jsFunc(t, html, "stageTrackerSoakLeft"), + jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), jsFunc(t, html, "stageTrackerStageWord"), @@ -632,7 +634,7 @@ const _stageTracker = { stages }; const PIPE = 'aria-label="Pipeline progress"'; const count = (s, needle) => s.split(needle).length - 1; const chevrons = (s) => count(s.slice(s.indexOf(PIPE)).split('
    ')[0], '
  • ([^<]+)<\/span>/); return m && m[1].trim(); }; +const activeShort = (s) => { const strip = s.slice(s.indexOf(PIPE)).split('')[0]; const m = strip.match(/([^<]+)<\/span>/); return m ? m[1].trim() : strip.includes('data-route-state="active"') ? 'CI + Review' : null; }; // A live row for comparison: the sample must have the same chevron count. const liveRow = stageTrackerRowHtml({ repo: 'hive/x', number: 7, kind: 'issue', title: 'Live', url: '#', stage: 30, stage_since: '' }, stages, { nowMs: Date.now() }); @@ -673,20 +675,21 @@ function stageTrackerMotionEffect(id) { return id; } function stageTrackerReducedMotion() { return false; } // N Preview clicks: still one row, one strip, lit chevron alternating -const want = ['CI / Review', 'Claimed', 'CI / Review', 'Claimed', 'CI / Review']; +const want = ['CI + Review', 'Claimed', 'CI + Review', 'Claimed', 'CI + Review']; for (let i = 0; i < want.length; i++) { stageTrackerPreviewMotion(i % 2 ? 'comet' : 'wash'); const s = sampleEl.innerHTML; assert.strictEqual(count(s, '
    now; const litWord = (html) => text((/
  • ]*>([\s\S]*?)<\/li>/.exec(strip(html)) || ['', ''])[1]); +const assertTracks = (html) => { + assert.strictEqual((strip(html).match(/data-track="ci"/g) || []).length, 1); + assert.strictEqual((strip(html).match(/data-track="review"/g) || []).length, 1); + assert.strictEqual(litWord(html), '', 'a push cannot fabricate observed coding or a reviewer'); +}; const since = new Date(now - 3 * 3600000).toISOString(); const row = (extra) => stageTrackerRowHtml(Object.assign({ repo: 'hivecommons/hive', number: 8, kind: 'pr', title: 'docs', url: 'https://x/8', stage: 71, stage_since: since, caption: 'Needs author', author: 'zoe', author_kind: 'human', stage_actor: { kind: 'human', login: 'zoe', why: '@zoe must act' } }, extra || {}), stages, ctx); const waiting = row({ push: { state: 'waiting', login: 'zoe', since } }); assert.ok(/^Needs @zoe\b/.test(litWord(waiting)), litWord(waiting)); const pushed = row({ stage_actor: { kind: 'hive', why: '@zoe pushed abc1234 — CI runs on the new head' }, push: { state: 'pushed', login: 'zoe', since: new Date(now - 120000).toISOString(), sha: 'abc1234', url: 'https://x/commit/abc1234', next: 'ci' } }); -assert.ok(/^CI \/ Review\b/.test(litWord(pushed)), litWord(pushed)); +assertTracks(pushed); assert.ok(!/ham-actor-ico[^>]*aria-label="Next move: human"/.test(pushed), 'the hive carries it: no person glyph on the chevron'); assert.ok(!/Needs @zoe/.test(litWord(pushed)), litWord(pushed)); assert.ok(pushed.includes('>@zoe pushed abc1234 · 2m'), pushed); assert.ok(pushed.includes('Push: @zoe pushed abc1234 2m ago'), 'hover line'); // 072 the same. const back = row({ stage: 72, caption: 'Returned to contributor', push: { state: 'pushed', login: 'zoe', since: new Date(now - 120000).toISOString(), sha: 'abc1234', next: 're-review' } }); -assert.ok(/^CI \/ Review\b/.test(litWord(back)), litWord(back)); +assertTracks(back); assert.ok(back.includes('pushed abc1234 · re-review pending · 2m'), back); // The nudge names the old head, but no webhook booked a push time. // The canonical backend projection still releases the author wait. const reconciled = row({ stage_actor: { kind: 'hive', why: '@zoe pushed abc1234 — the re-review is queued for the new head' }, head: 'abc1234', caption: 'new head observed → re-review pending', presence: null, rework: null, push: { state: 'pushed', login: 'zoe', sha: 'abc1234', next: 're-review' } }); -assert.ok(/^CI \/ Review\b/.test(litWord(reconciled)), litWord(reconciled)); +assertTracks(reconciled); assert.ok(reconciled.includes('pushed abc1234 · re-review pending'), reconciled); assert.ok(!/waiting on @zoe to push|Needs @zoe/.test(reconciled), reconciled); // A retry on the same head is not a fabricated push. const retry = row({ head: 'abc1234', stage_actor: { kind: 'hive', why: 'checks pending again — no new push requested' }, caption: 'checks pending again on the current head — no new push requested', presence: null, rework: null, push: { state: 'checking', sha: 'abc1234', next: 'ci' } }); -assert.ok(/^CI \/ Review\b/.test(litWord(retry)), litWord(retry)); +assertTracks(retry); assert.ok(retry.includes('checks pending · no new push requested'), retry); assert.ok(!/waiting on @zoe to push|Needs @zoe|pushed abc1234/.test(retry), retry); // A single covering PR keeps the issue's row identity. Its via_pr view @@ -344,7 +349,7 @@ const covered = stageTrackerRowHtml({ repo: 'hivecommons/hive', number: 9, kind: author: 'zoe', author_kind: 'human', state: 'open', caption: 'new head observed → re-review pending', stage_actor: { kind: 'hive', why: 're-review queued for the new head' }, push: { state: 'pushed', login: 'zoe', sha: 'abc1234', next: 're-review' } }] }, stages, ctx); -assert.ok(/^CI \/ Review\b/.test(litWord(covered)), litWord(covered)); +assertTracks(covered); assert.ok(covered.includes('pushed abc1234 · re-review pending'), covered); assert.ok(!/waiting on @zoe to push|Needs @zoe/.test(covered), covered); console.log('push chevron ok'); diff --git a/src/pkg/dashboard/stage_tracker_repo_grouping_test.go b/src/pkg/dashboard/stage_tracker_repo_grouping_test.go index 7c38df2bfc..cbfb593f47 100644 --- a/src/pkg/dashboard/stage_tracker_repo_grouping_test.go +++ b/src/pkg/dashboard/stage_tracker_repo_grouping_test.go @@ -152,6 +152,7 @@ func stageTrackerRepoGroupingHarness(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerMotion"), jsFunc(t, html, "stageTrackerHoldLabels"), jsFunc(t, html, "stageTrackerSoakLeft"), + jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), jsFunc(t, html, "stageTrackerStageWord"), diff --git a/src/pkg/dashboard/stage_tracker_revision_test.go b/src/pkg/dashboard/stage_tracker_revision_test.go new file mode 100644 index 0000000000..c3d05472f1 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_revision_test.go @@ -0,0 +1,147 @@ +package dashboard + +import ( + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/crux" + "github.com/hivecommons/hive/pkg/evidence" + "github.com/hivecommons/hive/pkg/github" + "github.com/hivecommons/hive/pkg/review" +) + +func TestStageTrackerRevisionAdministrationIsNotCodeWork(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + pr, dispatch, status := trackerActivityFixture(now) + dispatch.Fixes = []review.PendingFix{{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Agent: "fixer", Dispatched: now}} + it := StageTrackerItem{Kind: "pr", Repo: pr.Repo, Number: pr.Number, Head: pr.HeadSHA, Stage: trackerNumberFixing} + verified := *status.Agents[1].CodeWork + status.Agents[1].CodeWork = nil + for _, action := range []string{github.AuditActionAgentCommentCreated, github.AuditActionIssueClaimed, + github.AuditActionAgentLabelApplied, github.AuditActionAgentReviewRequested} { + status.Agents[1].LastAction.Action = action + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.CodeActivity.Active || it.CodeActivity.State != "assigned" || it.DisplayColumn != trackerNumberReviewPending { + t.Fatalf("%s manufactured source work: %+v", action, it.CodeActivity) + } + } + for _, mutate := range []func(*crux.CodeWork){ + func(a *crux.CodeWork) { a.Repo = "other/repo" }, + func(a *crux.CodeWork) { a.Head = "old-head" }, + func(a *crux.CodeWork) { a.Source = "agent-says-investigating" }, + func(a *crux.CodeWork) { a.At = now.Add(-time.Second) }, + func(a *crux.CodeWork) { a.KickAt = now.Add(-time.Minute) }, + func(a *crux.CodeWork) { a.ObservedAt = time.Time{} }, + } { + observation := verified + mutate(&observation) + status.Agents[1].CodeWork = &observation + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.CodeActivity.Active { + t.Fatalf("unbound source observation manufactured coding: %+v", observation) + } + } + status.Agents[1].CodeWork = &verified + dispatch.Fixes[0].Number++ + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.CodeActivity.Active { + t.Fatal("another PR's assignment manufactured coding") + } +} + +func TestStageTrackerRevisionOwnReceiptSettlesConcurrentAssignment(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + pr, dispatch, status := trackerActivityFixture(now) + dispatch.Pending = []review.PendingReview{ + {Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Perspective: "quality", Head: "alpha", Agent: "A", ReviewModel: "model-A", Dispatched: now}, + {Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Perspective: "quality", Head: "beta", Agent: "B", ReviewModel: "model-B", Dispatched: now}, + } + status.Agents[0].Name = "B" + bundle := &evidence.Bundle{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, UpdatedAt: now, + Verdicts: []evidence.Verdict{ + {Perspective: "quality", Backend: "backend-A", Model: "model-A", Verdict: "approve", RecordedAt: now}, + {Perspective: "quality", Backend: "backend-B", Model: "model-B", Verdict: "approve", RecordedAt: now}, + }} + agg := &review.Aggregate{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, RecordedAt: now, + Verdict: "approve", MergeEligible: true, Perspectives: map[review.Perspective]review.Verdict{"quality": "approve"}, + Heads: map[review.Perspective][]string{"quality": {"alpha", "beta"}}, + ReportReceipts: []review.ReportReceipt{{Agent: "A", Perspective: "quality", Head: "alpha", ReceivedAt: now}}} + for _, stale := range []review.ReportReceipt{ + {Agent: "A", Perspective: "quality", Head: "beta", ReceivedAt: now}, + {Agent: "B", Perspective: "quality", Head: "alpha", ReceivedAt: now}, + {Agent: "B", Perspective: "quality", Head: "beta", Decided: true, ReceivedAt: now}, + {Agent: "B", Perspective: "quality", Head: "beta", ReceivedAt: now.Add(-time.Second)}, + {Agent: "B", Perspective: "quality", Head: "beta", ReceivedAt: now.Add(time.Second)}, + } { + agg.ReportReceipts = append(agg.ReportReceipts[:1], stale) + if got := stageTrackerReviewActivity(pr, bundle, agg, dispatch, status, now); !got.Active || got.Actor != "B" { + t.Fatalf("A's bundle/tied or mismatched receipt hid B: %+v", got) + } + } + agg.ReportReceipts[1] = review.ReportReceipt{Agent: "B", Perspective: "quality", Head: "beta", ReceivedAt: now} + if got := stageTrackerReviewActivity(pr, bundle, agg, dispatch, status, now); got.Active || got.State != "approved" { + t.Fatalf("B's own report did not settle B: %+v", got) + } + agg.HeadSHA = "old-head" + if got := stageTrackerReviewActivity(pr, bundle, agg, dispatch, status, now); !got.Active || got.Actor != "B" { + t.Fatalf("old-head receipts hid current-round B: %+v", got) + } +} + +func TestStageTrackerRevisionPushAndRetryHaveFreshProvenance(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + pr, dispatch, status := trackerActivityFixture(now) + status.Agents[1].CodeWork = nil + dispatch.Fixes = []review.PendingFix{{Repo: pr.Repo, Number: pr.Number, HeadSHA: pr.HeadSHA, Agent: "fixer", Dispatched: now}} + for _, stage := range []int{trackerNumberFixing, trackerNumberNeedsAuthor, trackerNumberReturned, trackerNumberAdopted} { + for _, state := range []string{pushStatePushed, pushStateChecking} { + it := StageTrackerItem{Kind: "pr", Repo: pr.Repo, Number: pr.Number, Head: pr.HeadSHA, Stage: stage, Author: "owner", + Push: &StageTrackerPush{State: state, Sha: pr.HeadSHA, Since: &now}} + stageTrackerApplyCodeActivity(&it, dispatch, status, now) + if it.CodeActivity.Actor != "" || it.CodeActivity.ObservedAt != nil || it.CodeActivity.Active || + it.CodeActivity.Source == "fix-dispatch" || it.DisplayColumn != trackerNumberReviewPending { + t.Fatalf("worker/owner provenance leaked into %s: %+v", state, it.CodeActivity) + } + if state == pushStateChecking && strings.Contains(it.CodeActivity.Caption, "New head") { + t.Fatal("same-head retry fabricated a new push") + } + } + } +} + +func TestStageTrackerRevisionCachedNameOnlyPolicyRemainsUnknown(t *testing.T) { + now := time.Now() + pr := github.PullRequest{HeadSHA: "head", CIActivity: &github.PRCIActivity{ + Head: "head", Source: "cached-checks", ObservedAt: &now, + RequiredKnown: true, Required: []string{"build"}, + Checks: []github.PRActivityCheck{{Name: "build", State: "completed", Conclusion: "success"}}, + }} + if got := stageTrackerCIActivity(pr, now); got.State != "unknown" || got.Active { + t.Fatalf("old name-only payload manufactured passing CI: %+v", got) + } +} + +func TestStageTrackerRevisionMultipleRequiredAppConstraints(t *testing.T) { + now := time.Now() + first, second := int64(11), int64(22) + pr := github.PullRequest{HeadSHA: "head", CIActivity: &github.PRCIActivity{ + Head: "head", Source: "checks", ObservedAt: &now, + RequiredKnown: true, RequiredSource: "rules", Required: []string{"build"}, + RequiredChecks: []github.PRRequiredCheck{ + {Name: "build", AppID: &first, AppKnown: true}, + {Name: "build", AppID: &second, AppKnown: true}, + }, + Checks: []github.PRActivityCheck{ + {Name: "build", AppID: &first, State: "completed", Conclusion: "success"}, + {Name: "build", AppID: &second, State: "completed", Conclusion: "success"}, + }, + }} + if got := stageTrackerCIActivity(pr, now); got.State != "passing" { + t.Fatalf("distinct required producers became an ambiguous retry: %+v", got) + } + pr.CIActivity.Checks[0].Conclusion = "failure" + if got := stageTrackerCIActivity(pr, now); got.State != "failing" { + t.Fatalf("a required producer's failure was hidden: %+v", got) + } +} diff --git a/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go b/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go index 10bc03a06f..2fc653a6da 100644 --- a/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go +++ b/src/pkg/dashboard/stage_tracker_sentinel_lane_test.go @@ -376,13 +376,13 @@ assert.ok(lit[1].includes('title="' + TIP + ' — '), 'the chevron tooltip leads assert.ok(lit[1].includes('aria-current="step"')); assert.ok(lit[1].includes('aria-label="Sentinel alert · needs human — ' + TIP + '"'), 'aria-label carries the wording: ' + lit[1]); assert.ok(lit[2].includes('aria-label="Next move: human"'), 'the 👤 actor icon stays'); -assert.ok(parked.includes('

    Needs human decision · Sentinel alert · needs human · Next move: human

    '), 'the compact caption says it too: ' + parked); +assert.ok(parked.includes('

    Needs human decision · Sentinel alert · needs human · Next move: human'), 'the compact caption preserves the human gate beside independent tracks: ' + parked); assert.ok(!parked.includes('ham-badge-sentinel'), 'no chip when the lane word already says it'); assert.ok(parked.includes(esc(TIP)), 'the PR link tooltip carries the sentinel line'); // Other lanes: chip beside the modifier pill, same tooltip. const review = stageTrackerRowHtml(P('o/r', 110, 50, Object.assign({ modifiers: ['needs-rebase'] }, flagged)), stages, ctx); -assert.ok(review.includes('') === false && review.includes('CI / Review'), 'lane word unchanged off the merge gate'); +assert.ok(!review.includes('') && review.includes('data-track="ci"') && review.includes('data-track="review"'), 'the informational notice preserves both independent tracks off the merge gate'); const chips = /([\s\S]*?)<\/span><\/li>/.exec(review); assert.ok(chips, review); assert.ok(/^sentinel<\/span>needs rebase<\/span>$/.test(chips[1]), 'sentinel chip leads the chip area: ' + chips[1]); diff --git a/src/pkg/dashboard/stage_tracker_status_collection_test.go b/src/pkg/dashboard/stage_tracker_status_collection_test.go new file mode 100644 index 0000000000..fa8d775336 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_status_collection_test.go @@ -0,0 +1,179 @@ +package dashboard + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/github" +) + +func TestStageTrackerRESTCheckPaginationMustCompleteBeforeProjection(t *testing.T) { + for _, mode := range []string{"complete", "partial", "malformed"} { + t.Run(mode, func(t *testing.T) { + reads := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/pulls/7"): + fmt.Fprint(w, `{"number":7,"mergeable":true,"mergeable_state":"blocked","head":{"sha":"head"},"base":{"ref":"v5"}}`) + case strings.HasSuffix(r.URL.Path, "/commits/head/check-runs"): + reads++ + if mode == "malformed" { + fmt.Fprint(w, `{}`) + } else if r.URL.Query().Get("page") == "2" { + if mode == "partial" { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + } else { + fmt.Fprint(w, `{"check_runs":[{"id":103,"name":"validate","head_sha":"head","app":{"id":11},"status":"completed","conclusion":"failure"}]}`) + } + } else { + w.Header().Set("Link", fmt.Sprintf(`; rel="next"`, r.Host, r.URL.Path)) + fmt.Fprint(w, `{"check_runs":[{"id":101,"name":"validate","head_sha":"head","app":{"id":11},"status":"completed","conclusion":"success"}]}`) + } + case strings.HasSuffix(r.URL.Path, "/protection/required_status_checks"): + fmt.Fprint(w, `{"contexts":["validate"],"checks":[{"context":"validate","app_id":11}]}`) + default: + fmt.Fprint(w, `{}`) + } + })) + defer srv.Close() + client := github.NewClientForTest(srv.URL, "org", []string{"repo"}, slog.New(slog.NewTextHandler(io.Discard, nil))) + client.SetGraphQLPRBatchConfig(func() bool { return false }, func() int { return 50 }) + prs := []github.PullRequest{{Repo: "org/repo", Number: 7, HeadSHA: "head", BaseRef: "v5", MergeableState: "blocked"}} + client.EnrichCIStatus(context.Background(), prs) + got := stageTrackerCIActivity(prs[0], time.Now()) + if mode == "complete" { + if reads != 2 || got.State != "failing" || prs[0].CIStatus != "failure" { + t.Fatalf("later-page required failure was lost: reads=%d, %+v", reads, got) + } + } else if got.State != "unknown" || prs[0].CIStatus == "success" || + (prs[0].Protection != nil && len(prs[0].Protection.MissingRequiredChecks) != 0) { + t.Fatalf("incomplete check collection invented a verdict or absence: %+v", got) + } + }) + } +} + +func TestStageTrackerRESTCommitStatusCollectionAndRequiredBinding(t *testing.T) { + for _, tc := range []struct { + name, app, status, want string + missing, red bool + }{ + {"any-app passing", "null", "success", "passing", false, false}, + {"any-app failing", "null", "failure", "failing", false, true}, + {"any-app pending", "null", "pending", "queued", false, false}, + {"any-app error", "-1", "error", "failing", false, true}, + {"explicit-any-app passing", "-1", "success", "passing", false, false}, + {"pinned-app cannot use unbound success", "11", "success", "unknown", false, false}, + {"pinned-app unbound pending", "11", "pending", "unknown", false, false}, + {"status-reader denied", "null", "denied", "unknown", false, false}, + {"status-reader partial", "null", "partial", "unknown", false, false}, + {"wrong-head statuses", "null", "wrong-head", "unknown", false, false}, + {"observed absent from both sources", "null", "absent", "missing", true, false}, + {"malformed status reader", "null", "malformed", "unknown", false, false}, + {"check and status passing", "null", "success", "passing", false, false}, + {"check and status failing", "null", "failure", "failing", false, true}, + {"check and status pending", "null", "pending", "queued", false, false}, + {"check and denied status", "null", "denied", "unknown", false, false}, + {"check and malformed status", "null", "malformed", "unknown", false, false}, + {"missing status context", "null", "malformed-context", "unknown", false, false}, + {"unknown published status state", "null", "mystery", "unknown", false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + statusReads := 0 + withCheck := strings.HasPrefix(tc.name, "check and") + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/pulls/7"): + fmt.Fprint(w, `{"number":7,"state":"open","mergeable":true,"mergeable_state":"blocked","head":{"sha":"head"},"base":{"ref":"v5"}}`) + case strings.HasSuffix(r.URL.Path, "/check-runs"): + if withCheck { + fmt.Fprint(w, `{"total_count":1,"check_runs":[{"id":301,"name":"validate","head_sha":"head","app":{"id":22},"status":"completed","conclusion":"success"}]}`) + } else { + fmt.Fprint(w, `{"total_count":0,"check_runs":[]}`) + } + case strings.HasSuffix(r.URL.Path, "/protection/required_status_checks"): + fmt.Fprintf(w, `{"contexts":["validate"],"checks":[{"context":"validate","app_id":%s}]}`, tc.app) + case strings.HasSuffix(r.URL.Path, "/status"): + statusReads++ + switch tc.status { + case "denied": + http.Error(w, `{"message":"Resource not accessible by integration"}`, http.StatusForbidden) + case "partial": + if r.URL.Query().Get("page") == "2" { + http.Error(w, `{"message":"unavailable"}`, http.StatusServiceUnavailable) + } else { + w.Header().Set("Link", fmt.Sprintf(`; rel="next"`, r.Host, r.URL.Path)) + fmt.Fprint(w, `{"sha":"head","statuses":[]}`) + } + case "wrong-head": + fmt.Fprint(w, `{"sha":"old-head","statuses":[{"id":201,"context":"validate","state":"success"}]}`) + case "absent": + fmt.Fprint(w, `{"sha":"head","statuses":[]}`) + case "malformed": + fmt.Fprint(w, `{}`) + case "malformed-context": + fmt.Fprint(w, `{"sha":"head","statuses":[{"id":201,"state":"success"}]}`) + default: + fmt.Fprintf(w, `{"sha":"head","statuses":[{"id":201,"node_id":"actual-status-node","context":"validate","state":%q,"created_at":"2026-11-02T12:00:00Z","target_url":"https://github.com/org/repo/commit/head"}]}`, tc.status) + } + default: + fmt.Fprint(w, `{}`) + } + })) + defer srv.Close() + client := github.NewClientForTest(srv.URL, "org", []string{"repo"}, slog.New(slog.NewTextHandler(io.Discard, nil))) + client.SetGraphQLPRBatchConfig(func() bool { return false }, func() int { return 50 }) + prs := []github.PullRequest{{Repo: "org/repo", Number: 7, HeadSHA: "head", BaseRef: "v5", MergeableState: "blocked"}} + client.EnrichCIStatus(context.Background(), prs) + raw, err := json.Marshal(prs[0]) + if err != nil { + t.Fatal(err) + } + var pr github.PullRequest + if err := json.Unmarshal(raw, &pr); err != nil { + t.Fatal(err) + } + if statusReads == 0 || pr.CIActivity == nil || !pr.CIActivity.RequiredKnown || pr.CIActivity.RequiredSource != "protection" { + t.Fatalf("actual protection/status readers were bypassed: reads=%d, %+v", statusReads, pr.CIActivity) + } + if got := stageTrackerCIActivity(pr, time.Now()); got.State != tc.want { + t.Fatalf("REST/checks/protection/status/JSON/projection = %+v, want %s; raw %s", got, tc.want, raw) + } + if pr.Protection == nil { + t.Fatal("canonical protection facts were dropped") + } + if got := len(pr.Protection.MissingRequiredChecks) > 0; got != tc.missing { + t.Fatalf("canonical missing=%v, want %v: %+v", got, tc.missing, pr.Protection) + } + if got := len(pr.Protection.FailingRequiredChecks) > 0; got != tc.red { + t.Fatalf("canonical failing=%v, want %v: %+v", got, tc.red, pr.Protection) + } + if tc.want == "passing" || tc.want == "failing" || tc.want == "queued" { + a := pr.CIActivity + foundStatus := false + for _, check := range a.Checks { + foundStatus = foundStatus || (check.ID == 201 && check.Kind == "commit_status" && check.Head == "head") + } + if !a.StatusesKnown || a.StatusesObservedAt == nil || !foundStatus { + t.Fatalf("real status identity/provenance was lost: %+v", a) + } + if !withCheck { + staleChecks := time.Now().Add(-trackerActivityFreshWindow - time.Second) + a.ObservedAt = &staleChecks + got := stageTrackerCIActivity(pr, time.Now()) + if got.ObservedAt == nil || !got.ObservedAt.Equal(*a.StatusesObservedAt) || got.Active { + t.Fatalf("status freshness inherited the unrelated check snapshot: %+v", got) + } + } + } + }) + } +} diff --git a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go index db8011ba3b..cc9b4a8d4f 100644 --- a/src/pkg/dashboard/stage_tracker_ui_prelude_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_prelude_test.go @@ -94,6 +94,7 @@ func stageTrackerRowsPreludeJS(t *testing.T, html string) string { jsFunc(t, html, "stageTrackerTrainIconHtml"), jsFunc(t, html, "stageTrackerHoldLabels"), jsFunc(t, html, "stageTrackerSoakLeft"), + jsFunc(t, html, "stageTrackerActivityTrackHtml"), jsFunc(t, html, "stageTrackerStripItems"), jsFunc(t, html, "stageTrackerCurrentStageHtml"), jsFunc(t, html, "stageTrackerStageWord"), @@ -199,7 +200,11 @@ stageTrackerRowHtml = (item, stages, ctx) => { rebaseCoherent(item); return rawR const strips = (row) => row.split('aria-label="Pipeline progress"').slice(1); const strip = (row) => strips(row)[0].split('

    row.split('
    Array.from(strip(html).matchAll(/
  • m[1]); +// These route fixtures pin the native aggregate stage geometry. Track-specific +// physical columns and simultaneous activity are covered by stage_tracker_activity.test.js. +const segStates = (html) => Array.from(strip(html).matchAll(/
  • ]*)/g)) + .filter(m => !m[2].includes('data-track="review"')) + .map(m => m[2].includes('data-track="ci"') ? (/data-route-state="([^"]*)"/.exec(m[2]) || [])[1] : m[1]); // Visible title occurrences (element text only; title="" attrs excluded). const titles = (html, t) => (html.match(new RegExp('>' + t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '<', 'g')) || []).length; const prCol = (html) => Array.from(html.slice(0, html.indexOf('aria-label="Pipeline progress"')).matchAll(/]*>(.*?)<\/a>/g)).map(m => m[1]); diff --git a/src/pkg/dashboard/stage_tracker_ui_rows_test.go b/src/pkg/dashboard/stage_tracker_ui_rows_test.go index a9e3f8343d..88aa80cc10 100644 --- a/src/pkg/dashboard/stage_tracker_ui_rows_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_rows_test.go @@ -35,7 +35,7 @@ assert.ok(/aria-label="Pipeline progress">[\s\S]*?<\/ol>\s*[\s\S]*?<\/span><\/li><\/ol><\/span><\/div>\s*<\/div>\s*
    /.test(row), 'the chip cell closes the title line, directly above its own strip row'); assert.ok(row.indexOf('
    ') < row.indexOf('ham-badges') && row.indexOf('ham-badges') < row.indexOf('aria-label="Pipeline progress"'), 'chip and strip share one row container'); assert.ok(row.includes('ham-kind-ico'), 'kind icon'); -assert.strictEqual((strip(row).match(/Returned to @karibhou's clanker'), row); // Invariant: a PR never occupies the issue slot. A PR with no linked issue @@ -327,14 +327,13 @@ row = stageTrackerRowHtml({ repo: 'acme/console', number: 107, kind: 'pr', stage assert.ok(row.includes('ham-mod-needs-decision">needs human decision') && tooltip(row).includes('Flags: needs human decision'), row); // Whose move it is, as an ink-coloured icon after the word: Review = hive, // PR in progress = the PR author, Claimed = the claimant; Open/Actionable carry none. -assert.ok(row.includes('CI / ReviewReturned to contributorNeeds @samFix it'), prCol(sr[0])[0]); assert.deepStrictEqual(segStates(sr[0]), [B, B, B, D, 'active detoured', T, 'todo cap'], 'PR strip starts at PR in progress'); -assert.ok(sr[0].includes('Fixing1h') > sr[0].indexOf('aria-label="Pipeline progress"') && sr[0].includes('ham-mod-needs-rebase">needs rebase'), 'Fixing is the author\'s move; the chip says what is being fixed: ' + sr[0]); +assert.ok(sr[0].includes('Waiting for fixer') && !sr[0].includes('ham-actor-ico') && sr[0].indexOf('1h') > sr[0].indexOf('aria-label="Pipeline progress"') && sr[0].includes('ham-mod-needs-rebase">needs rebase'), 'a rebase label and next mover cannot manufacture observed coding: ' + sr[0]); assert.ok(/^ data-ham-kind="pr" data-ham-stage="70" data-ham-sub-key="acme\/console\/pr#102">/.test(sr[0]) && /]*title="Fix it · Fixing review findings Rebasing onto main/.test(sr[0]), 'sub-row tooltip rides the PR link, not the container: ' + sr[0].slice(0, 400)); assert.ok(prCol(sr[1])[0].includes('ham-author-clanker') && prCol(sr[1])[0].includes('#103')); assert.deepStrictEqual(segStates(sr[1]), [B, B, B, 'active', T, T, 'todo cap'], 'a PR at 030 lights PR in progress on its own sub-row'); @@ -534,7 +533,7 @@ assert.strictEqual(stageTrackerSortKey({ kind: 'pr', stage: 72 }, stages).anchor // Header: names once, aligned with the chevrons, plus the since column. const head = stageTrackerHeaderHtml(stages); -assert.deepStrictEqual(Array.from(head.matchAll(/(?:)?([^<]*)<\/span>/g)).map(m => m[1]), ['Open', 'Actionable', 'Claimed', 'PR in progress', 'CI / Review', 'Merge queue']); +assert.deepStrictEqual(Array.from(head.matchAll(/(?:)?([^<]*)<\/span>/g)).map(m => m[1]), ['Open', 'Actionable', 'Claimed', 'PR in progress', 'CI', 'Review', 'Merge queue']); // The Merge queue column wears the train icon (hover "Merge queue"), the // same railcar as the train header chip and the 080 chevron (#15395). assert.ok(head.includes('' + stageTrackerTrainIconHtml('ham-ico ham-train-icon ham-col-ico') + 'Merge queue'), head); @@ -551,6 +550,11 @@ assert.deepStrictEqual(segStates(row), ['active', T, T, T, T, T, 'todo cap']); const prWords = {}; for (const [st, word, actor] of [[50, 'CI / Review', 'hive'], [60, 'Review passed', 'hive'], [70, 'Fixing', 'author'], [71, 'Needs author', 'author'], [72, 'Returned to contributor', 'author'], [74, 'Adopted by hive', 'hive'], [80, 'Ready for auto merge', 'hive'], [85, 'Needs human decision', 'human'], [90, 'Ready for human merge', 'human'], [100, 'Merging', 'hive']]) { const r = stageTrackerRowHtml({ repo: 'acme/console', number: 500 + st, kind: 'pr', stage: st, author_kind: 'clanker' }, stages, ctx); + if ([50, 60, 70, 71, 72, 74].includes(st)) { + assert.ok(r.includes('data-track="ci"') && r.includes('data-track="review"'), 'pre-gate tracks remain separate at ' + st); + assert.ok(r.includes('CI unknown') && r.includes('Review unknown'), 'legacy labels alone cannot supply activity at ' + st); + continue; + } const m = /aria-current="step">]*>[\s\S]*?<\/svg>([^<]*)<\/span>]*aria-label="Next move: ([a-z]+)"[^>]*>/.exec(r); assert.ok(m, 'stage ' + st + ' has no active word + actor: ' + r); assert.deepStrictEqual([m[1], m[2]], [word, actor === 'author' ? 'clanker' : actor], 'stage ' + st); @@ -559,8 +563,8 @@ for (const [st, word, actor] of [[50, 'CI / Review', 'hive'], [60, 'Review passe // The responsive caption names the column, the detour word when there is one, // and the next mover for the strip's active segment; it stays empty when no // active segment is in range. -assert.strictEqual(stageTrackerCurrentStageHtml({ repo: 'acme/console', number: 570, kind: 'pr', stage: 70, author_kind: 'clanker' }, stages), '

    CI / Review · Fixing · Next move: clanker

    '); -assert.strictEqual(stageTrackerCurrentStageHtml({ repo: 'acme/console', number: 560, kind: 'pr', stage: 60 }, stages), '

    Review passed · Next move: hive

    ', 'no detour → column word only'); +assert.strictEqual(stageTrackerCurrentStageHtml({ repo: 'acme/console', number: 570, kind: 'pr', stage: 70, author_kind: 'clanker' }, stages), '

    CI + Review · Waiting for fixer · activity unknown

    '); +assert.strictEqual(stageTrackerCurrentStageHtml({ repo: 'acme/console', number: 560, kind: 'pr', stage: 60 }, stages), '

    CI + Review

    ', 'a reviewed label is not current-head independent approval evidence'); assert.strictEqual(stageTrackerCurrentStageHtml({ repo: 'acme/console', number: 570, kind: 'pr', stage: 70, author_kind: 'clanker' }, stages, { from: 500 }), '', 'no caption when the active segment is out of range'); assert.strictEqual(STAGE_TRACKER_ACTOR[70], 'author', '070 fixing is the author\'s move'); // Filters. @@ -606,13 +610,14 @@ assert.deepStrictEqual(stageTrackerVisible(g, { kind: 'pr', repo: '' }).map(it = // sub-row container, kind / author / actor icons, chips, since cells and // every non-active chevron carry none; icons expose their label via aria-label. const tags = (html) => Array.from(html.matchAll(/<(\w+)\b([^>]*)>/g)).map(m => ({ tag: m[1], attrs: m[2] })); -const titled = (html) => tags(html).filter(t => / title="/.test(t.attrs)); +const titled = (html) => tags(html).filter(t => / title="/.test(t.attrs) && !t.attrs.includes('data-track=')); const expectTitles = (html, want, what) => assert.deepStrictEqual(titled(html).map(t => t.tag + '.' + ((/class="([^" ]+)/.exec(t.attrs) || [])[1] || '')), want, what + ': ' + html); assert.ok(!/]*>\s*/.test(golden), 'no svg <title> tooltips anywhere in the tracker'); assert.ok(!/<(div|span)[^>]*class="ham-(row|sub|since|badge|kind-ico)[^>]*title="/.test(golden), 'containers, since cells, chips and kind icons carry no title'); for (const r of golden.split('<div class="ham-row"').slice(1)) { const seg = Array.from(r.matchAll(/<li class="ham-seg ([^"]*)"([^>]*)>/g)); for (const m of seg) { + if (m[2].includes('data-track=')) continue; // Independent evidence tooltips are pinned in the activity-track tests. const isActive = /\bactive\b/.test(m[1]); assert.strictEqual(/ title="/.test(m[2]), isActive, (isActive ? 'active chevron needs a title' : 'inactive chevron must have no title') + ': ' + m[0]); } @@ -624,13 +629,13 @@ assert.ok(/<li class="ham-seg active" title="Claimed" aria-current="step">/.test assert.ok(/<a class="ham-ref"[^>]*title="[^"]*@ann[^"]*"/.test(row), 'the #N link carries the full row tooltip'); // Issue with one PR: #N link, issue title, PR link (its title + author), active chevron. row = stageTrackerRowHtml(g[1], stages, ctx); -expectTitles(row, ['a.ham-ref', 'span.ham-title', 'a.ham-pr-ref', 'li.ham-seg'], 'issue with one PR'); +expectTitles(row, ['a.ham-ref', 'span.ham-title', 'a.ham-pr-ref'], 'issue with one PR; independent track tooltips are separate'); assert.ok(/<a class="ham-pr-ref"[^>]*title="The one PR Author: hive · @hive-bot · linked PR, shown on its issue's row"/.test(row), 'the PR link also explains the shared row: ' + row); // tracker-cues: with no agent on the item the chevron is static (waiting); // the pulse and the "Working now" lead need a worker in ctx.workers. -assert.ok(/<li class="ham-seg active" title="Review pending · Next move: hive" aria-current="step">/.test(row), 'active chevron: stage + whose move (nobody working: static): ' + row); +assert.ok(row.includes('CI unknown') && row.includes('Review unknown') && !strip(row).includes('data-motion='), 'a stage label alone supplies no activity: ' + row); row = stageTrackerRowHtml(g[1], stages, Object.assign({}, ctx, { workers: { 'g/r#21': { agent: 'scout', action: 'agent_comment_created', at: new Date(now - 120000).toISOString() } } })); -assert.ok(/<li class="ham-seg active" data-motion="active" title="Working now: scout commented · 2m ago — Review pending · Next move: hive" aria-current="step">/.test(row), 'active chevron: working lead + pulse when an agent is on the nested PR: ' + row); +assert.ok(row.includes('Review unknown') && !strip(row).includes('data-motion='), 'a generic commenter is not a current-head reviewer: ' + row); assert.ok(/class="ham-row cue-working"/.test(row), 'the row carries the working cue: ' + row); assert.ok(!/<li class="ham-seg active" data-motion=[^>]*title="Claimed"/.test(stageTrackerRowHtml(g[0], stages, ctx)), 'Claimed is static: no data-motion'); // Issue with two PRs: #N link + title on the issue line, nothing lit there; diff --git a/src/pkg/dashboard/static-src/css/tracker.css b/src/pkg/dashboard/static-src/css/tracker.css index 14449263ea..3af192b832 100644 --- a/src/pkg/dashboard/static-src/css/tracker.css +++ b/src/pkg/dashboard/static-src/css/tracker.css @@ -108,7 +108,7 @@ minus the fixed 4em cap and the six gaps) plus the two gaps between them, so the PR cell starts at the PR in progress chevron; the PR cell takes what is left and gives way to the chip, which lives in the cap cell. */ - .ham-head-cols .ham-seg.ham-head-lead { flex: 0 0 calc((100% - 4em - 6 * var(--sp-1)) / 2 + 2 * var(--sp-1)); padding: 0 var(--sp-6) 0 0; } + .ham-head-cols .ham-seg.ham-head-lead { flex: 0 0 calc((100% - 4em - var(--ham-visible-columns) * var(--sp-1)) * 3 / var(--ham-visible-columns) + 2 * var(--sp-1)); padding: 0 var(--sp-6) 0 0; } .ham-head-cols .ham-seg.ham-head-lead.ham-head-wide { flex: 1 1 0; } /* The PR cell is one line: connector, author icon + #N + title, lineage chip and base pill sit side by side; the lineage chip gives way first @@ -326,8 +326,16 @@ .ham-badge-reroute { color: var(--status-warn); border-color: color-mix(in srgb, var(--status-warn) 55%, transparent); font-weight: var(--fw-medium); display: inline-flex; align-items: center; gap: var(--sp-1); } .ham-badge-reroute .ham-presence-dot { width: 0.5em; height: 0.5em; border-radius: var(--r-pill); background: var(--text-faint); flex: 0 0 auto; } .ham-badge-reroute.ham-reroute-online .ham-presence-dot { background: var(--status-ok); } - .ham-strip { list-style: none; margin: 0; padding: 0; display: flex; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; --ham-notch: 8px; } + .ham-strip { list-style: none; margin: 0; padding: 0; display: flex; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; --ham-notch: 8px; --ham-visible-columns: 7; } + .ham-strip:not(.ham-head-cols) { display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; } .ham-seg { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: center; justify-content: center; padding: 0 var(--sp-4) 0 var(--sp-5); font-size: var(--fs-xs); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%, var(--ham-notch) 50%); } + .ham-activity-track { clip-path: none; border: var(--line-width) solid var(--line-subtle); border-radius: var(--r-sm); flex-direction: column; align-items: flex-start; padding: var(--sp-1) var(--sp-2); white-space: normal; } + .ham-track-name { font-weight: var(--fw-semibold); } + .ham-track-state { overflow-wrap: anywhere; font-size: var(--fs-xs); } + .ham-track-state a { color: inherit; } + .ham-track-code-note, .ham-track-context { overflow-wrap: anywhere; font-size: var(--fs-xs); } + .ham-track-freshness { position: absolute; right: var(--sp-1); top: 0; color: var(--amber); } + .ham-activity-track[data-activity-state="failing"], .ham-activity-track[data-activity-state="changes_requested"] { border-color: var(--amber); color: var(--amber); } .ham-seg:first-child { clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%); } .ham-seg.cap { flex: 0 0 4em; } .ham-seg.active.merged { background: var(--green); color: var(--surface-0); animation: none; } @@ -753,6 +761,10 @@ /* Keep the aligned progress strip compact; put its active step in a wrapping caption instead of squeezing actionable words into a chevron. */ .ham-cols .ham-seg-t, .ham-row .ham-seg-t, .ham-row .ham-detour { display: none; } + .ham-cols .ham-track-head .ham-seg-t { display: inline; } + .ham-track-state { display: none; } + .ham-track-code-note, .ham-track-context { display: none; } + .ham-activity-track { align-items: center; } .ham-active-ico { display: block; } .ham-row .ham-actor-ico { display: none; } .ham-current-stage { display: block; } diff --git a/src/pkg/dashboard/static-src/js/tracker-motion.js b/src/pkg/dashboard/static-src/js/tracker-motion.js index 31a9c6bc37..4d0dfcd7e0 100644 --- a/src/pkg/dashboard/static-src/js/tracker-motion.js +++ b/src/pkg/dashboard/static-src/js/tracker-motion.js @@ -387,7 +387,7 @@ // refresh runs then. const STAGE_TRACKER_SETTLE_MS = 1200; const STAGE_TRACKER_HEADER_KEY = '__cols'; - const STAGE_TRACKER_CAP_COLUMN = STAGE_TRACKER_PATH.length; + const STAGE_TRACKER_CAP_COLUMN = STAGE_TRACKER_PATH.length + 1; var _stageTrackerCols = null; var _stageTrackerMoves = {}; var _stageTrackerRowSrc = typeof WeakMap === 'function' ? new WeakMap() : null; @@ -398,7 +398,8 @@ function stageTrackerColIndex(item, stages) { const anchor = stageTrackerAnchor(item.stage, stages, item.via_pr ? 'pr' : item.kind, item); if (anchor >= STAGE_TRACKER_TERMINAL) return STAGE_TRACKER_CAP_COLUMN; - return STAGE_TRACKER_PATH.indexOf(anchor); + const idx = STAGE_TRACKER_PATH.indexOf(anchor); + return idx + (anchor > 50 ? 1 : 0); } // Pure: item key → column for every row a payload draws. An issue with @@ -410,9 +411,9 @@ for (const it of items) { if (!it || !it.kind || !(Number(it.number) > 0)) continue; const linked = it.kind === 'issue' ? stageTrackerLinkedSorted(it, stages).filter(lp => lp && Number(lp.number) > 0) : []; - const shown = linked.length === 1 ? Object.assign({}, it, { via_pr: true, stage: linked[0].stage || 40 }) : it; + const shown = linked.length === 1 ? Object.assign({}, it, { via_pr: true, stage: linked[0].stage || 40, display_column: linked[0].display_column || 0, head: linked[0].head, code_activity: linked[0].code_activity }) : it; out[stageTrackerItemKey(it)] = stageTrackerColIndex(shown, stages); - for (const lp of linked) out[stageTrackerItemKey({ repo: it.repo, kind: 'pr', number: lp.number })] = stageTrackerColIndex({ kind: 'pr', stage: lp.stage || 0 }, stages); + for (const lp of linked) out[stageTrackerItemKey({ repo: it.repo, kind: 'pr', number: lp.number })] = stageTrackerColIndex({ kind: 'pr', stage: lp.stage || 0, display_column: lp.display_column || 0, head: lp.head, code_activity: lp.code_activity }, stages); } return out; } diff --git a/src/pkg/dashboard/static-src/js/tracker-row-anchor.js b/src/pkg/dashboard/static-src/js/tracker-row-anchor.js index 314194e50d..807d3c153e 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-anchor.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-anchor.js @@ -16,9 +16,19 @@ // attempt that found the conflict) or a planner-ordered merge_train // still rides on the record — hive's own #15574 read "Fixing" under // Merge queue after "fell back to Fixing — conflicting". - function stageTrackerAnchor(stage, stages, kind, item) { + function stageTrackerAnchor(stage, stages, kind, item, presentation) { const cur = Number(stage) || 0; if (cur >= STAGE_TRACKER_TERMINAL) return STAGE_TRACKER_TERMINAL; + // Backend evidence owns this presentation mapping, never a label or + // client-side interpretation of a CI failure. Native stages stay intact. + const displayHeadMatches = item && item.code_activity && String(item.code_activity.head || '') === String(item.head || ''); + if (presentation !== false && cur < 80 && displayHeadMatches && (Number(item.display_column) === 30 || Number(item.display_column) === 50)) return Number(item.display_column); + // Older payloads can identify owner waits/adoption, but cannot prove + // coding. Keep their native words; never use this fallback for counts/sort. + if (presentation !== false && item && !item.code_activity && !item.merge_gate && !item.merge_train && [71, 72, 74].includes(cur)) { + if (item.push && ['pushed', 'checking'].includes(item.push.state)) return 50; + return STAGE_TRACKER_PR_COLUMN; + } // Under repair past 030 → CI / Review, before any gate or train // promotion. The one park the predicate also names, 085 needs // decision, stays at the gate: the person decides there. diff --git a/src/pkg/dashboard/static-src/js/tracker-row-layout.js b/src/pkg/dashboard/static-src/js/tracker-row-layout.js index 6f44f80fcd..381e89a538 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-layout.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-layout.js @@ -14,6 +14,8 @@ function stageTrackerSinceHtml(item, nowMs) { const mods = Array.isArray(item.modifiers) ? item.modifiers : []; let sinceMs = Date.parse(item.stage_since || ''); + const code = item.code_activity; + if (Number(item.display_column) === 30 && code && code.head === item.head && Number.isFinite(Date.parse(code.since || ''))) sinceMs = Date.parse(code.since); // A blocked row without stage_since still shows its age, from created_at. if (!sinceMs && mods.indexOf('blocked') >= 0) sinceMs = stageTrackerOpenSince(item).ms; const stalled = mods.indexOf('stalled') >= 0; @@ -61,6 +63,7 @@ const open = Array.isArray(issue.linked_prs) ? issue.linked_prs.filter(x => x && x.number !== lp.number && stageTrackerLinkedPROpen(x, issue)) : []; const canonical = /^https?:\/\/[^/]+\/([^/]+\/[^/]+)\/pull\/\d+(?:[?#].*)?$/.exec(String(lp.url || '')); return { repo: canonical ? canonical[1] : (lp.repo || issue.repo), number: lp.number, kind: 'pr', title: lp.title || '', url: lp.url || '', author: lp.author || '', author_kind: lp.author_kind || '', + ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, state: lp.state || '', terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', stage: lp.stage || 0, stage_since: lp.stage_since || '', stage_slug: lp.stage_slug || '', modifiers: lp.modifiers || [], deferred_modifiers: lp.deferred_modifiers || [], caption: lp.caption || '', reason: lp.reason || '', preparation: lp.preparation || null, human_attention: lp.human_attention || null, human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, @@ -270,7 +273,7 @@ function stageTrackerLinkedSorted(item, stages) { const linked = Array.isArray(item.linked_prs) ? item.linked_prs.filter(lp => stageTrackerLinkedDrawnHere(lp, item) && !stageTrackerLinkedSupersededGone(lp, item)) : (item.linked_pr ? [{ number: item.linked_pr }] : []); const sinceOf = lp => Date.parse(lp.stage_since || '') || Infinity; - return linked.sort((x, y) => (stageTrackerAnchor(y.stage, stages, 'pr', y) - stageTrackerAnchor(x.stage, stages, 'pr', x)) || (stageTrackerAttentionTier(x) - stageTrackerAttentionTier(y)) || (sinceOf(x) - sinceOf(y)) || ((x.number || 0) - (y.number || 0))); + return linked.sort((x, y) => (stageTrackerAnchor(y.stage, stages, 'pr', y, false) - stageTrackerAnchor(x.stage, stages, 'pr', x, false)) || (stageTrackerAttentionTier(x) - stageTrackerAttentionTier(y)) || (sinceOf(x) - sinceOf(y)) || ((x.number || 0) - (y.number || 0))); } // Pure: a PR whose drawn_under issue is not a row of this page (filtered @@ -320,7 +323,7 @@ // far along as its furthest covering PR — then longest-waiting first. function stageTrackerSortKey(item, stages) { const l = stageTrackerLead(item, stages); - return { anchor: stageTrackerAnchor(l.stage, stages, l.kind, l.lead), since: Date.parse(l.since) || Infinity }; + return { anchor: stageTrackerAnchor(l.stage, stages, l.kind, l.lead, false), since: Date.parse(l.since) || Infinity }; } /* ---- Repo chip and group-by-repo (pure; run under node by diff --git a/src/pkg/dashboard/static-src/js/tracker-row-render.js b/src/pkg/dashboard/static-src/js/tracker-row-render.js index 8d313f34d6..5fd920f7a2 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-render.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-render.js @@ -105,6 +105,7 @@ const lineage = (lp.lineage && typeof stageTrackerLineageChipHtml === 'function' ? stageTrackerLineageChipHtml(lp, nowMs) : '') || (typeof stageTrackerAdoptedFromChipHtml === 'function' ? stageTrackerAdoptedFromChipHtml(lp, nowMs) : ''); prRefs = [STAGE_TRACKER_LINKED_GLYPH + stageTrackerPRPillsHtml(stageTrackerPRRef(lp.number, lp.url, lp.author_kind || '', lp.author, lp.title, (lp.title ? lp.title + '\n' : '') + 'Author: ' + who + ' · ' + stageTrackerLinkedTip(item, lp.number, ctx)), typeof stageTrackerLinkedChipsHtml === 'function' ? stageTrackerLinkedChipsHtml(lp, lineage) : (lineage || null), lp.base_ref)]; shown = Object.assign({}, item, { via_pr: true, stage: stageTrackerLeadStage(lp), stage_since: lp.stage_since || item.stage_since, modifiers: lp.modifiers || item.modifiers, deferred_modifiers: lp.deferred_modifiers || item.deferred_modifiers || [], caption: lp.caption || item.caption, reason: lp.reason || item.reason, preparation: lp.preparation || null, + ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null }); } else if (linked.length) { diff --git a/src/pkg/dashboard/static-src/js/tracker-row-strip.js b/src/pkg/dashboard/static-src/js/tracker-row-strip.js index b7acdb3885..b60c92bab8 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row-strip.js +++ b/src/pkg/dashboard/static-src/js/tracker-row-strip.js @@ -6,6 +6,7 @@ const byNum = {}; (stages || []).forEach(st => { byNum[st.number] = st; }); const cols = STAGE_TRACKER_PATH.map(n => { + if (n === 50) return '<li class="ham-seg ham-track-head"><span class="ham-seg-t">CI</span></li><li class="ham-seg ham-track-head"><span class="ham-seg-t">Review</span></li>'; const name = n === 0 ? 'Open' : ((byNum[n] || {}).short || (byNum[n] || {}).label || String(n)); // The Merge queue column wears the same train as the train header chip. const ico = n === 80 && typeof stageTrackerTrainIconHtml === 'function' ? stageTrackerTrainIconHtml('ham-ico ham-train-icon ham-col-ico') : ''; @@ -14,6 +15,44 @@ return `<div class="ham-cols" aria-hidden="true"><div class="ham-strip-row"><ol class="ham-strip">${cols}<li class="ham-seg cap ham-history-head" title="History — decisions and actions on this item">${stageTrackerIcon('history', 'ham-ico ham-history-ico', 'History — decisions and actions on this item')}</li></ol><span class="ham-since">since</span></div></div>`; } + // Evidence is supplied independently by the backend. A native 050 label + // cannot say who reviews, whether checks run, or whether an author codes. + function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { + if (blank) return `<li class="ham-seg blank" data-track="${kind}" data-route-state="blank" aria-hidden="true"></li>`; + const name = kind === 'ci' ? 'CI' : 'Review'; + const a = item && item[kind + '_activity']; + const matches = a && item.head && a.head === item.head; + let caption = matches ? a.caption || name + ' unknown' : name + ' unknown'; + const observed = matches && a.observed_at ? Date.parse(a.observed_at) : NaN; + const activityFreshMS = 2 * 60 * 1000; + const clock = Number(nowMs) || Date.now(); + const stale = Number.isFinite(observed) && (clock - observed > activityFreshMS || observed > clock); + const active = matches && a.active && Number.isFinite(observed) && !stale; + const state = matches ? a.state || 'unknown' : 'unknown'; + if (matches && (a.active || ['running', 'reviewing', 'adjudicating'].includes(state)) && (!Number.isFinite(observed) || stale)) caption = name + ' activity unknown · last observed ' + state; + const cls = Number.isFinite(observed) && !stale && (state === 'passing' || state === 'approved') ? 'done' : active ? 'active' : 'todo'; + const source = matches ? a.source || 'unavailable' : 'unavailable'; + const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale · ' : 'observed · ') + new Date(observed).toISOString(); + const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' · since ' + new Date(a.since).toISOString() : ''; + const blocker = matches && a.blocker ? ' · ' + a.blocker : ''; + let tip = caption + blocker + ' · head ' + (item.head || 'unknown') + ' · ' + source + ' · ' + freshness + since; + const ownsPR = item.kind === 'pr' || item.via_pr; + const code = item.code_activity; + const codeNote = code && code.head === item.head && Number(item.display_column) === 50 && + ((kind === 'review' && code.state === 'waiting_fixer') || (kind === 'ci' && code.state === 'waiting_ci')) ? code.caption : ''; + if (codeNote) tip += ' · code source ' + (code.source || 'unavailable') + ' · observed ' + (code.observed_at || 'unknown') + ' · since ' + (code.since || 'unknown') + (code.blocker ? ' · ' + code.blocker : ''); + const contextWord = kind === 'review' && sg.state === 'active' && !codeNote && sg.detour ? sg.detour.text : ''; + let decided = kind === 'review' && sg.state === 'active' && item.decided && typeof stageTrackerMergeGateWordHtml === 'function' ? stageTrackerMergeGateWordHtml(item, nowMs) : ''; + const codeObserved = Date.parse(code && code.observed_at || ''); + const codeFresh = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; + if (!codeFresh) decided = decided.replace(/>Fixing(?=\s|<)/g, '>Fix requested'); + const word = esc(caption.replace(new RegExp('^' + name + ' ?'), '') || state); + const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; + const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${word}</a>` : word; + const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); + return `<li class="ham-seg ham-activity-track ${cls}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}"${sg.state === 'active' ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(tip + (codeNote ? ' · ' + codeNote : ''))}"` : ''} aria-label="${esc(name + ': ' + tip + (codeNote ? ' · ' + codeNote : ''))}"><span class="ham-track-name">${name}</span><span class="ham-track-state">${evidenceLink}</span>${codeNote || contextWord ? `<span class="ham-track-code-note">${esc(codeNote || contextWord)}</span>` : ''}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}${stale || !Number.isFinite(observed) ? '<span class="ham-track-freshness">?</span>' : ''}</li>`; + } + // Chevrons for one item. range bounds the columns the item owns (an // issue row stops at PR in progress, a nested PR row starts there); // columns outside it are invisible spacers that keep the grid aligned. @@ -51,10 +90,18 @@ // tracker-cues helpers are optional here so a lifted copy of this // function (tests, previews) renders without them. const worker = typeof stageTrackerWorkingOn === 'function' ? stageTrackerWorkingOn(item, ctx && ctx.workers) : null; + const code = item.code_activity; + const codeObserved = code && code.observed_at ? Date.parse(code.observed_at) : NaN; + const codeFreshMS = 2 * 60 * 1000; + const clock = Number(nowMs) || Date.now(); + const codeWorking = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= codeFreshMS; let motion = stageTrackerMotion(item); + if (code && !codeWorking && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_STATIC; if (motion === STAGE_TRACKER_MOTION_ACTIVE && !worker) motion = STAGE_TRACKER_MOTION_STATIC; + if (codeWorking && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_ACTIVE; const motionAttr = motion === STAGE_TRACKER_MOTION_STATIC ? '' : ` data-motion="${motion}"`; return segs.map(sg => { + if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs)).join(''); if (sg.number < from || sg.number > to) return `<li class="ham-seg blank${sg.cap ? ' cap' : ''}" aria-hidden="true"></li>`; const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); @@ -92,6 +139,11 @@ else if (sentinelSuffix) tip = tip + ' — ' + stageTrackerSentinelTip(item); // Working or waiting leads: what happens now, or what it waits on. if (!sg.cap && typeof stageTrackerCueLead === 'function') tip = stageTrackerCueLead(item, worker, nowMs) + tip; + if (sg.number === 30 && item.code_activity && Number(item.display_column) === 30) { + tip = (codeWorking ? code.caption : sg.detour ? sg.detour.text : 'Code activity unknown') + ' · head ' + (item.head || 'unknown') + ' · ' + (code.source || 'unavailable') + ' · observed ' + (code.observed_at || 'unknown') + ' · since ' + (code.since || 'unknown'); + if (code.blocker) tip += ' · ' + code.blocker; + if (claimant) tip += ' · ' + stageTrackerClaimantLine(claimant, nowMs); + } } let inner; // A lit chevron on a row parked on a person ("Needs human decision", @@ -113,7 +165,7 @@ const gateCue = gateWord && typeof stageTrackerGateCueHtml === 'function' ? stageTrackerGateCueHtml(item, nowMs, trains) : ''; // The agent-working spinner (tracker-cues) names the agent and what // it did, so a spinning glyph is never unexplained. - const workTip = worker && typeof stageTrackerCueLead === 'function' ? stageTrackerCueLead(item, worker, nowMs).replace(/ — $/, '') : ''; + const workTip = code && Number(item.display_column) === 30 ? (codeWorking ? code.caption : '') : worker && typeof stageTrackerCueLead === 'function' ? stageTrackerCueLead(item, worker, nowMs).replace(/ — $/, '') : ''; const workIco = workTip ? `<span class="ham-active-ico-wrap" role="img" title="${esc(workTip)}" aria-label="${esc(workTip)}">${stageTrackerIcon(sg.number, 'ham-ico ham-active-ico')}</span>` : stageTrackerIcon(sg.number, 'ham-ico ham-active-ico'); // The cap chevron is the ✓ only once the PR is merged; until then // the column is the row's history and wears the history mark. @@ -132,11 +184,32 @@ && (!range || range.from == null || sg.number >= range.from) && (!range || range.to == null || sg.number <= range.to)); if (!active) return ''; - const actor = active.cap ? '' : stageTrackerActorTip(item); + const actor = active.cap || active.number === 50 ? '' : stageTrackerActorTip(item); const by = active.cap && item.terminal_merge && typeof stageTrackerMergedByText === 'function' ? stageTrackerMergedByText(item.merged_by) : ''; const regressed = stageTrackerRegressionText(item, Date.now()); - const text = active.short + (by ? ' ' + by : '') + (active.detour && active.detour.text !== active.short ? ' · ' + active.detour.text : '') + actor + (regressed ? ' · ' + regressed : ''); - return `<p class="ham-current-stage">${esc(text)}</p>`; + let text = active.short + (by ? ' ' + by : '') + (active.detour && active.detour.text !== active.short ? ' · ' + active.detour.text : '') + actor + (regressed ? ' · ' + regressed : ''); + const decidedInfo = active.number === 50 && item.decided && typeof stageTrackerMergeGateInfo === 'function' ? stageTrackerMergeGateInfo(item, nowMs) : null; + if (decidedInfo) { + const code = item.code_activity; + const observed = Date.parse(code && code.observed_at || ''); + const activityFreshMS = 2 * 60 * 1000; + const clock = Number(nowMs) || Date.now(); + const working = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(observed) && observed <= clock && clock - observed <= activityFreshMS; + const word = !working && decidedInfo.word === 'Fixing' ? 'Fix requested' : decidedInfo.word; + text = word + (decidedInfo.detail ? ' · ' + decidedInfo.detail : '') + (regressed ? ' · ' + regressed : ''); + } + const tracks = (item.kind === 'pr' || item.via_pr) && item.head ? ['ci', 'review'].map(kind => { + const a = item[kind + '_activity']; + const name = kind === 'ci' ? 'CI' : 'Review'; + if (!a || a.head !== item.head) return name + ' unknown'; + const observed = Date.parse(a.observed_at || ''); + const activityFreshMS = 2 * 60 * 1000; + const clock = Number(nowMs) || Date.now(); + const fresh = Number.isFinite(observed) && observed <= clock && clock - observed <= activityFreshMS; + if ((a.active || ['running', 'reviewing', 'adjudicating'].includes(a.state)) && !fresh) return name + ' activity unknown · last observed ' + (a.state || 'unknown'); + return (a.caption || name + ' unknown') + (!Number.isFinite(observed) ? ' · observation time unknown' : !fresh ? ' · stale observation' : ''); + }).join(' · ') : ''; + return `<p class="ham-current-stage">${esc(text + (tracks ? ' · ' + tracks : ''))}</p>`; } // "040 Covered by PR" — the stage code plus the strip word the payload @@ -225,6 +298,8 @@ : [stageTrackerHeadline(item), item.caption || item.reason || '', item.repo || '']; if (item.author || ak) lines.push('Author: ' + (item.author ? '@' + item.author : '') + (ak ? ' (' + (akPlain[ak] || ak) + akSource + ')' : '') + (item.tier ? ' · ' + item.tier : '')); if (item.origin) lines.push('Origin: origin/' + item.origin); + const claimant = typeof stageTrackerClaimant === 'function' ? stageTrackerClaimant(item) : null; + if (claimant) lines.push(stageTrackerClaimantLine(claimant, nowMs)); if (item.kind === 'issue' && Array.isArray(item.linked_prs) && item.linked_prs.length) lines.push('Covering PR: ' + item.linked_prs.map(lp => Number(lp.number) || 0).sort((x, y) => x - y).map(n => '#' + n).join(', ')); else if (item.kind === 'issue' && item.linked_pr) lines.push('Covering PR: #' + item.linked_pr + (typeof stageTrackerLineageClause === 'function' ? stageTrackerLineageClause(item) : '')); let actorLine = stageTrackerActorTip(item).replace(/^ · /, ''); diff --git a/src/pkg/dashboard/static-src/js/tracker-row.js b/src/pkg/dashboard/static-src/js/tracker-row.js index 6a97c24937..741ecf3c14 100644 --- a/src/pkg/dashboard/static-src/js/tracker-row.js +++ b/src/pkg/dashboard/static-src/js/tracker-row.js @@ -23,6 +23,20 @@ detour.text = stageTrackerReturnedWord(item, detour.text); detour.sentinelSuffix = stageTrackerSentinelAsSuffix(item); } + const code = item.code_activity; + const codeMatches = code && String(code.head || '') === String(item.head || ''); + const codeObserved = codeMatches && code.observed_at ? Date.parse(code.observed_at) : NaN; + const activityFreshMS = 2 * 60 * 1000; + const clock = Number(nowMs) || Date.now(); + const codeWorking = codeMatches && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; + const codeCaption = codeMatches ? (!codeWorking && code.state === 'fixing' ? 'Fix task assigned · activity unknown' : code.caption) : 'Code activity unknown'; + if (detour && !code && cur === 70 && !detour.sentinel) detour.text = 'Waiting for fixer · activity unknown'; + if (detour && code && [70, 71, 72].includes(cur)) detour.text = codeCaption || detour.text; + if (detour && code && cur === 74 && codeWorking) detour.text += ' · ' + codeCaption; + if (detour && code && cur === 74 && !codeWorking) { + if (detour.text === 'Adopting · fixer resolving conflicts') detour.text = 'Adopted repair' + (Number(item.adopted_by) ? ' → #' + Number(item.adopted_by) : ''); + detour.text += ' · activity unknown'; + } const segs = STAGE_TRACKER_PATH.map(n => { const st = n === 0 ? { label: 'Open', short: 'Open', description: 'Open, not yet in a stage' } : (byNum[n] || {}); let state = 'todo'; @@ -35,12 +49,15 @@ // read as 080 with "Next move: human"). const tipStage = (state === 'active' && curStage.label) ? curStage : st; let word = state === 'active' && STAGE_TRACKER_ACTIVE_WORD[cur] ? STAGE_TRACKER_ACTIVE_WORD[cur] : (st.short || st.label || String(n)); + if (state === 'active' && n === 50) word = 'CI + Review'; + if (state === 'active' && n === 30 && cur === 70 && !codeWorking) word = 'PR in progress'; // A merge-train member's word is its place in the train (#15117). if (state === 'active' && !detour && n > 0 && typeof stageTrackerTrainWord === 'function') { const tw = stageTrackerTrainWord(item, trains); if (tw) word = tw; } // A PR the hive is rebasing (the train's or the fixer's episode) // reads "Rebasing · attempt 1/2" in the CI / Review column it sits // in (hive#15825) — its head has no CI yet, so no merge-queue word. if (state === 'active' && !detour && n > 0 && n < 80 && item.rebase && item.rebase.text && !(typeof stageTrackerTrain === 'function' && stageTrackerTrain(item))) word = String(item.rebase.text); + if (state === 'active' && n === 30 && code && code.state === 'fixing') word = codeCaption; const mods = Array.isArray(item.modifiers) ? item.modifiers : []; const openHold = n === 0 && state === 'active' && mods.indexOf('hold') >= 0; // hold is a human instruction, so it wins over blocked when both are present. diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 680c21de4d..80065e550f 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -1445,7 +1445,7 @@ minus the fixed 4em cap and the six gaps) plus the two gaps between them, so the PR cell starts at the PR in progress chevron; the PR cell takes what is left and gives way to the chip, which lives in the cap cell. */ - .ham-head-cols .ham-seg.ham-head-lead { flex: 0 0 calc((100% - 4em - 6 * var(--sp-1)) / 2 + 2 * var(--sp-1)); padding: 0 var(--sp-6) 0 0; } + .ham-head-cols .ham-seg.ham-head-lead { flex: 0 0 calc((100% - 4em - var(--ham-visible-columns) * var(--sp-1)) * 3 / var(--ham-visible-columns) + 2 * var(--sp-1)); padding: 0 var(--sp-6) 0 0; } .ham-head-cols .ham-seg.ham-head-lead.ham-head-wide { flex: 1 1 0; } /* The PR cell is one line: connector, author icon + #N + title, lineage chip and base pill sit side by side; the lineage chip gives way first @@ -1663,8 +1663,16 @@ .ham-badge-reroute { color: var(--status-warn); border-color: color-mix(in srgb, var(--status-warn) 55%, transparent); font-weight: var(--fw-medium); display: inline-flex; align-items: center; gap: var(--sp-1); } .ham-badge-reroute .ham-presence-dot { width: 0.5em; height: 0.5em; border-radius: var(--r-pill); background: var(--text-faint); flex: 0 0 auto; } .ham-badge-reroute.ham-reroute-online .ham-presence-dot { background: var(--status-ok); } - .ham-strip { list-style: none; margin: 0; padding: 0; display: flex; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; --ham-notch: 8px; } + .ham-strip { list-style: none; margin: 0; padding: 0; display: flex; gap: var(--sp-1); min-height: 18px; flex: 1 1 auto; min-width: 0; --ham-notch: 8px; --ham-visible-columns: 7; } + .ham-strip:not(.ham-head-cols) { display: grid; grid-template-columns: repeat(var(--ham-visible-columns), minmax(0, 1fr)) 4em; } .ham-seg { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: center; justify-content: center; padding: 0 var(--sp-4) 0 var(--sp-5); font-size: var(--fs-xs); font-weight: var(--fw-medium); white-space: nowrap; overflow: hidden; clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%, var(--ham-notch) 50%); } + .ham-activity-track { clip-path: none; border: var(--line-width) solid var(--line-subtle); border-radius: var(--r-sm); flex-direction: column; align-items: flex-start; padding: var(--sp-1) var(--sp-2); white-space: normal; } + .ham-track-name { font-weight: var(--fw-semibold); } + .ham-track-state { overflow-wrap: anywhere; font-size: var(--fs-xs); } + .ham-track-state a { color: inherit; } + .ham-track-code-note, .ham-track-context { overflow-wrap: anywhere; font-size: var(--fs-xs); } + .ham-track-freshness { position: absolute; right: var(--sp-1); top: 0; color: var(--amber); } + .ham-activity-track[data-activity-state="failing"], .ham-activity-track[data-activity-state="changes_requested"] { border-color: var(--amber); color: var(--amber); } .ham-seg:first-child { clip-path: polygon(0 0, calc(100% - var(--ham-notch)) 0, 100% 50%, calc(100% - var(--ham-notch)) 100%, 0 100%); } .ham-seg.cap { flex: 0 0 4em; } .ham-seg.active.merged { background: var(--green); color: var(--surface-0); animation: none; } @@ -2090,6 +2098,10 @@ /* Keep the aligned progress strip compact; put its active step in a wrapping caption instead of squeezing actionable words into a chevron. */ .ham-cols .ham-seg-t, .ham-row .ham-seg-t, .ham-row .ham-detour { display: none; } + .ham-cols .ham-track-head .ham-seg-t { display: inline; } + .ham-track-state { display: none; } + .ham-track-code-note, .ham-track-context { display: none; } + .ham-activity-track { align-items: center; } .ham-active-ico { display: block; } .ham-row .ham-actor-ico { display: none; } .ham-current-stage { display: block; } @@ -17173,9 +17185,19 @@ <h3 class="faq-group-title">Where to get help</h3> // attempt that found the conflict) or a planner-ordered merge_train // still rides on the record — hive's own #15574 read "Fixing" under // Merge queue after "fell back to Fixing — conflicting". - function stageTrackerAnchor(stage, stages, kind, item) { + function stageTrackerAnchor(stage, stages, kind, item, presentation) { const cur = Number(stage) || 0; if (cur >= STAGE_TRACKER_TERMINAL) return STAGE_TRACKER_TERMINAL; + // Backend evidence owns this presentation mapping, never a label or + // client-side interpretation of a CI failure. Native stages stay intact. + const displayHeadMatches = item && item.code_activity && String(item.code_activity.head || '') === String(item.head || ''); + if (presentation !== false && cur < 80 && displayHeadMatches && (Number(item.display_column) === 30 || Number(item.display_column) === 50)) return Number(item.display_column); + // Older payloads can identify owner waits/adoption, but cannot prove + // coding. Keep their native words; never use this fallback for counts/sort. + if (presentation !== false && item && !item.code_activity && !item.merge_gate && !item.merge_train && [71, 72, 74].includes(cur)) { + if (item.push && ['pushed', 'checking'].includes(item.push.state)) return 50; + return STAGE_TRACKER_PR_COLUMN; + } // Under repair past 030 → CI / Review, before any gate or train // promotion. The one park the predicate also names, 085 needs // decision, stays at the gate: the person decides there. @@ -17229,6 +17251,20 @@ <h3 class="faq-group-title">Where to get help</h3> detour.text = stageTrackerReturnedWord(item, detour.text); detour.sentinelSuffix = stageTrackerSentinelAsSuffix(item); } + const code = item.code_activity; + const codeMatches = code && String(code.head || '') === String(item.head || ''); + const codeObserved = codeMatches && code.observed_at ? Date.parse(code.observed_at) : NaN; + const activityFreshMS = 2 * 60 * 1000; + const clock = Number(nowMs) || Date.now(); + const codeWorking = codeMatches && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; + const codeCaption = codeMatches ? (!codeWorking && code.state === 'fixing' ? 'Fix task assigned · activity unknown' : code.caption) : 'Code activity unknown'; + if (detour && !code && cur === 70 && !detour.sentinel) detour.text = 'Waiting for fixer · activity unknown'; + if (detour && code && [70, 71, 72].includes(cur)) detour.text = codeCaption || detour.text; + if (detour && code && cur === 74 && codeWorking) detour.text += ' · ' + codeCaption; + if (detour && code && cur === 74 && !codeWorking) { + if (detour.text === 'Adopting · fixer resolving conflicts') detour.text = 'Adopted repair' + (Number(item.adopted_by) ? ' → #' + Number(item.adopted_by) : ''); + detour.text += ' · activity unknown'; + } const segs = STAGE_TRACKER_PATH.map(n => { const st = n === 0 ? { label: 'Open', short: 'Open', description: 'Open, not yet in a stage' } : (byNum[n] || {}); let state = 'todo'; @@ -17241,12 +17277,15 @@ <h3 class="faq-group-title">Where to get help</h3> // read as 080 with "Next move: human"). const tipStage = (state === 'active' && curStage.label) ? curStage : st; let word = state === 'active' && STAGE_TRACKER_ACTIVE_WORD[cur] ? STAGE_TRACKER_ACTIVE_WORD[cur] : (st.short || st.label || String(n)); + if (state === 'active' && n === 50) word = 'CI + Review'; + if (state === 'active' && n === 30 && cur === 70 && !codeWorking) word = 'PR in progress'; // A merge-train member's word is its place in the train (#15117). if (state === 'active' && !detour && n > 0 && typeof stageTrackerTrainWord === 'function') { const tw = stageTrackerTrainWord(item, trains); if (tw) word = tw; } // A PR the hive is rebasing (the train's or the fixer's episode) // reads "Rebasing · attempt 1/2" in the CI / Review column it sits // in (hive#15825) — its head has no CI yet, so no merge-queue word. if (state === 'active' && !detour && n > 0 && n < 80 && item.rebase && item.rebase.text && !(typeof stageTrackerTrain === 'function' && stageTrackerTrain(item))) word = String(item.rebase.text); + if (state === 'active' && n === 30 && code && code.state === 'fixing') word = codeCaption; const mods = Array.isArray(item.modifiers) ? item.modifiers : []; const openHold = n === 0 && state === 'active' && mods.indexOf('hold') >= 0; // hold is a human instruction, so it wins over blocked when both are present. @@ -17539,6 +17578,7 @@ <h3 class="faq-group-title">Where to get help</h3> const byNum = {}; (stages || []).forEach(st => { byNum[st.number] = st; }); const cols = STAGE_TRACKER_PATH.map(n => { + if (n === 50) return '<li class="ham-seg ham-track-head"><span class="ham-seg-t">CI</span></li><li class="ham-seg ham-track-head"><span class="ham-seg-t">Review</span></li>'; const name = n === 0 ? 'Open' : ((byNum[n] || {}).short || (byNum[n] || {}).label || String(n)); // The Merge queue column wears the same train as the train header chip. const ico = n === 80 && typeof stageTrackerTrainIconHtml === 'function' ? stageTrackerTrainIconHtml('ham-ico ham-train-icon ham-col-ico') : ''; @@ -17547,6 +17587,44 @@ <h3 class="faq-group-title">Where to get help</h3> return `<div class="ham-cols" aria-hidden="true"><div class="ham-strip-row"><ol class="ham-strip">${cols}<li class="ham-seg cap ham-history-head" title="History — decisions and actions on this item">${stageTrackerIcon('history', 'ham-ico ham-history-ico', 'History — decisions and actions on this item')}</li></ol><span class="ham-since">since</span></div></div>`; } + // Evidence is supplied independently by the backend. A native 050 label + // cannot say who reviews, whether checks run, or whether an author codes. + function stageTrackerActivityTrackHtml(item, kind, sg, blank, nowMs) { + if (blank) return `<li class="ham-seg blank" data-track="${kind}" data-route-state="blank" aria-hidden="true"></li>`; + const name = kind === 'ci' ? 'CI' : 'Review'; + const a = item && item[kind + '_activity']; + const matches = a && item.head && a.head === item.head; + let caption = matches ? a.caption || name + ' unknown' : name + ' unknown'; + const observed = matches && a.observed_at ? Date.parse(a.observed_at) : NaN; + const activityFreshMS = 2 * 60 * 1000; + const clock = Number(nowMs) || Date.now(); + const stale = Number.isFinite(observed) && (clock - observed > activityFreshMS || observed > clock); + const active = matches && a.active && Number.isFinite(observed) && !stale; + const state = matches ? a.state || 'unknown' : 'unknown'; + if (matches && (a.active || ['running', 'reviewing', 'adjudicating'].includes(state)) && (!Number.isFinite(observed) || stale)) caption = name + ' activity unknown · last observed ' + state; + const cls = Number.isFinite(observed) && !stale && (state === 'passing' || state === 'approved') ? 'done' : active ? 'active' : 'todo'; + const source = matches ? a.source || 'unavailable' : 'unavailable'; + const freshness = !Number.isFinite(observed) ? 'observation time unknown' : (stale ? 'stale · ' : 'observed · ') + new Date(observed).toISOString(); + const since = matches && a.since && Number.isFinite(Date.parse(a.since)) ? ' · since ' + new Date(a.since).toISOString() : ''; + const blocker = matches && a.blocker ? ' · ' + a.blocker : ''; + let tip = caption + blocker + ' · head ' + (item.head || 'unknown') + ' · ' + source + ' · ' + freshness + since; + const ownsPR = item.kind === 'pr' || item.via_pr; + const code = item.code_activity; + const codeNote = code && code.head === item.head && Number(item.display_column) === 50 && + ((kind === 'review' && code.state === 'waiting_fixer') || (kind === 'ci' && code.state === 'waiting_ci')) ? code.caption : ''; + if (codeNote) tip += ' · code source ' + (code.source || 'unavailable') + ' · observed ' + (code.observed_at || 'unknown') + ' · since ' + (code.since || 'unknown') + (code.blocker ? ' · ' + code.blocker : ''); + const contextWord = kind === 'review' && sg.state === 'active' && !codeNote && sg.detour ? sg.detour.text : ''; + let decided = kind === 'review' && sg.state === 'active' && item.decided && typeof stageTrackerMergeGateWordHtml === 'function' ? stageTrackerMergeGateWordHtml(item, nowMs) : ''; + const codeObserved = Date.parse(code && code.observed_at || ''); + const codeFresh = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= activityFreshMS; + if (!codeFresh) decided = decided.replace(/>Fixing(?=\s|<)/g, '>Fix requested'); + const word = esc(caption.replace(new RegExp('^' + name + ' ?'), '') || state); + const evidenceURL = matches && /^https?:\/\//i.test(String(a.url || '')) ? a.url : ''; + const evidenceLink = ownsPR && evidenceURL ? `<a href="${esc(evidenceURL)}" target="_blank" rel="noopener noreferrer" aria-label="${esc('Open current-head ' + name + ' evidence')}">${word}</a>` : word; + const routeState = (sg.state || 'todo') + (sg.detour ? ' detoured' : ''); + return `<li class="ham-seg ham-activity-track ${cls}" data-track="${kind}" data-route-state="${esc(routeState)}" data-activity-state="${esc(state)}"${sg.state === 'active' ? ' aria-current="step"' : ''}${active ? ' data-motion="active"' : ''}${ownsPR ? ` title="${esc(tip + (codeNote ? ' · ' + codeNote : ''))}"` : ''} aria-label="${esc(name + ': ' + tip + (codeNote ? ' · ' + codeNote : ''))}"><span class="ham-track-name">${name}</span><span class="ham-track-state">${evidenceLink}</span>${codeNote || contextWord ? `<span class="ham-track-code-note">${esc(codeNote || contextWord)}</span>` : ''}${decided ? `<span class="ham-track-context">${decided}</span>` : ''}${stale || !Number.isFinite(observed) ? '<span class="ham-track-freshness">?</span>' : ''}</li>`; + } + // Chevrons for one item. range bounds the columns the item owns (an // issue row stops at PR in progress, a nested PR row starts there); // columns outside it are invisible spacers that keep the grid aligned. @@ -17584,10 +17662,18 @@ <h3 class="faq-group-title">Where to get help</h3> // tracker-cues helpers are optional here so a lifted copy of this // function (tests, previews) renders without them. const worker = typeof stageTrackerWorkingOn === 'function' ? stageTrackerWorkingOn(item, ctx && ctx.workers) : null; + const code = item.code_activity; + const codeObserved = code && code.observed_at ? Date.parse(code.observed_at) : NaN; + const codeFreshMS = 2 * 60 * 1000; + const clock = Number(nowMs) || Date.now(); + const codeWorking = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && Number.isFinite(codeObserved) && codeObserved <= clock && clock - codeObserved <= codeFreshMS; let motion = stageTrackerMotion(item); + if (code && !codeWorking && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_STATIC; if (motion === STAGE_TRACKER_MOTION_ACTIVE && !worker) motion = STAGE_TRACKER_MOTION_STATIC; + if (codeWorking && Number(item.display_column) === 30) motion = STAGE_TRACKER_MOTION_ACTIVE; const motionAttr = motion === STAGE_TRACKER_MOTION_STATIC ? '' : ` data-motion="${motion}"`; return segs.map(sg => { + if (sg.number === 50) return ['ci', 'review'].map(kind => stageTrackerActivityTrackHtml(item, kind, sg, sg.number < from || sg.number > to, nowMs)).join(''); if (sg.number < from || sg.number > to) return `<li class="ham-seg blank${sg.cap ? ' cap' : ''}" aria-hidden="true"></li>`; const sentinel = !!(sg.detour && sg.detour.sentinel); const sentinelSuffix = !!(sg.detour && sg.detour.sentinelSuffix); @@ -17625,6 +17711,11 @@ <h3 class="faq-group-title">Where to get help</h3> else if (sentinelSuffix) tip = tip + ' — ' + stageTrackerSentinelTip(item); // Working or waiting leads: what happens now, or what it waits on. if (!sg.cap && typeof stageTrackerCueLead === 'function') tip = stageTrackerCueLead(item, worker, nowMs) + tip; + if (sg.number === 30 && item.code_activity && Number(item.display_column) === 30) { + tip = (codeWorking ? code.caption : sg.detour ? sg.detour.text : 'Code activity unknown') + ' · head ' + (item.head || 'unknown') + ' · ' + (code.source || 'unavailable') + ' · observed ' + (code.observed_at || 'unknown') + ' · since ' + (code.since || 'unknown'); + if (code.blocker) tip += ' · ' + code.blocker; + if (claimant) tip += ' · ' + stageTrackerClaimantLine(claimant, nowMs); + } } let inner; // A lit chevron on a row parked on a person ("Needs human decision", @@ -17646,7 +17737,7 @@ <h3 class="faq-group-title">Where to get help</h3> const gateCue = gateWord && typeof stageTrackerGateCueHtml === 'function' ? stageTrackerGateCueHtml(item, nowMs, trains) : ''; // The agent-working spinner (tracker-cues) names the agent and what // it did, so a spinning glyph is never unexplained. - const workTip = worker && typeof stageTrackerCueLead === 'function' ? stageTrackerCueLead(item, worker, nowMs).replace(/ — $/, '') : ''; + const workTip = code && Number(item.display_column) === 30 ? (codeWorking ? code.caption : '') : worker && typeof stageTrackerCueLead === 'function' ? stageTrackerCueLead(item, worker, nowMs).replace(/ — $/, '') : ''; const workIco = workTip ? `<span class="ham-active-ico-wrap" role="img" title="${esc(workTip)}" aria-label="${esc(workTip)}">${stageTrackerIcon(sg.number, 'ham-ico ham-active-ico')}</span>` : stageTrackerIcon(sg.number, 'ham-ico ham-active-ico'); // The cap chevron is the ✓ only once the PR is merged; until then // the column is the row's history and wears the history mark. @@ -17665,11 +17756,32 @@ <h3 class="faq-group-title">Where to get help</h3> && (!range || range.from == null || sg.number >= range.from) && (!range || range.to == null || sg.number <= range.to)); if (!active) return ''; - const actor = active.cap ? '' : stageTrackerActorTip(item); + const actor = active.cap || active.number === 50 ? '' : stageTrackerActorTip(item); const by = active.cap && item.terminal_merge && typeof stageTrackerMergedByText === 'function' ? stageTrackerMergedByText(item.merged_by) : ''; const regressed = stageTrackerRegressionText(item, Date.now()); - const text = active.short + (by ? ' ' + by : '') + (active.detour && active.detour.text !== active.short ? ' · ' + active.detour.text : '') + actor + (regressed ? ' · ' + regressed : ''); - return `<p class="ham-current-stage">${esc(text)}</p>`; + let text = active.short + (by ? ' ' + by : '') + (active.detour && active.detour.text !== active.short ? ' · ' + active.detour.text : '') + actor + (regressed ? ' · ' + regressed : ''); + const decidedInfo = active.number === 50 && item.decided && typeof stageTrackerMergeGateInfo === 'function' ? stageTrackerMergeGateInfo(item, nowMs) : null; + if (decidedInfo) { + const code = item.code_activity; + const observed = Date.parse(code && code.observed_at || ''); + const activityFreshMS = 2 * 60 * 1000; + const clock = Number(nowMs) || Date.now(); + const working = code && code.head === item.head && code.source === 'fix-dispatch+successful-edit+verified-git-worktree' && code.active && code.state === 'fixing' && Number.isFinite(observed) && observed <= clock && clock - observed <= activityFreshMS; + const word = !working && decidedInfo.word === 'Fixing' ? 'Fix requested' : decidedInfo.word; + text = word + (decidedInfo.detail ? ' · ' + decidedInfo.detail : '') + (regressed ? ' · ' + regressed : ''); + } + const tracks = (item.kind === 'pr' || item.via_pr) && item.head ? ['ci', 'review'].map(kind => { + const a = item[kind + '_activity']; + const name = kind === 'ci' ? 'CI' : 'Review'; + if (!a || a.head !== item.head) return name + ' unknown'; + const observed = Date.parse(a.observed_at || ''); + const activityFreshMS = 2 * 60 * 1000; + const clock = Number(nowMs) || Date.now(); + const fresh = Number.isFinite(observed) && observed <= clock && clock - observed <= activityFreshMS; + if ((a.active || ['running', 'reviewing', 'adjudicating'].includes(a.state)) && !fresh) return name + ' activity unknown · last observed ' + (a.state || 'unknown'); + return (a.caption || name + ' unknown') + (!Number.isFinite(observed) ? ' · observation time unknown' : !fresh ? ' · stale observation' : ''); + }).join(' · ') : ''; + return `<p class="ham-current-stage">${esc(text + (tracks ? ' · ' + tracks : ''))}</p>`; } // "040 Covered by PR" — the stage code plus the strip word the payload @@ -17758,6 +17870,8 @@ <h3 class="faq-group-title">Where to get help</h3> : [stageTrackerHeadline(item), item.caption || item.reason || '', item.repo || '']; if (item.author || ak) lines.push('Author: ' + (item.author ? '@' + item.author : '') + (ak ? ' (' + (akPlain[ak] || ak) + akSource + ')' : '') + (item.tier ? ' · ' + item.tier : '')); if (item.origin) lines.push('Origin: origin/' + item.origin); + const claimant = typeof stageTrackerClaimant === 'function' ? stageTrackerClaimant(item) : null; + if (claimant) lines.push(stageTrackerClaimantLine(claimant, nowMs)); if (item.kind === 'issue' && Array.isArray(item.linked_prs) && item.linked_prs.length) lines.push('Covering PR: ' + item.linked_prs.map(lp => Number(lp.number) || 0).sort((x, y) => x - y).map(n => '#' + n).join(', ')); else if (item.kind === 'issue' && item.linked_pr) lines.push('Covering PR: #' + item.linked_pr + (typeof stageTrackerLineageClause === 'function' ? stageTrackerLineageClause(item) : '')); let actorLine = stageTrackerActorTip(item).replace(/^ · /, ''); @@ -18230,6 +18344,8 @@ <h3 class="faq-group-title">Where to get help</h3> function stageTrackerSinceHtml(item, nowMs) { const mods = Array.isArray(item.modifiers) ? item.modifiers : []; let sinceMs = Date.parse(item.stage_since || ''); + const code = item.code_activity; + if (Number(item.display_column) === 30 && code && code.head === item.head && Number.isFinite(Date.parse(code.since || ''))) sinceMs = Date.parse(code.since); // A blocked row without stage_since still shows its age, from created_at. if (!sinceMs && mods.indexOf('blocked') >= 0) sinceMs = stageTrackerOpenSince(item).ms; const stalled = mods.indexOf('stalled') >= 0; @@ -18277,6 +18393,7 @@ <h3 class="faq-group-title">Where to get help</h3> const open = Array.isArray(issue.linked_prs) ? issue.linked_prs.filter(x => x && x.number !== lp.number && stageTrackerLinkedPROpen(x, issue)) : []; const canonical = /^https?:\/\/[^/]+\/([^/]+\/[^/]+)\/pull\/\d+(?:[?#].*)?$/.exec(String(lp.url || '')); return { repo: canonical ? canonical[1] : (lp.repo || issue.repo), number: lp.number, kind: 'pr', title: lp.title || '', url: lp.url || '', author: lp.author || '', author_kind: lp.author_kind || '', + ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, state: lp.state || '', terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', stage: lp.stage || 0, stage_since: lp.stage_since || '', stage_slug: lp.stage_slug || '', modifiers: lp.modifiers || [], deferred_modifiers: lp.deferred_modifiers || [], caption: lp.caption || '', reason: lp.reason || '', preparation: lp.preparation || null, human_attention: lp.human_attention || null, human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', base_ref: lp.base_ref || '', decision_needed: lp.decision_needed || null, @@ -18486,7 +18603,7 @@ <h3 class="faq-group-title">Where to get help</h3> function stageTrackerLinkedSorted(item, stages) { const linked = Array.isArray(item.linked_prs) ? item.linked_prs.filter(lp => stageTrackerLinkedDrawnHere(lp, item) && !stageTrackerLinkedSupersededGone(lp, item)) : (item.linked_pr ? [{ number: item.linked_pr }] : []); const sinceOf = lp => Date.parse(lp.stage_since || '') || Infinity; - return linked.sort((x, y) => (stageTrackerAnchor(y.stage, stages, 'pr', y) - stageTrackerAnchor(x.stage, stages, 'pr', x)) || (stageTrackerAttentionTier(x) - stageTrackerAttentionTier(y)) || (sinceOf(x) - sinceOf(y)) || ((x.number || 0) - (y.number || 0))); + return linked.sort((x, y) => (stageTrackerAnchor(y.stage, stages, 'pr', y, false) - stageTrackerAnchor(x.stage, stages, 'pr', x, false)) || (stageTrackerAttentionTier(x) - stageTrackerAttentionTier(y)) || (sinceOf(x) - sinceOf(y)) || ((x.number || 0) - (y.number || 0))); } // Pure: a PR whose drawn_under issue is not a row of this page (filtered @@ -18536,7 +18653,7 @@ <h3 class="faq-group-title">Where to get help</h3> // far along as its furthest covering PR — then longest-waiting first. function stageTrackerSortKey(item, stages) { const l = stageTrackerLead(item, stages); - return { anchor: stageTrackerAnchor(l.stage, stages, l.kind, l.lead), since: Date.parse(l.since) || Infinity }; + return { anchor: stageTrackerAnchor(l.stage, stages, l.kind, l.lead, false), since: Date.parse(l.since) || Infinity }; } /* ---- Repo chip and group-by-repo (pure; run under node by @@ -18705,6 +18822,7 @@ <h3 class="faq-group-title">Where to get help</h3> const lineage = (lp.lineage && typeof stageTrackerLineageChipHtml === 'function' ? stageTrackerLineageChipHtml(lp, nowMs) : '') || (typeof stageTrackerAdoptedFromChipHtml === 'function' ? stageTrackerAdoptedFromChipHtml(lp, nowMs) : ''); prRefs = [STAGE_TRACKER_LINKED_GLYPH + stageTrackerPRPillsHtml(stageTrackerPRRef(lp.number, lp.url, lp.author_kind || '', lp.author, lp.title, (lp.title ? lp.title + '\n' : '') + 'Author: ' + who + ' · ' + stageTrackerLinkedTip(item, lp.number, ctx)), typeof stageTrackerLinkedChipsHtml === 'function' ? stageTrackerLinkedChipsHtml(lp, lineage) : (lineage || null), lp.base_ref)]; shown = Object.assign({}, item, { via_pr: true, stage: stageTrackerLeadStage(lp), stage_since: lp.stage_since || item.stage_since, modifiers: lp.modifiers || item.modifiers, deferred_modifiers: lp.deferred_modifiers || item.deferred_modifiers || [], caption: lp.caption || item.caption, reason: lp.reason || item.reason, preparation: lp.preparation || null, + ci_activity: lp.ci_activity || null, review_activity: lp.review_activity || null, code_activity: lp.code_activity || null, display_column: lp.display_column || 0, terminal_merge: !!lp.terminal_merge, merged_by: lp.merged_by || '', human_approver: lp.human_approver || '', manual_merge: !!lp.manual_merge, human_merge_reason: lp.human_merge_reason || '', human_merge_reason_text: lp.human_merge_reason_text || '', sentinel_alert: !!lp.sentinel_alert, sentinel_reason: lp.sentinel_reason || '', sentinel_details: lp.sentinel_details || [], sentinel_notice: !!lp.sentinel_notice, head: lp.head || '', decision_needed: lp.decision_needed || null, hold: lp.hold || null, adoption: lp.adoption || null, stage_actor: lp.stage_actor || item.stage_actor || null, claimant: lp.claimant || null, presence: lp.presence || null, rework: lp.rework || null, push: lp.push || null, merge_gate: lp.merge_gate || null, merge_train: lp.merge_train || null, left_train: lp.left_train || null, overlap: lp.overlap || null, decided: lp.decided || item.decided || null }); } else if (linked.length) { @@ -19171,7 +19289,7 @@ <h3 class="faq-group-title">Where to get help</h3> // refresh runs then. const STAGE_TRACKER_SETTLE_MS = 1200; const STAGE_TRACKER_HEADER_KEY = '__cols'; - const STAGE_TRACKER_CAP_COLUMN = STAGE_TRACKER_PATH.length; + const STAGE_TRACKER_CAP_COLUMN = STAGE_TRACKER_PATH.length + 1; var _stageTrackerCols = null; var _stageTrackerMoves = {}; var _stageTrackerRowSrc = typeof WeakMap === 'function' ? new WeakMap() : null; @@ -19182,7 +19300,8 @@ <h3 class="faq-group-title">Where to get help</h3> function stageTrackerColIndex(item, stages) { const anchor = stageTrackerAnchor(item.stage, stages, item.via_pr ? 'pr' : item.kind, item); if (anchor >= STAGE_TRACKER_TERMINAL) return STAGE_TRACKER_CAP_COLUMN; - return STAGE_TRACKER_PATH.indexOf(anchor); + const idx = STAGE_TRACKER_PATH.indexOf(anchor); + return idx + (anchor > 50 ? 1 : 0); } // Pure: item key → column for every row a payload draws. An issue with @@ -19194,9 +19313,9 @@ <h3 class="faq-group-title">Where to get help</h3> for (const it of items) { if (!it || !it.kind || !(Number(it.number) > 0)) continue; const linked = it.kind === 'issue' ? stageTrackerLinkedSorted(it, stages).filter(lp => lp && Number(lp.number) > 0) : []; - const shown = linked.length === 1 ? Object.assign({}, it, { via_pr: true, stage: linked[0].stage || 40 }) : it; + const shown = linked.length === 1 ? Object.assign({}, it, { via_pr: true, stage: linked[0].stage || 40, display_column: linked[0].display_column || 0, head: linked[0].head, code_activity: linked[0].code_activity }) : it; out[stageTrackerItemKey(it)] = stageTrackerColIndex(shown, stages); - for (const lp of linked) out[stageTrackerItemKey({ repo: it.repo, kind: 'pr', number: lp.number })] = stageTrackerColIndex({ kind: 'pr', stage: lp.stage || 0 }, stages); + for (const lp of linked) out[stageTrackerItemKey({ repo: it.repo, kind: 'pr', number: lp.number })] = stageTrackerColIndex({ kind: 'pr', stage: lp.stage || 0, display_column: lp.display_column || 0, head: lp.head, code_activity: lp.code_activity }, stages); } return out; } diff --git a/src/pkg/dashboard/status_builder.go b/src/pkg/dashboard/status_builder.go index be43d6132f..5b492f0227 100644 --- a/src/pkg/dashboard/status_builder.go +++ b/src/pkg/dashboard/status_builder.go @@ -1161,6 +1161,7 @@ func buildAgentsWithHidden(statuses map[string]*crux.Process, cfg *config.Config Starting: proc.Starting && proc.State != crux.StateRunning, Busy: busy, AwaitingCI: awaitingCI, + CodeWork: proc.CodeWork, Paused: proc.Paused, PausedAt: formatOptionalTime(proc.PausedAt), PausedReason: redactTokens(proc.PausedReason), @@ -1228,6 +1229,14 @@ func buildAgentsWithHidden(statuses map[string]*crux.Process, cfg *config.Config CadenceModes: cadenceModes, } applyAgentLastAction(&a, proc, busy) + if a.CodeWork != nil { + if proc.LastKick == nil || !proc.LastKick.Equal(a.CodeWork.KickAt) { + a.CodeWork = nil + } else { + observation := *a.CodeWork + a.CodeWork = &observation + } + } // #7421: how the last kicked turn ended, so the card can say "asked // the operator what to do" or "stood down" instead of implying work. if proc.KickOutcome.Settled(proc.LastKick) { diff --git a/src/pkg/github/automerge_sweep.go b/src/pkg/github/automerge_sweep.go index 131df14adf..7cb045aed3 100644 --- a/src/pkg/github/automerge_sweep.go +++ b/src/pkg/github/automerge_sweep.go @@ -140,13 +140,3 @@ func (c *Client) info(msg string, args ...any) { c.logger.Info(msg, args...) } } - -// requiredStatusCheckContexts returns the set of status-check contexts / -// check-run names the base branch requires, and whether that set is known. -// See RequiredStatusCheckContexts for the resolution order; on v5 the merge -// sweep itself lives in pkg/github/automerge, so this Client-level shim is -// used only by the protection-facts collector (#7515). -func (c *Client) requiredStatusCheckContexts(ctx context.Context, owner, repo, branch string) (map[string]bool, bool) { - set, ok := c.configRequiredChecksForRepo(owner + "/" + repo) - return RequiredStatusCheckContexts(ctx, c.client, owner, repo, branch, set, ok) -} diff --git a/src/pkg/github/client.go b/src/pkg/github/client.go index 7cf1957651..bc9dd017e7 100644 --- a/src/pkg/github/client.go +++ b/src/pkg/github/client.go @@ -65,6 +65,7 @@ type Client struct { graphQLPRBatchPageSize func() int prBatchMu sync.Mutex prBatchCheckRuns map[prBatchCheckRunKey][]*gh.CheckRun + prBatchCheckObservedAt map[prBatchCheckRunKey]time.Time prBatchReviews map[string]map[int]prReviewState prBatchStats GraphQLPRBatchStats prBatchGraphQLRate RateLimitEntry @@ -995,8 +996,9 @@ type PullRequest struct { // carries nothing the base does not already have (an adoption whose // original landed another way, hivecommons/hive#15499). Only the // single-PR GET carries these counts; false until EnrichCIStatus ran. - BaseDiffEmpty bool `json:"base_diff_empty,omitempty"` - CIStatus string `json:"ci_status"` + BaseDiffEmpty bool `json:"base_diff_empty,omitempty"` + CIStatus string `json:"ci_status"` + CIActivity *PRCIActivity `json:"ci_activity,omitempty"` // CIRealCheckRuns is the count of non-meta check runs observed on the head. // CIRealCheckRunsKnown distinguishes an observed metadata-only head from // older/test payloads that did not collect this evidence. @@ -2588,6 +2590,7 @@ func (c *Client) enrichPRCI(ctx context.Context, pr *PullRequest) map[string]boo const ciStatusSuccess = "success" const ciStatusFailure = "failure" const ciStatusPending = "pending" + pr.CIActivity = nil if pr.HeadSHA == "" { pr.CIStatus = ciStatusPending @@ -2622,20 +2625,35 @@ func (c *Client) enrichPRCI(ctx context.Context, pr *PullRequest) map[string]boo } var allCheckRuns []*gh.CheckRun - if cached, ok := c.graphQLBatchCheckRuns(pr.Repo, pr.Number, pr.HeadSHA); ok { + checkSource := "github-check-runs" + var checkObservedAt *time.Time + if cached, observedAt, ok := c.graphQLBatchCheckRunsObservation(pr.Repo, pr.Number, pr.HeadSHA); ok { allCheckRuns = cached + checkSource = "github-graphql-cache" + checkObservedAt = observedAt } else { - checkRuns, _, err := c.client.Checks.ListCheckRunsForRef(ctx, owner, repoName, pr.HeadSHA, &gh.ListCheckRunsOptions{ + options := &gh.ListCheckRunsOptions{ ListOptions: gh.ListOptions{PerPage: 100}, - }) - if err != nil { - c.logger.Warn("failed to fetch check runs", "repo", pr.Repo, "pr", pr.Number, "error", err) - pr.CIStatus = ciStatusPending - return nil } - allCheckRuns = checkRuns.CheckRuns + for { + checkRuns, response, err := c.client.Checks.ListCheckRunsForRef(ctx, owner, repoName, pr.HeadSHA, options) + if err != nil || checkRuns == nil || checkRuns.CheckRuns == nil { + c.logger.Warn("failed to fetch check runs", "repo", pr.Repo, "pr", pr.Number, "error", err) + pr.CIStatus = ciStatusPending + return nil + } + allCheckRuns = append(allCheckRuns, checkRuns.CheckRuns...) + if response == nil || response.NextPage == 0 { + break + } + options.Page = response.NextPage + } + at := time.Now().UTC() + checkObservedAt = &at } - latestCheckRuns := latestCheckRunsByNameAndApp(allCheckRuns) + currentHeadRuns := checkRunsOnHead(allCheckRuns, pr.HeadSHA) + latestCheckRuns := latestCheckRunsByNameAndApp(currentHeadRuns) + pr.CIActivity = prCIActivity(pr.HeadSHA, checkSource, activityCheckRunsByNameAndApp(currentHeadRuns), checkObservedAt) // Snapshot the CI verdict for the evidence bundle once it is known. Never // affects the verdict or any merge decision. // Keyed by owner/name: pr.Repo may be the bare repo name, and a bundle @@ -2809,6 +2827,9 @@ func (c *Client) fetchFailureExcerpt(ctx context.Context, owner, repo string, ru seen := map[string]bool{} perRun := make([][]string, 0, len(runIDs)) for idx, id := range runIDs { + if id <= 0 { + continue + } if idx >= excerptMaxRuns { break } diff --git a/src/pkg/github/commit_ci.go b/src/pkg/github/commit_ci.go index 732aebdbd2..345c1b2022 100644 --- a/src/pkg/github/commit_ci.go +++ b/src/pkg/github/commit_ci.go @@ -194,40 +194,44 @@ func RequiredStatusCheckContextsDetailed(ctx context.Context, client *gh.Client, } func RequiredStatusCheckContextsDetailedWithSource(ctx context.Context, client *gh.Client, owner, repo, branch string, configSet map[string]bool, configKnown bool) (required map[string]bool, known bool, fromConfig bool, fallback bool, source string) { + required, known, fromConfig, fallback, source, _ = RequiredStatusCheckPolicy(ctx, client, owner, repo, branch, configSet, configKnown) + return +} + +// RequiredStatusCheckPolicy preserves producer bindings from the very same +// authoritative read as the compatibility name-set APIs. Config fallback is +// deliberately distinguished from observed forge policy. +func RequiredStatusCheckPolicy(ctx context.Context, client *gh.Client, owner, repo, branch string, configSet map[string]bool, configKnown bool) (required map[string]bool, known bool, fromConfig bool, fallback bool, source string, bindings []PRRequiredCheck) { if client == nil || strings.TrimSpace(branch) == "" { if configKnown { - return configSet, true, true, true, "config" + return configSet, true, true, true, "config", nil } - return nil, false, false, false, "none" + return nil, false, false, false, "none", nil } cacheKey := requiredChecksForbiddenCacheKey(client, owner, repo, branch) if !sharedRequiredChecksForbiddenCache.get(cacheKey) { - rsc, _, err := client.Repositories.GetRequiredStatusChecks(ctx, owner, repo, branch) + names, checks, err := requiredStatusChecksFromProtectionEndpoint(ctx, client, owner, repo, branch) if err == nil { - if rsc == nil { - return map[string]bool{}, true, false, false, "protection" - } - required = requiredContextsFromRequiredStatusChecks(rsc.Contexts, rsc.Checks) - return required, true, false, false, "protection" + return names, true, false, false, "protection", checks } if errors.Is(err, gh.ErrBranchNotProtected) { - return map[string]bool{}, true, false, false, "protection-unprotected" + return map[string]bool{}, true, false, false, "protection-unprotected", nil } if isRequiredChecksForbiddenCacheable(err) { sharedRequiredChecksForbiddenCache.put(cacheKey) } } - if branchRequired, branchKnown, err := requiredStatusChecksFromBranchEndpoint(ctx, client, owner, repo, branch); err == nil && branchKnown { - return branchRequired, true, false, false, "branch" + if branchRequired, branchKnown, err, checks := requiredStatusChecksFromBranchEndpointWithBindings(ctx, client, owner, repo, branch); err == nil && branchKnown { + return branchRequired, true, false, false, "branch", checks } - if rulesRequired, rulesKnown, err := requiredStatusChecksFromRulesEndpoint(ctx, client, owner, repo, branch); err == nil && rulesKnown { - return rulesRequired, true, false, false, "rules" + if rulesRequired, rulesKnown, err, checks := requiredStatusChecksFromRulesEndpointWithBindings(ctx, client, owner, repo, branch); err == nil && rulesKnown { + return rulesRequired, true, false, false, "rules", checks } if configKnown { - return configSet, true, true, true, "config" + return configSet, true, true, true, "config", nil } - return nil, false, false, false, "none" + return nil, false, false, false, "none", nil } func requiredContextsFromRequiredStatusChecks(contexts *[]string, checks *[]*gh.RequiredStatusCheck) map[string]bool { @@ -250,34 +254,32 @@ func requiredContextsFromRequiredStatusChecks(contexts *[]string, checks *[]*gh. return required } -func requiredStatusChecksFromBranchEndpoint(ctx context.Context, client *gh.Client, owner, repo, branch string) (map[string]bool, bool, error) { +func requiredStatusChecksFromBranchEndpointWithBindings(ctx context.Context, client *gh.Client, owner, repo, branch string) (map[string]bool, bool, error, []PRRequiredCheck) { if client == nil || strings.TrimSpace(branch) == "" { - return nil, false, nil + return nil, false, nil, nil } path := fmt.Sprintf("repos/%s/%s/branches/%s", owner, repo, url.PathEscape(branch)) req, err := client.NewRequest("GET", path, nil) if err != nil { - return nil, false, err + return nil, false, err, nil } var resp struct { Protected bool `json:"protected"` Protection *struct { RequiredStatusChecks *struct { - Contexts []string `json:"contexts"` - Checks []struct { - Context string `json:"context"` - } `json:"checks"` + Contexts []string `json:"contexts"` + Checks []requiredCheckWire `json:"checks"` } `json:"required_status_checks"` } `json:"protection"` } if _, err := client.Do(ctx, req, &resp); err != nil { - return nil, false, err + return nil, false, err, nil } if !resp.Protected { - return map[string]bool{}, true, nil + return map[string]bool{}, true, nil, nil } if resp.Protection == nil || resp.Protection.RequiredStatusChecks == nil { - return nil, false, nil + return nil, false, nil, nil } required := make(map[string]bool) for _, name := range resp.Protection.RequiredStatusChecks.Contexts { @@ -290,28 +292,29 @@ func requiredStatusChecksFromBranchEndpoint(ctx context.Context, client *gh.Clie required[check.Context] = true } } - return required, true, nil + contexts := resp.Protection.RequiredStatusChecks.Contexts + return required, true, nil, bindingsFromWire(contexts, resp.Protection.RequiredStatusChecks.Checks) } -func requiredStatusChecksFromRulesEndpoint(ctx context.Context, client *gh.Client, owner, repo, branch string) (map[string]bool, bool, error) { +func requiredStatusChecksFromRulesEndpointWithBindings(ctx context.Context, client *gh.Client, owner, repo, branch string) (map[string]bool, bool, error, []PRRequiredCheck) { if client == nil || strings.TrimSpace(branch) == "" { - return nil, false, nil + return nil, false, nil, nil } path := fmt.Sprintf("repos/%s/%s/rules/branches/%s", owner, repo, url.PathEscape(branch)) req, err := client.NewRequest("GET", path, nil) if err != nil { - return nil, false, err + return nil, false, err, nil } var payload any if _, err := client.Do(ctx, req, &payload); err != nil { - return nil, false, err + return nil, false, err, nil } required := make(map[string]bool) known := collectRequiredStatusCheckRules(payload, required) if !known { - return nil, false, nil + return nil, false, nil, nil } - return required, true, nil + return required, true, nil, requiredBindingsFromRules(payload) } func collectRequiredStatusCheckRules(v any, required map[string]bool) bool { @@ -510,6 +513,7 @@ func EvaluateCommitCI(ctx context.Context, client *gh.Client, owner, repo, sha s checkOpts.Page = resp.NextPage } + allCheckRuns = checkRunsOnHead(allCheckRuns, sha) dcoSatisfied := dcoContextSucceeded(allStatuses, allCheckRuns) noteActivity := func(at time.Time) { @@ -1033,29 +1037,83 @@ func LatestMergedPRHead(ctx context.Context, client *gh.Client, owner, repo, bas type checkRunIdentity struct { name string appID int64 + head string } func latestCheckRunsByNameAndApp(checks []*gh.CheckRun) []*gh.CheckRun { - if len(checks) == 0 { - return nil - } - latest := make(map[checkRunIdentity]*gh.CheckRun, len(checks)) - for _, cr := range checks { - if cr == nil { - continue + groups := groupedCheckRuns(checks) + var out []*gh.CheckRun + for _, group := range groups { + knownIDs := true + for _, check := range group { + knownIDs = knownIDs && check.GetID() > 0 + } + best := group[0] + for _, candidate := range group[1:] { + // Without real IDs, do not let an unordered success erase an + // observed blocker. Display ambiguity is handled separately. + if !knownIDs && checkRunBlockerRank(candidate) != checkRunBlockerRank(best) { + if checkRunBlockerRank(candidate) > checkRunBlockerRank(best) { + best = candidate + } + continue + } + if checkRunIsNewer(candidate, best) { + best = candidate + } } - key := checkRunIdentity{name: cr.GetName()} - if app := cr.GetApp(); app != nil { - key.appID = app.GetID() + out = append(out, best) + } + return sortedCheckRuns(out) +} + +func groupedCheckRuns(checks []*gh.CheckRun) map[checkRunIdentity][]*gh.CheckRun { + groups := map[checkRunIdentity][]*gh.CheckRun{} + for _, check := range checks { + if check != nil { + key := checkRunIdentity{name: check.GetName(), appID: check.GetApp().GetID(), head: check.GetHeadSHA()} + groups[key] = append(groups[key], check) } - if prev := latest[key]; prev == nil || checkRunIsNewer(cr, prev) { - latest[key] = cr + } + return groups +} + +func checkRunsOnHead(checks []*gh.CheckRun, head string) []*gh.CheckRun { + var out []*gh.CheckRun + for _, check := range checks { + if check != nil && (check.GetHeadSHA() == "" || strings.EqualFold(check.GetHeadSHA(), head)) { + out = append(out, check) } } - out := make([]*gh.CheckRun, 0, len(latest)) - for _, cr := range latest { - out = append(out, cr) + return out +} + +// Activity keeps ambiguous producer/run observations; it must not change the +// canonical merge/DCO selector's one-observation-per-identity contract. +func activityCheckRunsByNameAndApp(checks []*gh.CheckRun) []*gh.CheckRun { + var out []*gh.CheckRun + for key, group := range groupedCheckRuns(checks) { + ambiguous := key.appID == 0 + for _, check := range group { + ambiguous = ambiguous || check.GetID() <= 0 + } + if ambiguous { + out = append(out, group...) + continue + } + best := latestCheckRunsByNameAndApp(group)[0] + out = append(out, best) + for _, check := range group { + if check.GetID() == best.GetID() && check.GetStartedAt().Time.Equal(best.GetStartedAt().Time) && + (check.GetStatus() != best.GetStatus() || check.GetConclusion() != best.GetConclusion()) { + out = append(out, check) + } + } } + return sortedCheckRuns(out) +} + +func sortedCheckRuns(out []*gh.CheckRun) []*gh.CheckRun { // Map iteration order is randomized, so callers that build a failure // excerpt from the first few entries (fetchFailureExcerpt) would see a // different, arbitrary subset of failing checks on every call. Sort by @@ -1073,12 +1131,38 @@ func latestCheckRunsByNameAndApp(checks []*gh.CheckRun) []*gh.CheckRun { if app := out[j].GetApp(); app != nil { aj = app.GetID() } - return ai < aj + if ai != aj { + return ai < aj + } + if out[i].GetHeadSHA() != out[j].GetHeadSHA() { + return out[i].GetHeadSHA() < out[j].GetHeadSHA() + } + if !out[i].GetStartedAt().Time.Equal(out[j].GetStartedAt().Time) { + return out[i].GetStartedAt().Before(out[j].GetStartedAt().Time) + } + if out[i].GetID() != out[j].GetID() { + return out[i].GetID() < out[j].GetID() + } + if out[i].GetConclusion() != out[j].GetConclusion() { + return out[i].GetConclusion() < out[j].GetConclusion() + } + if out[i].GetStatus() != out[j].GetStatus() { + return out[i].GetStatus() < out[j].GetStatus() + } + if out[i].GetNodeID() != out[j].GetNodeID() { + return out[i].GetNodeID() < out[j].GetNodeID() + } + return out[i].GetDetailsURL() < out[j].GetDetailsURL() }) return out } func checkRunIsNewer(candidate, current *gh.CheckRun) bool { + // A single lexicographic ordering is essential: switching between IDs and + // start times depending on the pair makes selection nontransitive. + if candidate.GetID() != current.GetID() { + return candidate.GetID() > current.GetID() + } candidateStarted := candidate.GetStartedAt().Time currentStarted := current.GetStartedAt().Time switch { @@ -1087,6 +1171,35 @@ func checkRunIsNewer(candidate, current *gh.CheckRun) bool { case currentStarted.After(candidateStarted): return false default: - return candidate.GetID() > current.GetID() + if checkRunBlockerRank(candidate) != checkRunBlockerRank(current) { + return checkRunBlockerRank(candidate) > checkRunBlockerRank(current) + } + if candidate.GetStatus() != current.GetStatus() { + return candidate.GetStatus() > current.GetStatus() + } + if candidate.GetConclusion() != current.GetConclusion() { + return candidate.GetConclusion() > current.GetConclusion() + } + if candidate.GetNodeID() != current.GetNodeID() { + return candidate.GetNodeID() > current.GetNodeID() + } + return candidate.GetDetailsURL() > current.GetDetailsURL() + } +} + +func checkRunBlockerRank(check *gh.CheckRun) int { + const ( + success = iota + pending + failing + ) + if check.GetStatus() != "completed" { + return pending + } + switch check.GetConclusion() { + case "success", "neutral", "skipped": + return success + default: + return failing } } diff --git a/src/pkg/github/commit_ci_dco_context_test.go b/src/pkg/github/commit_ci_dco_context_test.go index d700cdfcb6..455d1cfe2d 100644 --- a/src/pkg/github/commit_ci_dco_context_test.go +++ b/src/pkg/github/commit_ci_dco_context_test.go @@ -35,7 +35,7 @@ func TestDCOContextSucceeded(t *testing.T) { return &gh.RepoStatus{Context: gh.Ptr(ctx), State: gh.Ptr(state)} } run := func(id int64, name, status, conclusion string, started time.Time) *gh.CheckRun { - cr := &gh.CheckRun{ID: gh.Ptr(id), Name: gh.Ptr(name), Status: gh.Ptr(status), StartedAt: &gh.Timestamp{Time: started}} + cr := &gh.CheckRun{ID: gh.Ptr(id), Name: gh.Ptr(name), Status: gh.Ptr(status), StartedAt: &gh.Timestamp{Time: started}, App: &gh.App{ID: gh.Ptr(int64(10))}} if conclusion != "" { cr.Conclusion = gh.Ptr(conclusion) } @@ -61,6 +61,14 @@ func TestDCOContextSucceeded(t *testing.T) { }, {name: "check-run action_required", runs: []*gh.CheckRun{run(1, "DCO", "completed", "action_required", t0)}, want: false}, {name: "check-run still running", runs: []*gh.CheckRun{run(1, "DCO", "in_progress", "", t0)}, want: false}, + { + name: "unknown producer cannot prove latest success", + runs: []*gh.CheckRun{ + {ID: gh.Ptr(int64(1)), Name: gh.Ptr("DCO"), Status: gh.Ptr("completed"), Conclusion: gh.Ptr("success")}, + {ID: gh.Ptr(int64(2)), Name: gh.Ptr("DCO"), Status: gh.Ptr("completed"), Conclusion: gh.Ptr("failure")}, + }, + want: false, + }, { name: "newer rerun failure supersedes older success", runs: []*gh.CheckRun{ diff --git a/src/pkg/github/commit_ci_order_test.go b/src/pkg/github/commit_ci_order_test.go new file mode 100644 index 0000000000..eb21e33ff7 --- /dev/null +++ b/src/pkg/github/commit_ci_order_test.go @@ -0,0 +1,134 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" +) + +func TestCommitCISelectionAllPermutations(t *testing.T) { + first := time.Date(2026, 11, 2, 12, 5, 0, 0, time.UTC) + earlier := first.Add(-time.Minute) + run := func(id int64, status, conclusion string, started *time.Time) *gh.CheckRun { + check := &gh.CheckRun{ID: gh.Ptr(id), Name: gh.Ptr("validate"), HeadSHA: gh.Ptr("head"), + App: &gh.App{ID: gh.Ptr(int64(11))}, Status: gh.Ptr(status), Conclusion: gh.Ptr(conclusion)} + if started != nil { + check.StartedAt = &gh.Timestamp{Time: *started} + } + return check + } + permutations := [][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}} + for _, mode := range []string{"mixed-starts", "missing-starts", "tied-starts", "missing-id", "missing-ids", "tied-ids", "wrong-head", "latest-success", "superseded-tie", "independent-app"} { + t.Run(mode, func(t *testing.T) { + checks := []*gh.CheckRun{ + run(101, "completed", "success", &first), + run(102, "queued", "", nil), + run(103, "completed", "failure", &earlier), + } + wantGreen, wantDCO := false, false + switch mode { + case "missing-starts": + for _, check := range checks { + check.StartedAt = nil + } + case "tied-starts", "tied-ids": + for _, check := range checks { + check.StartedAt = &gh.Timestamp{Time: first} + if mode == "tied-ids" { + check.ID = gh.Ptr(int64(101)) + } + } + case "missing-id": + checks[1].ID = nil + case "missing-ids": + for _, check := range checks { + check.ID = nil + } + case "wrong-head": + checks[0].ID, checks[0].HeadSHA = gh.Ptr(int64(999)), gh.Ptr("old-head") + case "latest-success": + checks[0].Conclusion, checks[2].Conclusion = gh.Ptr("failure"), gh.Ptr("success") + wantGreen, wantDCO = true, true + case "superseded-tie": + checks[1].ID, checks[1].StartedAt = gh.Ptr(int64(101)), &gh.Timestamp{Time: first} + checks[1].Status, checks[1].Conclusion = gh.Ptr("completed"), gh.Ptr("failure") + checks[2].Conclusion = gh.Ptr("success") + wantGreen, wantDCO = true, true + case "independent-app": + checks[1].App.ID = gh.Ptr(int64(22)) + checks[1].Status, checks[1].Conclusion = gh.Ptr("completed"), gh.Ptr("success") + // Canonical DCO accepts an independent producer's success; + // required CI still sees the required-name failure. + wantDCO = true + } + var firstSelection, firstActivity string + for i, permutation := range permutations { + t.Run(fmt.Sprint(i), func(t *testing.T) { + ordered := []*gh.CheckRun{checks[permutation[0]], checks[permutation[1]], checks[permutation[2]]} + selected := latestCheckRunsByNameAndApp(checkRunsOnHead(ordered, "head")) + serialized, err := json.Marshal(selected) + if err != nil { + t.Fatal(err) + } + if i == 0 { + firstSelection = string(serialized) + } else if string(serialized) != firstSelection { + t.Fatalf("selection changed with input order: %s vs %s", serialized, firstSelection) + } + activity, err := json.Marshal(activityCheckRunsByNameAndApp(checkRunsOnHead(ordered, "head"))) + if err != nil { + t.Fatal(err) + } + if i == 0 { + firstActivity = string(activity) + } else if string(activity) != firstActivity { + t.Fatalf("activity changed with input order: %s vs %s", activity, firstActivity) + } + var dco []*gh.CheckRun + for _, check := range ordered { + copy := *check + copy.Name = gh.Ptr("DCO") + dco = append(dco, ©) + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/check-runs") { + payload := ordered + if strings.HasPrefix(r.URL.Path, "/dco/") { + payload = dco + } + _ = json.NewEncoder(w).Encode(map[string]any{"check_runs": payload}) + } else { + fmt.Fprint(w, `{"sha":"head","statuses":[]}`) + } + })) + defer srv.Close() + client := gh.NewClient(srv.Client()) + client.BaseURL, _ = url.Parse(srv.URL + "/") + got, err := EvaluateCommitCI(context.Background(), client, "org", "repo", "head", + CommitCIOptions{Required: map[string]bool{"validate": true}, RequiredKnown: true}) + if err != nil || got.Green != wantGreen { + t.Fatalf("EvaluateCommitCI = %+v, %v; want green=%v", got, err, wantGreen) + } + if got := dcoContextSucceeded(nil, checkRunsOnHead(dco, "head")); got != wantDCO { + t.Fatalf("canonical DCO = %v, want %v", got, wantDCO) + } + dcoClient := gh.NewClient(srv.Client()) + dcoClient.BaseURL, _ = url.Parse(srv.URL + "/dco/") + dcoState, err := EvaluateCommitCI(context.Background(), dcoClient, "org", "repo", "head", + CommitCIOptions{Required: map[string]bool{"DCO": true}, RequiredKnown: true}) + if err != nil || dcoState.Green != wantGreen { + t.Fatalf("EvaluateCommitCI DCO = %+v, %v; want green=%v", dcoState, err, wantGreen) + } + }) + } + }) + } +} diff --git a/src/pkg/github/pr_batch_graphql.go b/src/pkg/github/pr_batch_graphql.go index fe6275698e..dbcc0f2139 100644 --- a/src/pkg/github/pr_batch_graphql.go +++ b/src/pkg/github/pr_batch_graphql.go @@ -31,13 +31,14 @@ query($owner: String!, $name: String!, $first: Int!, $cursor: String) { commits(last: 1) { nodes { commit { + oid statusCheckRollup { state contexts(first: 50) { nodes { __typename - ... on CheckRun { name conclusion status detailsUrl } - ... on StatusContext { context state targetUrl } + ... on CheckRun { id databaseId name conclusion status detailsUrl startedAt completedAt checkSuite { app { databaseId } commit { oid } } } + ... on StatusContext { id context state targetUrl createdAt } } } } @@ -97,6 +98,7 @@ type graphQLPRBatchNode struct { Commits struct { Nodes []struct { Commit struct { + OID string `json:"oid"` StatusCheckRollup *struct { State string `json:"state"` Contexts struct { @@ -121,14 +123,27 @@ type graphQLPRBatchNode struct { } type graphQLPRBatchContext struct { - TypeName string `json:"__typename"` - Name string `json:"name"` - Conclusion string `json:"conclusion"` - Status string `json:"status"` - DetailsURL string `json:"detailsUrl"` - Context string `json:"context"` - State string `json:"state"` - TargetURL string `json:"targetUrl"` + TypeName string `json:"__typename"` + Name string `json:"name"` + Conclusion string `json:"conclusion"` + Status string `json:"status"` + DetailsURL string `json:"detailsUrl"` + Context string `json:"context"` + State string `json:"state"` + TargetURL string `json:"targetUrl"` + ID string `json:"id"` + DatabaseID *int64 `json:"databaseId"` + StartedAt *time.Time `json:"startedAt"` + CompletedAt *time.Time `json:"completedAt"` + CreatedAt *time.Time `json:"createdAt"` + CheckSuite *struct { + App *struct { + DatabaseID *int64 `json:"databaseId"` + } `json:"app"` + Commit *struct { + OID string `json:"oid"` + } `json:"commit"` + } `json:"checkSuite"` } func (c *Client) graphQLPRBatchEnabledEffective() bool { @@ -216,6 +231,7 @@ func (c *Client) invalidateGraphQLPRBatchPR(repo string, number int) { for k := range c.prBatchCheckRuns { if k.repo == key && k.number == number { delete(c.prBatchCheckRuns, k) + delete(c.prBatchCheckObservedAt, k) } } } @@ -231,6 +247,7 @@ func (c *Client) clearGraphQLPRBatchRepo(repo string) { for k := range c.prBatchCheckRuns { if k.repo == key { delete(c.prBatchCheckRuns, k) + delete(c.prBatchCheckObservedAt, k) } } } @@ -264,6 +281,10 @@ func (c *Client) storeGraphQLPRBatchNode(repo string, n graphQLPRBatchNode) { } key := prBatchCheckRunKey{repo: canonicalPRDetailRepo(repo), number: n.Number, headSHA: n.HeadRefOID} c.prBatchCheckRuns[key] = cloneCheckRuns(checks) + if c.prBatchCheckObservedAt == nil { + c.prBatchCheckObservedAt = map[prBatchCheckRunKey]time.Time{} + } + c.prBatchCheckObservedAt[key] = time.Now().UTC() c.prBatchMu.Unlock() } c.storeGraphQLPRBatchReview(repo, n) @@ -288,7 +309,7 @@ func graphQLCheckRuns(n graphQLPRBatchNode) ([]*gh.CheckRun, bool) { return nil, false } var out []*gh.CheckRun - for i, ctx := range n.Commits.Nodes[0].Commit.StatusCheckRollup.Contexts.Nodes { + for _, ctx := range n.Commits.Nodes[0].Commit.StatusCheckRollup.Contexts.Nodes { name, status, conclusion, url := "", "", "", "" switch ctx.TypeName { case "CheckRun": @@ -298,14 +319,39 @@ func graphQLCheckRuns(n graphQLPRBatchNode) ([]*gh.CheckRun, bool) { default: continue } - id := int64(i + 1) - out = append(out, &gh.CheckRun{ - ID: gh.Ptr(id), + run := &gh.CheckRun{ + ID: clonePtr(ctx.DatabaseID), + NodeID: gh.Ptr(ctx.ID), + HeadSHA: gh.Ptr(n.HeadRefOID), Name: gh.Ptr(name), Status: gh.Ptr(status), Conclusion: gh.Ptr(conclusion), DetailsURL: gh.Ptr(url), - }) + } + if oid := n.Commits.Nodes[0].Commit.OID; oid != "" { + run.HeadSHA = gh.Ptr(oid) + } + if ctx.TypeName == "CheckRun" { + if ctx.CheckSuite != nil && ctx.CheckSuite.Commit != nil && ctx.CheckSuite.Commit.OID != "" { + run.HeadSHA = gh.Ptr(ctx.CheckSuite.Commit.OID) + } + if ctx.CheckSuite != nil && ctx.CheckSuite.App != nil { + run.App = &gh.App{ID: clonePtr(ctx.CheckSuite.App.DatabaseID)} + } + if ctx.StartedAt != nil { + run.StartedAt = &gh.Timestamp{Time: *ctx.StartedAt} + } + if ctx.CompletedAt != nil { + run.CompletedAt = &gh.Timestamp{Time: *ctx.CompletedAt} + } + } else { + // Legacy statuses have a real node ID and creation time, but no + // numeric check-run or producer App identity. + if ctx.CreatedAt != nil { + run.StartedAt = &gh.Timestamp{Time: *ctx.CreatedAt} + } + } + out = append(out, run) } return out, true } @@ -331,17 +377,32 @@ func conclusionFromStatusContext(state string) string { } func (c *Client) graphQLBatchCheckRuns(repo string, number int, headSHA string) ([]*gh.CheckRun, bool) { + checks, _, ok := c.graphQLBatchCheckRunsObservation(repo, number, headSHA) + return checks, ok +} + +func (c *Client) graphQLBatchCheckRunsObservation(repo string, number int, headSHA string) ([]*gh.CheckRun, *time.Time, bool) { if c == nil || strings.TrimSpace(headSHA) == "" { - return nil, false + return nil, nil, false } + key := prBatchCheckRunKey{repo: canonicalPRDetailRepo(repo), number: number, headSHA: headSHA} c.prBatchMu.Lock() defer c.prBatchMu.Unlock() checks, ok := c.prBatchCheckRuns[key] if !ok { - return nil, false + return nil, nil, false + } + at := c.prBatchCheckObservedAt[key] + if at.IsZero() { + return cloneCheckRuns(checks), nil, true } - return cloneCheckRuns(checks), true + return cloneCheckRuns(checks), &at, true +} + +func (c *Client) graphQLBatchCheckObservedAt(repo string, number int, headSHA string) *time.Time { + _, at, _ := c.graphQLBatchCheckRunsObservation(repo, number, headSHA) + return at } func (c *Client) storeGraphQLPRBatchReview(repo string, n graphQLPRBatchNode) { @@ -402,14 +463,21 @@ func cloneCheckRuns(in []*gh.CheckRun) []*gh.CheckRun { continue } out = append(out, &gh.CheckRun{ - ID: clonePtr(cr.ID), - Name: clonePtr(cr.Name), - Status: clonePtr(cr.Status), - Conclusion: clonePtr(cr.Conclusion), - DetailsURL: clonePtr(cr.DetailsURL), - StartedAt: cloneTimestamp(cr.StartedAt), - App: cr.App, + ID: clonePtr(cr.ID), + NodeID: clonePtr(cr.NodeID), + HeadSHA: clonePtr(cr.HeadSHA), + Name: clonePtr(cr.Name), + Status: clonePtr(cr.Status), + Conclusion: clonePtr(cr.Conclusion), + DetailsURL: clonePtr(cr.DetailsURL), + StartedAt: cloneTimestamp(cr.StartedAt), + CompletedAt: cloneTimestamp(cr.CompletedAt), }) + if cr.App != nil { + app := *cr.App + app.ID = clonePtr(cr.App.ID) + out[len(out)-1].App = &app + } } return out } diff --git a/src/pkg/github/pr_batch_graphql_status_test.go b/src/pkg/github/pr_batch_graphql_status_test.go index c2045396c2..c0f5dd628e 100644 --- a/src/pkg/github/pr_batch_graphql_status_test.go +++ b/src/pkg/github/pr_batch_graphql_status_test.go @@ -53,9 +53,9 @@ func decodeGQLPRNode(t *testing.T, raw string) graphQLPRBatchNode { func TestGraphQLCheckRunsMixesCheckRunsAndStatusContexts(t *testing.T) { n := decodeGQLPRNode(t, gqlPRNodeWithContextsJSON(1, "sha-1", - `{"__typename":"CheckRun","name":"unit","status":"COMPLETED","conclusion":"SUCCESS","detailsUrl":"https://ci.example/unit"},`+ - `{"__typename":"StatusContext","context":"DCO","state":"FAILURE","targetUrl":"https://probot.github.io/apps/dco/"},`+ - `{"__typename":"StatusContext","context":"ci/pending","state":"PENDING"},`+ + `{"__typename":"CheckRun","id":"CR_unit","databaseId":101,"name":"unit","status":"COMPLETED","conclusion":"SUCCESS","detailsUrl":"https://ci.example/unit"},`+ + `{"__typename":"StatusContext","id":"SC_DCO","context":"DCO","state":"FAILURE","targetUrl":"https://probot.github.io/apps/dco/"},`+ + `{"__typename":"StatusContext","id":"SC_pending","context":"ci/pending","state":"PENDING"},`+ `{"__typename":"SomethingElse","name":"ignored","status":"COMPLETED","conclusion":"FAILURE"}`)) checks, ok := graphQLCheckRuns(n) @@ -65,15 +65,18 @@ func TestGraphQLCheckRunsMixesCheckRunsAndStatusContexts(t *testing.T) { if len(checks) != 3 { t.Fatalf("got %d check runs, want 3 (unknown __typename skipped)", len(checks)) } - want := []struct{ name, status, conclusion, url string }{ - {"unit", "completed", "success", "https://ci.example/unit"}, - {"DCO", "completed", "failure", "https://probot.github.io/apps/dco/"}, - {"ci/pending", "in_progress", "", ""}, + want := []struct { + id int64 + nodeID, name, status, conclusion, url string + }{ + {101, "CR_unit", "unit", "completed", "success", "https://ci.example/unit"}, + {0, "SC_DCO", "DCO", "completed", "failure", "https://probot.github.io/apps/dco/"}, + {0, "SC_pending", "ci/pending", "in_progress", "", ""}, } for i, w := range want { cr := checks[i] - if cr.GetID() != int64(i+1) { - t.Fatalf("check[%d] id = %d, want %d", i, cr.GetID(), i+1) + if cr.GetID() != w.id || cr.GetNodeID() != w.nodeID || cr.GetHeadSHA() != "sha-1" { + t.Fatalf("check[%d] identity = %d/%s/%s, want %d/%s/sha-1", i, cr.GetID(), cr.GetNodeID(), cr.GetHeadSHA(), w.id, w.nodeID) } if cr.GetName() != w.name || cr.GetStatus() != w.status || cr.GetConclusion() != w.conclusion || cr.GetDetailsURL() != w.url { t.Fatalf("check[%d] = %s/%s/%s/%s, want %s/%s/%s/%s", i, diff --git a/src/pkg/github/pr_ci_activity.go b/src/pkg/github/pr_ci_activity.go new file mode 100644 index 0000000000..9ca1ba6200 --- /dev/null +++ b/src/pkg/github/pr_ci_activity.go @@ -0,0 +1,172 @@ +package github + +import ( + "sort" + "strings" + "time" + + gh "github.com/google/go-github/v72/github" +) + +// PRCIActivity is display evidence, not a merge authorization. Required is +// resolved by the existing protection collector; an unresolved set stays unknown. +type PRCIActivity struct { + Head string `json:"head"` + Source string `json:"source"` + ObservedAt *time.Time `json:"observed_at,omitempty"` + RequiredKnown bool `json:"required_known"` + Required []string `json:"required,omitempty"` + RequiredChecks []PRRequiredCheck `json:"required_checks,omitempty"` + RequiredSource string `json:"required_source,omitempty"` + Checks []PRActivityCheck `json:"checks,omitempty"` + StatusesKnown bool `json:"statuses_known"` + StatusesObservedAt *time.Time `json:"statuses_observed_at,omitempty"` +} + +type PRActivityCheck struct { + Name string `json:"name"` + State string `json:"state"` + Conclusion string `json:"conclusion,omitempty"` + URL string `json:"url,omitempty"` + Since *time.Time `json:"since,omitempty"` + ID int64 `json:"id,omitempty"` + NodeID string `json:"node_id,omitempty"` + AppID *int64 `json:"app_id,omitempty"` + Head string `json:"head,omitempty"` + Kind string `json:"kind,omitempty"` +} + +// With AppKnown, nil or -1 is a forge-observed any-App constraint. +type PRRequiredCheck struct { + Name string `json:"name"` + AppID *int64 `json:"app_id"` + AppKnown bool `json:"app_known"` +} + +func prCIActivity(head, source string, checks []*gh.CheckRun, observed *time.Time) *PRCIActivity { + out := &PRCIActivity{Head: head, Source: source, ObservedAt: observed} + for _, cr := range checks { + if cr == nil || (cr.GetHeadSHA() != "" && !strings.EqualFold(cr.GetHeadSHA(), head)) { + continue + } + check := PRActivityCheck{Name: cr.GetName(), State: cr.GetStatus(), Conclusion: cr.GetConclusion(), URL: cr.GetDetailsURL()} + check.ID, check.NodeID, check.Head = cr.GetID(), cr.GetNodeID(), cr.GetHeadSHA() + if cr.App != nil && cr.App.GetID() > 0 { + check.AppID = clonePtr(cr.App.ID) + } + if at := cr.GetStartedAt(); !at.IsZero() { + t := at.Time + check.Since = &t + } + + if at := cr.GetCompletedAt(); cr.GetStatus() == "completed" && !at.IsZero() { + t := at.Time + check.Since = &t + } + out.Checks = append(out.Checks, check) + } + return out +} + +// ChecksForRequired excludes other producers when forge policy pins an App. +// Missing producer detail is unknown, not permission to use an optional App. +func (a *PRCIActivity) ChecksForRequired(name string) []PRActivityCheck { + var constraints []PRRequiredCheck + for _, required := range a.RequiredChecks { + if required.Name == name { + constraints = append(constraints, required) + } + } + var out []PRActivityCheck + for _, check := range a.Checks { + if check.Name != name || (check.Head != "" && !strings.EqualFold(check.Head, a.Head)) { + continue + } + if len(constraints) == 0 { + out = append(out, check) + continue + } + unknown := false + for _, required := range constraints { + if !required.AppKnown { + unknown = true + continue + } + if required.AppID == nil || *required.AppID == -1 || (check.AppID != nil && *check.AppID == *required.AppID) { + out = append(out, check) + unknown = false + break + } + unknown = unknown || check.AppID == nil + } + if unknown { + check.State, check.Conclusion = "unknown", "" + out = append(out, check) + } + } + return out +} + +func (a *PRCIActivity) setRequired(set map[string]bool, known bool) { + a.RequiredKnown = known + a.Required = nil + for name, required := range set { + if required { + a.Required = append(a.Required, name) + } + } + sort.Strings(a.Required) +} + +func (a *PRCIActivity) addCommitStatuses(statuses []*gh.RepoStatus, observedAt time.Time) { + a.StatusesKnown, a.StatusesObservedAt = true, &observedAt + for _, status := range statuses { + if status == nil { + continue + } + check := PRActivityCheck{ + Name: status.GetContext(), State: "completed", URL: status.GetTargetURL(), + ID: status.GetID(), NodeID: status.GetNodeID(), Head: a.Head, Kind: "commit_status", + } + switch status.GetState() { + case "success": + check.Conclusion = "success" + case "failure", "error": + check.Conclusion = "failure" + case "pending": + check.State = "pending" + default: + check.State = "unknown" + } + if at := status.GetCreatedAt(); !at.IsZero() { + t := at.Time + check.Since = &t + } + duplicate := false + for i, existing := range a.Checks { + if check.NodeID != "" && existing.NodeID == check.NodeID { + a.Checks[i] = check + duplicate = true + break + } + } + + if !duplicate { + a.Checks = append(a.Checks, check) + } + } +} + +// NeedsCommitStatusEvidence identifies REST snapshots whose any-App contexts +// also need the legacy status side before they can be called passing. +func (a *PRCIActivity) NeedsCommitStatusEvidence() bool { + if a.Source != "github-check-runs" { + return false + } + for _, binding := range a.RequiredChecks { + if binding.AppKnown && (binding.AppID == nil || *binding.AppID == -1) { + return true + } + } + return false +} diff --git a/src/pkg/github/pr_ci_activity_test.go b/src/pkg/github/pr_ci_activity_test.go new file mode 100644 index 0000000000..57c5a4e68e --- /dev/null +++ b/src/pkg/github/pr_ci_activity_test.go @@ -0,0 +1,56 @@ +package github + +import ( + "testing" + "time" + + gh "github.com/google/go-github/v72/github" +) + +func TestPRCIActivityBindsHeadAndObservation(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + checks := []*gh.CheckRun{ + nil, + {Name: gh.Ptr("old failure"), HeadSHA: gh.Ptr("old"), Status: gh.Ptr("completed"), Conclusion: gh.Ptr("failure")}, + {Name: gh.Ptr("build"), HeadSHA: gh.Ptr("head"), Status: gh.Ptr("in_progress"), StartedAt: &gh.Timestamp{Time: now}, DetailsURL: gh.Ptr("https://github.com/org/repo/actions/runs/1")}, + {Name: gh.Ptr("optional"), Status: gh.Ptr("completed"), Conclusion: gh.Ptr("skipped"), CompletedAt: &gh.Timestamp{Time: now}}, + } + a := prCIActivity("head", "github-check-runs", checks, &now) + if a.Head != "head" || a.ObservedAt != &now || len(a.Checks) != 2 || + a.Checks[0].Name != "build" || a.Checks[0].Since == nil || !a.Checks[0].Since.Equal(now) { + t.Fatalf("wrong head or timestamps: %+v", a) + } + a.setRequired(map[string]bool{"build": true, "optional": false}, true) + if !a.RequiredKnown || len(a.Required) != 1 || a.Required[0] != "build" { + t.Fatalf("optional check became required: %+v", a) + } + a.setRequired(nil, false) + if a.RequiredKnown || len(a.Required) != 0 { + t.Fatalf("unknown required set became known: %+v", a) + } +} + +func TestPRCIActivityGraphQLCacheObservationIsInvalidated(t *testing.T) { + now := time.Date(2026, 11, 2, 21, 0, 0, 0, time.UTC) + key := prBatchCheckRunKey{repo: "org/repo", number: 7, headSHA: "head"} + c := &Client{ + prBatchCheckRuns: map[prBatchCheckRunKey][]*gh.CheckRun{key: {}}, + prBatchCheckObservedAt: map[prBatchCheckRunKey]time.Time{key: now}, + } + if at := c.graphQLBatchCheckObservedAt("org/repo", 7, "head"); at == nil || !at.Equal(now) { + t.Fatalf("cache observation time lost: %v", at) + } + if at := c.graphQLBatchCheckObservedAt("org/repo", 7, "old"); at != nil { + t.Fatalf("old-head time leaked: %v", at) + } + c.invalidateGraphQLPRBatchPR("org/repo", 7) + if at := c.graphQLBatchCheckObservedAt("org/repo", 7, "head"); at != nil { + t.Fatalf("invalidated checks retained freshness: %v", at) + } + c.prBatchCheckRuns[key] = nil + c.prBatchCheckObservedAt[key] = now + c.clearGraphQLPRBatchRepo("org/repo") + if at := c.graphQLBatchCheckObservedAt("org/repo", 7, "head"); at != nil { + t.Fatalf("cleared repo retained freshness: %v", at) + } +} diff --git a/src/pkg/github/protection_facts.go b/src/pkg/github/protection_facts.go index af9e051172..6ad86958d0 100644 --- a/src/pkg/github/protection_facts.go +++ b/src/pkg/github/protection_facts.go @@ -30,8 +30,10 @@ type protectionCollector struct { } type requiredSet struct { - set map[string]bool - known bool + set map[string]bool + known bool + bindings []PRRequiredCheck + source string } // prReviewState is GitHub's review verdict for one PR, plus the display-only @@ -87,50 +89,68 @@ func (pc *protectionCollector) attach(ctx context.Context, pr *PullRequest, repo if reported != nil { req := pc.requiredChecks(ctx, pr.Repo, pr.BaseRef) + if pr.CIActivity != nil { + pr.CIActivity.setRequired(req.set, req.known) + pr.CIActivity.RequiredChecks = req.bindings + pr.CIActivity.RequiredSource = req.source + pr.CIActivity.RequiredKnown = req.known && req.source != "config" && observedRequiredBindings(req.set, req.bindings) + } if req.known { f.RequiredChecksKnown = true + needsStatuses := false + if pr.CIActivity != nil { + needsStatuses = pr.CIActivity.NeedsCommitStatusEvidence() + } + for name := range req.set { + present := reported[name] + if pr.CIActivity != nil && len(req.bindings) > 0 { + present = len(pr.CIActivity.ChecksForRequired(name)) > 0 + } + needsStatuses = needsStatuses || !present + } + statusesKnown := false + statuses := map[string]string{} + if needsStatuses { + collected, known := pc.c.commitStatuses(ctx, pr.Repo, pr.HeadSHA) + statusesKnown = known + if known { + for _, status := range collected { + statuses[status.GetContext()] = status.GetState() + } + if pr.CIActivity != nil { + pr.CIActivity.addCommitStatuses(collected, time.Now().UTC()) + } + } + } failing := make(map[string]bool, len(pr.FailingChecks)) for _, n := range pr.FailingChecks { failing[n] = true } - // observedRequired proves this repository reports its required - // contexts as CHECK RUNS. Without that proof a required context - // absent from the check-run listing may simply be a commit - // status, which this pass does not fetch; claiming it "has not - // reported" would be confidently wrong for every required - // context on such a repo. + // A check-run listing alone cannot prove a context is missing: + // legacy commit statuses may provide it. Failed status reads + // leave absence unknown, including for App-bound policy. observedRequired := 0 var missing, red []string for name := range req.set { + // Canonical facts retain their name-set contract. App-aware + // display ambiguity must not become a new merge policy. + _, statusReported := statuses[name] switch { - case failing[name]: + case failing[name] || statuses[name] == "failure" || statuses[name] == "error": observedRequired++ red = append(red, name) - case reported[name]: + case reported[name] || statusReported: observedRequired++ default: - missing = append(missing, name) + if statusesKnown { + missing = append(missing, name) + } } } f.FailingRequiredChecks = red - switch { - case observedRequired > 0: + if observedRequired > 0 || strings.EqualFold(pr.MergeableState, "blocked") { + sort.Strings(missing) f.MissingRequiredChecks = missing - case len(missing) > 0 && strings.EqualFold(pr.MergeableState, "blocked"): - // Nothing proves check-run reporting, but GitHub says the head is - // blocked: look at commit statuses before deciding. A context - // absent from both listings was never created, and must not be - // reported as merge-eligible (#11892). - if statuses, ok := pc.c.commitStatusContexts(ctx, pr.Repo, pr.HeadSHA); ok { - var never []string - for _, name := range missing { - if !statuses[name] { - never = append(never, name) - } - } - sort.Strings(never) - f.MissingRequiredChecks = never - } } } } @@ -146,25 +166,28 @@ func (pc *protectionCollector) attach(ctx context.Context, pr *PullRequest, repo pr.Protection = &f } -// commitStatusContexts returns the contexts of every commit status on sha, or -// ok=false when the listing could not be obtained. -func (c *Client) commitStatusContexts(ctx context.Context, repo, sha string) (map[string]bool, bool) { +// commitStatuses retains state and identity, not just context presence. +// A failed, incomplete or explicitly wrong-head listing is unknown. +func (c *Client) commitStatuses(ctx context.Context, repo, sha string) ([]*gh.RepoStatus, bool) { if sha == "" { return nil, false } owner, name := c.splitRepo(repo) - contexts := map[string]bool{} + var statuses []*gh.RepoStatus opts := &gh.ListOptions{PerPage: 100} for { status, resp, err := c.client.Repositories.GetCombinedStatus(ctx, owner, name, sha, opts) - if err != nil { + if err != nil || status == nil || status.Statuses == nil || (status.GetSHA() != "" && !strings.EqualFold(status.GetSHA(), sha)) { return nil, false } for _, st := range status.Statuses { - contexts[st.GetContext()] = true + if st == nil || strings.TrimSpace(st.GetContext()) == "" { + return nil, false + } + statuses = append(statuses, st) } if resp == nil || resp.NextPage == 0 { - return contexts, true + return statuses, true } opts.Page = resp.NextPage } @@ -176,8 +199,9 @@ func (pc *protectionCollector) requiredChecks(ctx context.Context, repo, branch return rs } owner, name := pc.c.splitRepo(repo) - set, known := pc.c.requiredStatusCheckContexts(ctx, owner, name, branch) - rs := requiredSet{set: set, known: known} + configSet, configKnown := pc.c.configRequiredChecksForRepo(owner + "/" + name) + set, known, _, _, source, bindings := RequiredStatusCheckPolicy(ctx, pc.c.client, owner, name, branch, configSet, configKnown) + rs := requiredSet{set: set, known: known, bindings: bindings, source: source} pc.required[key] = rs return rs } diff --git a/src/pkg/github/required_check_bindings.go b/src/pkg/github/required_check_bindings.go new file mode 100644 index 0000000000..9839a84bad --- /dev/null +++ b/src/pkg/github/required_check_bindings.go @@ -0,0 +1,189 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "sort" + "strings" + + gh "github.com/google/go-github/v72/github" +) + +func requiredBindings(contexts *[]string, checks *[]*gh.RequiredStatusCheck) []PRRequiredCheck { + byName := map[string][]PRRequiredCheck{} + if contexts != nil { + for _, name := range *contexts { + if strings.TrimSpace(name) != "" { + byName[name] = []PRRequiredCheck{{Name: name}} + } + } + } + // contexts is the compatibility projection of checks, not an additional + // any-App rule that can override a pinned producer. + seen := map[string]bool{} + if checks != nil { + for _, check := range *checks { + if check == nil || strings.TrimSpace(check.Context) == "" { + continue + } + if !seen[check.Context] { + byName[check.Context] = nil + seen[check.Context] = true + } + byName[check.Context] = append(byName[check.Context], PRRequiredCheck{Name: check.Context, AppID: clonePtr(check.AppID), AppKnown: true}) + } + } + var out []PRRequiredCheck + for _, checks := range byName { + out = append(out, checks...) + } + sort.Slice(out, func(i, j int) bool { + if out[i].Name != out[j].Name { + return out[i].Name < out[j].Name + } + if out[i].AppID == nil || out[j].AppID == nil { + return out[i].AppID == nil && out[j].AppID != nil + } + return *out[i].AppID < *out[j].AppID + }) + return out +} + +type requiredCheckWire struct { + Context string `json:"context"` + AppID json.RawMessage `json:"app_id"` +} + +func bindingsFromWire(contexts []string, checks []requiredCheckWire) []PRRequiredCheck { + var typed []*gh.RequiredStatusCheck + for _, check := range checks { + var id *int64 + _ = json.Unmarshal(check.AppID, &id) + typed = append(typed, &gh.RequiredStatusCheck{Context: check.Context, AppID: id}) + } + out := requiredBindings(&contexts, &typed) + for i := range out { + for _, check := range checks { + if check.Context == out[i].Name { + var id *int64 + if len(check.AppID) == 0 || json.Unmarshal(check.AppID, &id) != nil { + out[i].AppKnown = false + } + } + } + } + return out +} + +func observedRequiredBindings(names map[string]bool, bindings []PRRequiredCheck) bool { + for name := range names { + found := false + for _, check := range bindings { + if check.Name == name { + if !check.AppKnown || (check.AppID != nil && *check.AppID != -1 && *check.AppID <= 0) { + return false + } + found = true + } + } + if !found { + return false + } + } + return true +} + +func requiredStatusChecksFromProtectionEndpoint(ctx context.Context, client *gh.Client, owner, repo, branch string) (map[string]bool, []PRRequiredCheck, error) { + request, err := client.NewRequest(http.MethodGet, fmt.Sprintf("repos/%s/%s/branches/%s/protection/required_status_checks", owner, repo, url.PathEscape(branch)), nil) + if err != nil { + return nil, nil, err + } + var response *struct { + Contexts []string `json:"contexts"` + Checks []requiredCheckWire `json:"checks"` + } + _, err = client.Do(ctx, request, &response) + // Match go-github's sentinel conversion: a generic 404 does not prove + // the branch is unprotected and must still try the readable fallbacks. + if apiError, ok := err.(*gh.ErrorResponse); ok && apiError.Message == "Branch not protected" { + return nil, nil, gh.ErrBranchNotProtected + } + if err != nil { + return nil, nil, err + } + names := map[string]bool{} + if response == nil { + return names, nil, nil + } + names = requiredContextsFromRequiredStatusChecks(&response.Contexts, nil) + bindings := bindingsFromWire(response.Contexts, response.Checks) + for _, check := range bindings { + names[check.Name] = true + } + return names, bindings, nil +} + +func requiredBindingsFromRules(payload any) []PRRequiredCheck { + var checks []*gh.RequiredStatusCheck + known := map[string]bool{} + var collectChecks func(any) + collectChecks = func(v any) { + switch x := v.(type) { + case []any: + for _, item := range x { + collectChecks(item) + } + case map[string]any: + collectChecks(x["required_status_checks"]) + collectChecks(x["required_status_check_contexts"]) + if name, ok := x["context"].(string); ok && strings.TrimSpace(name) != "" { + var appID *int64 + rawID, present := x["integration_id"] + valid := present && rawID == nil + if id, ok := x["integration_id"].(float64); ok { + const maxExactRequiredAppID = 1 << 53 + if id <= maxExactRequiredAppID && id >= -1 && id != 0 && id == float64(int64(id)) { + value := int64(id) + appID, valid = &value, true + } + } + if previous, exists := known[name]; exists { + known[name] = previous && valid + } else { + known[name] = valid + } + checks = append(checks, &gh.RequiredStatusCheck{Context: name, AppID: appID}) + } + case string: + if strings.TrimSpace(x) != "" { + checks = append(checks, &gh.RequiredStatusCheck{Context: x}) + known[x] = false + } + } + } + var walk func(any) + walk = func(v any) { + switch x := v.(type) { + case []any: + for _, item := range x { + walk(item) + } + case map[string]any: + if typ, _ := x["type"].(string); typ == "required_status_checks" { + collectChecks(x["parameters"]) + collectChecks(x["required_status_checks"]) + } else { + walk(x["rules"]) + } + } + } + walk(payload) + out := requiredBindings(nil, &checks) + for i := range out { + out[i].AppKnown = known[out[i].Name] + } + return out +} diff --git a/src/pkg/github/required_check_bindings_test.go b/src/pkg/github/required_check_bindings_test.go new file mode 100644 index 0000000000..9a2c692f4c --- /dev/null +++ b/src/pkg/github/required_check_bindings_test.go @@ -0,0 +1,107 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +func TestRequiredCheckPolicy404PreservesSDKFallbackSemantics(t *testing.T) { + for _, tc := range []struct { + name, message, source string + status int + readableBranch, configKnown bool + known, empty, expectBranchRead bool + }{ + {"generic not found reads branch", "Not Found", "branch", http.StatusNotFound, true, false, true, false, true}, + {"empty not found reads branch", "", "branch", http.StatusNotFound, true, false, true, false, true}, + {"explicit unprotected is authoritative", "Branch not protected", "protection-unprotected", http.StatusNotFound, true, false, true, true, false}, + {"generic not found can use config", "Not Found", "config", http.StatusNotFound, false, true, true, false, true}, + {"generic not found without evidence is unknown", "Not Found", "none", http.StatusNotFound, false, false, false, true, true}, + {"denied without evidence is unknown", "Resource not accessible by integration", "none", http.StatusForbidden, false, false, false, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + var branchReads atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case strings.HasSuffix(r.URL.Path, "/protection/required_status_checks"): + w.WriteHeader(tc.status) + fmt.Fprintf(w, `{"message":%q}`, tc.message) + case r.URL.Path == "/repos/org/repo/branches/v5": + branchReads.Add(1) + if tc.readableBranch { + fmt.Fprint(w, `{"protected":true,"protection":{"required_status_checks":{"contexts":["build"],"checks":[{"context":"build","app_id":11}]}}}`) + } else { + http.Error(w, `{"message":"Resource not accessible by integration"}`, http.StatusForbidden) + } + default: + http.Error(w, `{"message":"Not Found"}`, http.StatusNotFound) + } + })) + defer srv.Close() + c := NewClientForTest(srv.URL, "org", []string{"repo"}, nil) + required, known, fromConfig, fallback, source, bindings := RequiredStatusCheckPolicy( + context.Background(), c.client, "org", "repo", "v5", map[string]bool{"configured": true}, tc.configKnown) + if known != tc.known || source != tc.source || (len(required) == 0) != tc.empty || + (branchReads.Load() > 0) != tc.expectBranchRead || fromConfig != (tc.source == "config") || + fallback != (tc.source == "config") { + t.Fatalf("required=%v known=%v source=%q config=%v fallback=%v branch reads=%d", required, known, source, fromConfig, fallback, branchReads.Load()) + } + if source == "branch" && (!required["build"] || len(bindings) != 1 || + !bindings[0].AppKnown || bindings[0].AppID == nil || *bindings[0].AppID != 11) { + t.Fatalf("readable branch fallback lost the actual required producer: %v %+v", required, bindings) + } + }) + } +} + +func TestRequiredCheckBindingPresenceAndExplicitAnyApp(t *testing.T) { + for _, tc := range []struct { + payload string + known bool + }{ + {`{"context":"build","app_id":11}`, true}, + {`{"context":"build","app_id":null}`, true}, + {`{"context":"build","app_id":-1}`, true}, + {`{"context":"build"}`, false}, + {`{"context":"build","app_id":"11"}`, false}, + } { + var check requiredCheckWire + if err := json.Unmarshal([]byte(tc.payload), &check); err != nil { + t.Fatal(err) + } + bindings := bindingsFromWire([]string{"build"}, []requiredCheckWire{check}) + if len(bindings) != 1 || bindings[0].AppKnown != tc.known || + observedRequiredBindings(map[string]bool{"build": true}, bindings) != tc.known { + t.Fatalf("%s produced %+v", tc.payload, bindings) + } + } + if bindings := bindingsFromWire([]string{"build"}, nil); observedRequiredBindings(map[string]bool{"build": true}, bindings) { + t.Fatal("name-only fallback claimed a known App constraint") + } + for _, id := range []string{"11", "null", "-1"} { + var payload any + if err := json.Unmarshal([]byte(`[{"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"build","integration_id":`+id+`}]}}]`), &payload); err != nil { + t.Fatal(err) + } + bindings := requiredBindingsFromRules(payload) + if len(bindings) != 1 || !bindings[0].AppKnown { + t.Fatalf("rules lost an explicit App constraint: %+v", bindings) + } + } + for _, field := range []string{"", `,"integration_id":"11"`, `,"integration_id":1.5`, `,"integration_id":9007199254740994`} { + var payload any + if err := json.Unmarshal([]byte(`[{"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"build"`+field+`}]}}]`), &payload); err != nil { + t.Fatal(err) + } + if bindings := requiredBindingsFromRules(payload); observedRequiredBindings(map[string]bool{"build": true}, bindings) { + t.Fatalf("missing/malformed rules binding claimed known policy: %s", field) + } + } +} diff --git a/src/pkg/review/dispatch.go b/src/pkg/review/dispatch.go index 14fa5329d1..8bac9cdeef 100644 --- a/src/pkg/review/dispatch.go +++ b/src/pkg/review/dispatch.go @@ -1970,35 +1970,42 @@ func pendingMissingPerspectives(state DispatchState, pr PullRequest, perspective func removeCompletedReviews(pending []PendingReview, artifact Artifact) []PendingReview { out := pending[:0] for _, p := range pending { - agg, ok := artifact.AggregateForBody(p.Repo, p.Number, p.HeadSHA, p.BodyDigest) - if !ok || strings.TrimSpace(agg.BodyDigest) != strings.TrimSpace(p.BodyDigest) || - (!agg.RecordedAt.IsZero() && agg.RecordedAt.Before(p.Dispatched)) { - out = append(out, p) - continue - } - _, reported := agg.Perspectives[p.Perspective] - if p.Decision { - reported = reported && agg.Decided && agg.Verdict != VerdictIncomplete - } else if p.Head != "" { - reported = containsHead(agg.Heads[p.Perspective], p.Head) - } - fresh := false - for _, receipt := range agg.ReportReceipts { - if receipt.Agent != "" && receipt.Agent == p.Agent && - receipt.Perspective == p.Perspective && receipt.Head == p.Head && - receipt.Decided == p.Decision && !receipt.ReceivedAt.IsZero() && - !receipt.ReceivedAt.Before(p.Dispatched) { - fresh = true - break - } - } - if !reported || !fresh { + if !PendingReviewCompleted(p, artifact) { out = append(out, p) } } return out } +// PendingReviewCompleted is the dispatch ledger's completion rule, shared +// with display consumers. Another agent's same-perspective report is not a +// receipt for this assignment. +func PendingReviewCompleted(p PendingReview, artifact Artifact) bool { + agg, ok := artifact.AggregateForBody(p.Repo, p.Number, p.HeadSHA, p.BodyDigest) + if !ok || strings.TrimSpace(agg.BodyDigest) != strings.TrimSpace(p.BodyDigest) || + (!agg.RecordedAt.IsZero() && agg.RecordedAt.Before(p.Dispatched)) { + return false + } + _, reported := agg.Perspectives[p.Perspective] + if p.Decision { + reported = reported && agg.Decided && agg.Verdict != VerdictIncomplete + } else if p.Head != "" { + reported = containsHead(agg.Heads[p.Perspective], p.Head) + } + if !reported { + return false + } + for _, receipt := range agg.ReportReceipts { + if receipt.Agent != "" && receipt.Agent == p.Agent && + receipt.Perspective == p.Perspective && receipt.Head == p.Head && + receipt.Decided == p.Decision && !receipt.ReceivedAt.IsZero() && + !receipt.ReceivedAt.Before(p.Dispatched) { + return true + } + } + return false +} + // PendingReviewerOccupancy counts durable dispatch bookkeeping, not running // processes. Confirmation means kick delivery, never review completion. func PendingReviewerOccupancy(state DispatchState) (records, agents, confirmedAgents int) { diff --git a/src/pkg/webassets/trackerrow/tracker-row-anchor.js b/src/pkg/webassets/trackerrow/tracker-row-anchor.js index 314194e50d..807d3c153e 100644 --- a/src/pkg/webassets/trackerrow/tracker-row-anchor.js +++ b/src/pkg/webassets/trackerrow/tracker-row-anchor.js @@ -16,9 +16,19 @@ // attempt that found the conflict) or a planner-ordered merge_train // still rides on the record — hive's own #15574 read "Fixing" under // Merge queue after "fell back to Fixing — conflicting". - function stageTrackerAnchor(stage, stages, kind, item) { + function stageTrackerAnchor(stage, stages, kind, item, presentation) { const cur = Number(stage) || 0; if (cur >= STAGE_TRACKER_TERMINAL) return STAGE_TRACKER_TERMINAL; + // Backend evidence owns this presentation mapping, never a label or + // client-side interpretation of a CI failure. Native stages stay intact. + const displayHeadMatches = item && item.code_activity && String(item.code_activity.head || '') === String(item.head || ''); + if (presentation !== false && cur < 80 && displayHeadMatches && (Number(item.display_column) === 30 || Number(item.display_column) === 50)) return Number(item.display_column); + // Older payloads can identify owner waits/adoption, but cannot prove + // coding. Keep their native words; never use this fallback for counts/sort. + if (presentation !== false && item && !item.code_activity && !item.merge_gate && !item.merge_train && [71, 72, 74].includes(cur)) { + if (item.push && ['pushed', 'checking'].includes(item.push.state)) return 50; + return STAGE_TRACKER_PR_COLUMN; + } // Under repair past 030 → CI / Review, before any gate or train // promotion. The one park the predicate also names, 085 needs // decision, stays at the gate: the person decides there. diff --git a/src/pkg/webassets/trackerrow/trackerrow_test.go b/src/pkg/webassets/trackerrow/trackerrow_test.go index 18acfb4566..1b919ad4ae 100644 --- a/src/pkg/webassets/trackerrow/trackerrow_test.go +++ b/src/pkg/webassets/trackerrow/trackerrow_test.go @@ -35,7 +35,7 @@ func TestFilesMatchEmbed(t *testing.T) { func TestAssetsDefineRowFunctions(t *testing.T) { want := map[string][]string{ "tracker-row-anchor.js": { - "function stageTrackerAnchor(stage, stages, kind, item) {", + "function stageTrackerAnchor(stage, stages, kind, item, presentation) {", }, "tracker-row-title.js": { "function stageTrackerSplitTitleTag(title) {",