diff --git a/docs/testing/end-to-end.md b/docs/testing/end-to-end.md index 518f7985..0696e99d 100644 --- a/docs/testing/end-to-end.md +++ b/docs/testing/end-to-end.md @@ -425,6 +425,11 @@ What it carries, and what is left over in each row: | 9.181 πŸ–₯ | Mobile options only for mobile projects | Conch.app on this Mac with three local projects: an iOS app, a plain Go service, and one whose app exists only on an agent's branch (worktree); then have an agent create an Expo app in the Go project | Right-click: **Mobile Preview** on the iOS project and the branch-only one, not on the Go service; a workbench on the Go service has no phone button and no Mobile layout; once the agent writes the Expo app's package.json, Mobile Preview appears there within seconds; in the branch-only project, β–Ά Run builds in the checkout that has the app | ☐ | | 9.182 | Pruning merged branches against GitHub | In a real repository: merge one branch's pull request on GitHub with a squash, another with a merge commit, and merge a third locally; push a fourth unmerged; commit once more on a fifth after its merge. Run `conch branch prune -merged`, then Settings β†’ Git β†’ Old branches β†’ Merged in Conch.app, and delete. | All three merged ones are listed (the squashed one once GitHub says it merged), ticked, and deleted; the pushed one and the one with a later commit are not listed; a branch checked out in a worktree is listed and kept. Against a server from before this, both say to reload it and delete nothing. | ☐ | | 9.183 πŸ–₯ | Agent teams in Conch.app with real agents | With `[[teams]]` Backend (a project) and UI (a branch pattern) and a dozen agents across two projects: watch Agents split; right-click one β†’ Team β†’ UI; drag another onto Backend and onto No team; New Task with a team; Show Side by Side and Broadcast to This Team… on a team's row; `conch server reload`; `conch status -team UI`. | Each project's Agents shows Backend, UI, then No team, with counts; a project with no team keeps its list. A move by menu or drag lands at once, in every window and the TUI's `conch status -team`; a reload keeps it. Side by Side puts the team's agents in one tab; the broadcast reaches only them. | ☐ | +| 9.184 πŸ’³πŸŒ | Conch.app's commit graph with agents | A project with Claude and Codex on task branches, one with an open pull request on a real GitHub repository and red CI, one whose change master then touches on the same lines; open **Commit Graph**. Rebase the second onto master by hand so it stops, then **Ask Codex to resolve**, and its menu's *Start a new agent* on another; **Hand to an Agent…** on an older commit; a SHA-256 reftable repository (`git init --object-format=sha256 --ref-format=reftable`) added as a project | Agents on branches lists both in urgency order with the right agent and ↑/↓; commits show their agent; the CI squares match GitHub; *will conflict* shows before anything moves, the banner when the rebase stops; the agent gets the files and resolves without pushing; the new task's branch starts at the commit; the header says **Git 3 Β· SHA-256 Β· reftable** | ☐ | +| 9.185 🌐 | The CI panel against real GitHub Actions | On a project with a month of real Actions history and `gh` logged in: **Commit Graph** β†’ **CI**, then 7d, 14d and 30d; on a busy repository watch *Reading the jobs of N more runs…* fill in; break a test on a branch, let its run fail, then **Re-run failed jobs** in the panel and **Re-run Failed Jobs** on the branch's menu | The numbers match GitHub's Actions page for the period (pass rate, the failing runs, a job's time); the re-run starts a new attempt of that run on GitHub, the button says *Re-running…* until the attempt shows, and the pull request's checks turn pending | ☐ | +| 9.186 πŸ’³πŸŒ | The autopilot's activity in Conch.app | With the autopilot on (auto_fix, auto_merge, auto_resolve, a check) for a real GitHub repository and a real agent on a task branch: open **Commit Graph** β†’ **Autopilot** and leave it open; break a test so CI fails, let the agent fix it, let the pull request merge; then quit everything, reload the server, and open it again | Each step appears in *What it did* as it happens (CI sent to the agent, pushed, merged), marked by kind, under Today, with the branch a link to its commits; *Minding now* follows the branch; the rules match Settings; after the reload the feed is all still there | ☐ | +| 9.187 πŸ’³ | Review and push a resolved rebase in Conch.app | A task branch pushed with a pull request, then the base changed on the same lines: open **Commit Graph**, **Ask an agent to resolve** with a real agent, wait for it to finish the rebase | The banner turns green (*rebased onto master*), the branch's card lists each commit old β†’ new with the conflicted one marked *resolved*; **Review the resolution** shows the agent's own lines as + / βˆ’; **Push (with lease)** replaces the old branch on GitHub and the pull request updates; on a second run, **Undo the rebase** puts the branch back and the conflict returns; with a commit pushed from elsewhere in between, the push is refused rather than overwriting it | ☐ | +| 9.188 πŸ’³ | Watch an agent resolve a conflict in Conch.app | A task branch whose rebase onto master stopped on a conflict: open **Commit Graph**, **Ask an agent to resolve** with a real agent; then once more with `auto_resolve` on and the autopilot asking | While the agent works the banner turns blue (*Claude is resolving the conflict with master*, *N of M files left Β· you asked …*, or *the autopilot asked*), the branch reads *resolving*, and **Show Claude** opens its pane; when the agent asks a permission question the banner says it is waiting on you; it turns green once the rebase is finished; closing the agent's pane mid-way turns it red (*has ended*) with **Ask again**; after `conch server reload` an agent still working in the stopped worktree still reads *resolving* | ☐ | Everything else marked πŸ’³ wants a model: the brain's providers (1.x), an agent's own state hooks and usage (2.1-2.5, 9.1, 9.21, 9.22, 9.70), saved diff --git a/internal/ghx/actions.go b/internal/ghx/actions.go new file mode 100644 index 00000000..6e484a1e --- /dev/null +++ b/internal/ghx/actions.go @@ -0,0 +1,382 @@ +package ghx + +import ( + "context" + "encoding/json" + "fmt" + "math" + "sort" + "strconv" + "time" +) + +// A repository's GitHub Actions history, read through gh, and what conch +// says about it: how often it passes, how long it takes, which jobs are +// slow or flaky, and which failures can be run again. + +// Run is one workflow run, at its latest attempt. +type Run struct { + ID int64 + Workflow string + Branch string + Sha string + Event string + Status string // queued, in_progress, completed + Conclusion string // success, failure, cancelled, timed_out, skipped… once completed + Attempt int + URL string + Created time.Time + Started time.Time + Updated time.Time +} + +// Job is one job of a run. +type Job struct { + Name string + Conclusion string + Started time.Time + Completed time.Time +} + +// Runs lists the repository's newest workflow runs, up to limit. +func Runs(ctx context.Context, dir string, limit int) ([]Run, error) { + out, err := run(ctx, dir, "run", "list", "--limit", strconv.Itoa(limit), "--json", + "databaseId,workflowName,headBranch,headSha,event,status,conclusion,attempt,url,createdAt,startedAt,updatedAt") + if err != nil { + return nil, err + } + var raw []struct { + ID int64 `json:"databaseId"` + Workflow string `json:"workflowName"` + Branch string `json:"headBranch"` + Sha string `json:"headSha"` + Event string `json:"event"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + Attempt int `json:"attempt"` + URL string `json:"url"` + Created time.Time `json:"createdAt"` + Started time.Time `json:"startedAt"` + Updated time.Time `json:"updatedAt"` + } + if err := json.Unmarshal(out, &raw); err != nil { + return nil, fmt.Errorf("gh run list: %w", err) + } + runs := make([]Run, 0, len(raw)) + for _, r := range raw { + runs = append(runs, Run{ID: r.ID, Workflow: r.Workflow, Branch: r.Branch, Sha: r.Sha, Event: r.Event, Status: r.Status, + Conclusion: r.Conclusion, Attempt: r.Attempt, URL: r.URL, Created: r.Created, Started: r.Started, Updated: r.Updated}) + } + return runs, nil +} + +// RunJobs lists a run's jobs. A finished run's jobs never change, so a +// caller may keep them. +func RunJobs(ctx context.Context, dir string, id int64) ([]Job, error) { + out, err := run(ctx, dir, "run", "view", strconv.FormatInt(id, 10), "--json", "jobs") + if err != nil { + return nil, err + } + var raw struct { + Jobs []struct { + Name string `json:"name"` + Conclusion string `json:"conclusion"` + Started time.Time `json:"startedAt"` + Completed time.Time `json:"completedAt"` + } `json:"jobs"` + } + if err := json.Unmarshal(out, &raw); err != nil { + return nil, fmt.Errorf("gh run view: %w", err) + } + jobs := make([]Job, 0, len(raw.Jobs)) + for _, j := range raw.Jobs { + jobs = append(jobs, Job{Name: j.Name, Conclusion: j.Conclusion, Started: j.Started, Completed: j.Completed}) + } + return jobs, nil +} + +// Rerun runs a run's failed jobs again, as a new attempt of the same run. +func Rerun(ctx context.Context, dir string, id int64) error { + _, err := run(ctx, dir, "run", "rerun", strconv.FormatInt(id, 10), "--failed") + return err +} + +// FailedRunID is the newest failed Actions run on branch β€” at commit head +// when given β€” for a re-run asked for by branch rather than by run. +func FailedRunID(ctx context.Context, dir, branch, head string) (int64, error) { + runs, err := failedRuns(ctx, dir, branch, head) + if err != nil { + return 0, err + } + return runs[0].ID, nil +} + +// failed says whether a finished run's conclusion is a failure: a timeout +// is one, a cancellation is somebody's choice. +func failed(conclusion string) bool { return conclusion == "failure" || conclusion == "timed_out" } + +// CIStats is what the CI panel shows for a period of whole days. +type CIStats struct { + Days int + // Finished runs that passed or failed in the period (a cancelled or + // skipped run is neither), and the same for the period before it. + Runs, Passed, Failed int + PrevRuns, PrevPassed int + // Medians, in seconds, of a run's time from start to finish and of + // its wait in the queue; the run time also for the period before. + MedianSeconds, PrevMedianSeconds, QueueSeconds int + // How long a branch stayed red: from a failed run to the next passing + // run of the same workflow on the same branch, median, and how many. + RedToGreenSeconds, RedToGreenCount int + // One entry a day, the oldest first and today last. + Daily []CIDay + // Each job, the slowest (by median) first. + Jobs []CIJob + // Jobs and runs that failed and then passed without a change. + Flaky []CIFlaky + // The newest run of each workflow on each branch, where it failed: + // what can be run again. + Failing []Run + // How many of the period's runs had their jobs read. + JobsRead int +} + +// CIDay is one day's finished runs. +type CIDay struct { + Date string // YYYY-MM-DD in the server's time zone + Passed, Failed int +} + +// CIJob is one job's record over the period. +type CIJob struct { + Name string + Runs, Failed int + MedianSeconds, P90Seconds int +} + +// CIFlaky is a job (or a whole run) that failed and passed with nothing +// changed: on the same commit, or on a second attempt of the same run. +type CIFlaky struct { + Name string + Times int + How string + Last time.Time +} + +// ComputeStats works out a period's statistics: the days days up to and +// including now's (in loc), and the same number before them. jobs holds +// the jobs of whichever runs have been read. +func ComputeStats(runs []Run, jobs map[int64][]Job, now time.Time, days int, loc *time.Location) CIStats { + if days < 1 { + days = 1 + } + y, m, d := now.In(loc).Date() + start := time.Date(y, m, d, 0, 0, 0, 0, loc).AddDate(0, 0, -(days - 1)) + prevStart := start.AddDate(0, 0, -days) + s := CIStats{Days: days} + day := map[string]int{} + for i := range days { + date := start.AddDate(0, 0, i).Format("2006-01-02") + day[date] = i + s.Daily = append(s.Daily, CIDay{Date: date}) + } + var durations, prevDurations, queues []int + type jobAcc struct { + runs, failed int + secs []int + } + jobAccs := map[string]*jobAcc{} + var inPeriod []Run + for _, r := range runs { + finished := r.Status == "completed" && (r.Conclusion == "success" || failed(r.Conclusion)) + switch { + case !finished: + continue + case !r.Created.Before(start): + inPeriod = append(inPeriod, r) + s.Runs++ + i := day[r.Created.In(loc).Format("2006-01-02")] + if r.Conclusion == "success" { + s.Passed++ + s.Daily[i].Passed++ + } else { + s.Failed++ + s.Daily[i].Failed++ + } + if !r.Started.IsZero() && r.Updated.After(r.Started) { + durations = append(durations, int(r.Updated.Sub(r.Started).Seconds())) + } + if !r.Started.IsZero() && !r.Started.Before(r.Created) { + queues = append(queues, int(r.Started.Sub(r.Created).Seconds())) + } + if js, ok := jobs[r.ID]; ok { + s.JobsRead++ + for _, j := range js { + a := jobAccs[j.Name] + if a == nil { + a = &jobAcc{} + jobAccs[j.Name] = a + } + a.runs++ + if failed(j.Conclusion) { + a.failed++ + } + if !j.Started.IsZero() && j.Completed.After(j.Started) { + a.secs = append(a.secs, int(j.Completed.Sub(j.Started).Seconds())) + } + } + } + case !r.Created.Before(prevStart): + s.PrevRuns++ + if r.Conclusion == "success" { + s.PrevPassed++ + } + if !r.Started.IsZero() && r.Updated.After(r.Started) { + prevDurations = append(prevDurations, int(r.Updated.Sub(r.Started).Seconds())) + } + } + } + s.MedianSeconds = percentile(durations, 0.5) + s.PrevMedianSeconds = percentile(prevDurations, 0.5) + s.QueueSeconds = percentile(queues, 0.5) + for name, a := range jobAccs { + s.Jobs = append(s.Jobs, CIJob{Name: name, Runs: a.runs, Failed: a.failed, MedianSeconds: percentile(a.secs, 0.5), P90Seconds: percentile(a.secs, 0.9)}) + } + sort.Slice(s.Jobs, func(i, j int) bool { + if s.Jobs[i].MedianSeconds != s.Jobs[j].MedianSeconds { + return s.Jobs[i].MedianSeconds > s.Jobs[j].MedianSeconds + } + return s.Jobs[i].Name < s.Jobs[j].Name + }) + + // Oldest first from here: red to green, and flakiness, follow time. + sort.Slice(inPeriod, func(i, j int) bool { + if !inPeriod[i].Created.Equal(inPeriod[j].Created) { + return inPeriod[i].Created.Before(inPeriod[j].Created) + } + return inPeriod[i].ID < inPeriod[j].ID + }) + redSince := map[string]time.Time{} + var greens []int + for _, r := range inPeriod { + k := r.Workflow + "\x00" + r.Branch + if failed(r.Conclusion) { + if _, ok := redSince[k]; !ok { + redSince[k] = r.Updated + } + } else if t, ok := redSince[k]; ok { + greens = append(greens, int(r.Updated.Sub(t).Seconds())) + delete(redSince, k) + } + } + s.RedToGreenSeconds, s.RedToGreenCount = percentile(greens, 0.5), len(greens) + + // A job that failed and passed on one commit in one workflow. + type seen struct{ failed, passed bool } + bySha := map[string]map[string]*seen{} + last := map[string]time.Time{} + for _, r := range inPeriod { + k := r.Workflow + "\x00" + r.Sha + if bySha[k] == nil { + bySha[k] = map[string]*seen{} + } + for _, j := range jobs[r.ID] { + sn := bySha[k][j.Name] + if sn == nil { + sn = &seen{} + bySha[k][j.Name] = sn + } + if failed(j.Conclusion) { + sn.failed = true + } else if j.Conclusion == "success" { + sn.passed = true + } + if sn.failed && sn.passed && r.Updated.After(last[k+"\x00"+j.Name]) { + last[k+"\x00"+j.Name] = r.Updated + } + } + } + flaky := map[string]*CIFlaky{} + for k, names := range bySha { + for name, sn := range names { + if !sn.failed || !sn.passed { + continue + } + f := flaky[name] + if f == nil { + f = &CIFlaky{Name: name, How: "failed and passed on the same commit"} + flaky[name] = f + } + f.Times++ + if t := last[k+"\x00"+name]; t.After(f.Last) { + f.Last = t + } + } + } + for _, f := range flaky { + s.Flaky = append(s.Flaky, *f) + } + sort.Slice(s.Flaky, func(i, j int) bool { + if s.Flaky[i].Times != s.Flaky[j].Times { + return s.Flaky[i].Times > s.Flaky[j].Times + } + return s.Flaky[i].Name < s.Flaky[j].Name + }) + // A run that passed only on a later attempt: which job failed first is + // not in the run's latest attempt, so the run itself is named. + retried := map[string]*CIFlaky{} + var retriedNames []string + for _, r := range inPeriod { + if r.Attempt > 1 && r.Conclusion == "success" { + f := retried[r.Workflow] + if f == nil { + f = &CIFlaky{Name: r.Workflow} + retried[r.Workflow] = f + retriedNames = append(retriedNames, r.Workflow) + } + f.Times++ + f.How = fmt.Sprintf("passed on attempt %d", r.Attempt) + f.Last = r.Updated + } + } + sort.Strings(retriedNames) + for _, n := range retriedNames { + s.Flaky = append(s.Flaky, *retried[n]) + } + + // What can be run again: each workflow's newest run on each branch, + // where it failed. Newest first. + newest := map[string]Run{} + for _, r := range runs { + if r.Status != "completed" { + continue + } + k := r.Workflow + "\x00" + r.Branch + if o, ok := newest[k]; !ok || r.Created.After(o.Created) || (r.Created.Equal(o.Created) && r.ID > o.ID) { + newest[k] = r + } + } + for _, r := range newest { + if failed(r.Conclusion) { + s.Failing = append(s.Failing, r) + } + } + sort.Slice(s.Failing, func(i, j int) bool { + if !s.Failing[i].Created.Equal(s.Failing[j].Created) { + return s.Failing[i].Created.After(s.Failing[j].Created) + } + return s.Failing[i].ID > s.Failing[j].ID + }) + return s +} + +// percentile is the nearest-rank percentile of xs (p in 0..1), 0 for none. +func percentile(xs []int, p float64) int { + if len(xs) == 0 { + return 0 + } + s := append([]int(nil), xs...) + sort.Ints(s) + i := int(math.Ceil(p*float64(len(s)))) - 1 + return s[max(0, min(i, len(s)-1))] +} diff --git a/internal/ghx/cistats_test.go b/internal/ghx/cistats_test.go new file mode 100644 index 00000000..b0225c4b --- /dev/null +++ b/internal/ghx/cistats_test.go @@ -0,0 +1,213 @@ +package ghx + +import ( + "context" + "errors" + "strings" + "testing" + "time" +) + +var statsNow = time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC) + +// run is a finished run that started at the given hours before statsNow, +// queued q seconds and took d seconds. +func ciRun(id int64, wf, branch, sha, conclusion string, hoursAgo float64, q, d int) Run { + created := statsNow.Add(-time.Duration(hoursAgo * float64(time.Hour))) + started := created.Add(time.Duration(q) * time.Second) + return Run{ID: id, Workflow: wf, Branch: branch, Sha: sha, Conclusion: conclusion, Status: "completed", Attempt: 1, + Created: created, Started: started, Updated: started.Add(time.Duration(d) * time.Second)} +} + +func job(name, conclusion string, secs int) Job { + start := statsNow.Add(-48 * time.Hour) + return Job{Name: name, Conclusion: conclusion, Started: start, Completed: start.Add(time.Duration(secs) * time.Second)} +} + +func TestStatsCounts(t *testing.T) { + runs := []Run{ + ciRun(6, "ci", "feat", "s3", "success", 2, 10, 300), + ciRun(5, "ci", "feat", "s2", "failure", 5, 20, 600), + ciRun(4, "ci", "main", "m1", "success", 30, 30, 400), + ciRun(3, "ci", "feat", "s1", "cancelled", 40, 5, 50), + // The prior period: older than the 7 days asked for. + ciRun(2, "ci", "main", "m0", "failure", 24*9, 10, 100), + ciRun(1, "ci", "main", "m0", "success", 24*10, 10, 100), + // Still running: counted nowhere yet. + {ID: 7, Workflow: "ci", Branch: "feat", Status: "in_progress", Created: statsNow.Add(-time.Hour)}, + } + jobs := map[int64][]Job{ + 6: {job("build", "success", 60), job("test", "success", 240)}, + 5: {job("build", "success", 80), job("test", "failure", 500)}, + 4: {job("build", "success", 70), job("test", "success", 300)}, + } + s := ComputeStats(runs, jobs, statsNow, 7, time.UTC) + // A cancelled run is neither a pass nor a failure. + if s.Runs != 3 || s.Passed != 2 || s.Failed != 1 { + t.Fatalf("counts: %+v", s) + } + if s.PrevRuns != 2 || s.PrevPassed != 1 { + t.Errorf("prior period: %d runs, %d passed", s.PrevRuns, s.PrevPassed) + } + if s.MedianSeconds != 400 || s.QueueSeconds != 20 { + t.Errorf("median %d, queue %d", s.MedianSeconds, s.QueueSeconds) + } + if s.JobsRead != 3 { + t.Errorf("jobs read for %d runs", s.JobsRead) + } + // One entry a day, oldest first, today last. + if len(s.Daily) != 7 || s.Daily[6].Date != "2026-11-14" || s.Daily[6].Passed != 1 || s.Daily[6].Failed != 1 { + t.Errorf("daily: %+v", s.Daily) + } + if s.Daily[5].Date != "2026-11-13" || s.Daily[5].Passed != 1 { + t.Errorf("yesterday: %+v", s.Daily[5]) + } + // Jobs, slowest first, with their median and slowest tenth. + if len(s.Jobs) != 2 || s.Jobs[0].Name != "test" || s.Jobs[0].Runs != 3 || s.Jobs[0].Failed != 1 || + s.Jobs[0].MedianSeconds != 300 || s.Jobs[0].P90Seconds != 500 { + t.Errorf("jobs: %+v", s.Jobs) + } + // The failure on feat went green when the next run on it finished. + if s.RedToGreenSeconds != 3*3600+310-620 || s.RedToGreenCount != 1 { + t.Errorf("red to green %d over %d", s.RedToGreenSeconds, s.RedToGreenCount) + } +} + +// A job that failed and passed on the same commit is flaky; so is a run +// that passed only on its second attempt. A failure fixed by a new commit +// is not. +func TestStatsFlaky(t *testing.T) { + runs := []Run{ + ciRun(4, "ci", "feat", "same", "success", 1, 1, 10), + ciRun(3, "ci", "feat", "same", "failure", 2, 1, 10), + ciRun(2, "ci", "feat", "fixed", "failure", 3, 1, 10), + ciRun(1, "ci", "feat", "fixed2", "success", 4, 1, 10), + } + retried := ciRun(5, "lint", "main", "x", "success", 1, 1, 10) + retried.Attempt = 2 + runs = append(runs, retried) + jobs := map[int64][]Job{ + 4: {job("test macos", "success", 9), job("build", "success", 1)}, + 3: {job("test macos", "failure", 9), job("build", "success", 1)}, + 2: {job("build", "failure", 1)}, + 1: {job("build", "success", 1)}, + } + s := ComputeStats(runs, jobs, statsNow, 7, time.UTC) + if len(s.Flaky) != 2 || s.Flaky[0].Name != "test macos" || s.Flaky[0].Times != 1 { + t.Fatalf("flaky: %+v", s.Flaky) + } + if s.Flaky[1].Name != "lint" || !strings.Contains(s.Flaky[1].How, "attempt") { + t.Errorf("a run that passed on a retry: %+v", s.Flaky[1]) + } +} + +// Failures that can still be re-run: the newest run of each workflow on a +// branch, when it failed β€” not one a later run already replaced. +func TestStatsFailing(t *testing.T) { + runs := []Run{ + ciRun(5, "ci", "feat", "b", "failure", 1, 1, 10), + ciRun(4, "ci", "feat", "a", "failure", 2, 1, 10), + ciRun(3, "ci", "main", "m", "success", 1, 1, 10), + ciRun(2, "ci", "main", "l", "failure", 2, 1, 10), + ciRun(1, "lint", "feat", "b", "timed_out", 1, 1, 10), + } + s := ComputeStats(runs, nil, statsNow, 7, time.UTC) + var ids []int64 + for _, f := range s.Failing { + ids = append(ids, f.ID) + } + if len(ids) != 2 || ids[0] != 5 || ids[1] != 1 { + t.Fatalf("failing: %+v", s.Failing) + } +} + +// Nothing ran: every number is zero and every day is there, empty. +func TestStatsEmpty(t *testing.T) { + s := ComputeStats(nil, nil, statsNow, 30, time.UTC) + if s.Runs != 0 || s.MedianSeconds != 0 || len(s.Daily) != 30 || len(s.Jobs) != 0 || s.Days != 30 { + t.Fatalf("%+v", s) + } + if s := ComputeStats(nil, nil, statsNow, 0, time.UTC); s.Days != 1 || len(s.Daily) != 1 { + t.Errorf("no days asked is one: %+v", s) + } +} + +func TestPercentile(t *testing.T) { + for _, c := range []struct { + xs []int + p float64 + want int + }{ + {nil, 0.5, 0}, + {[]int{7}, 0.9, 7}, + {[]int{3, 1, 2}, 0.5, 2}, + {[]int{1, 2, 3, 4}, 0.5, 2}, + {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 0.9, 9}, + } { + if got := percentile(c.xs, c.p); got != c.want { + t.Errorf("percentile(%v, %v) = %d, want %d", c.xs, c.p, got, c.want) + } + } +} + +// gh's own JSON, as gh run list and gh run view print it. +func TestRunsAndJobsThroughGH(t *testing.T) { + fakeGH(t, `case "$1 $2" in +"run list") cat <<'EOF' +[{"attempt":2,"conclusion":"success","createdAt":"2026-11-15T00:40:36Z","databaseId":43,"event":"pull_request","headBranch":"feat","headSha":"abc","startedAt":"2026-11-15T00:40:40Z","status":"completed","updatedAt":"2026-11-15T00:59:44Z","url":"https://x/runs/43","workflowName":"ci"}] +EOF +;; +"run view") [ "$3" = 43 ] && [ "$4" = --json ] || exit 9; cat <<'EOF' +{"jobs":[{"completedAt":"2026-11-15T00:41:14Z","conclusion":"success","databaseId":1,"name":"build","startedAt":"2026-11-15T00:40:38Z","status":"completed","url":"u"}]} +EOF +;; +"run rerun") [ "$3" = 43 ] && [ "$4" = --failed ] || exit 9 ;; +*) exit 7 ;; +esac +`) + ctx := context.Background() + runs, err := Runs(ctx, t.TempDir(), 50) + if err != nil || len(runs) != 1 { + t.Fatalf("runs %+v %v", runs, err) + } + r := runs[0] + if r.ID != 43 || r.Workflow != "ci" || r.Branch != "feat" || r.Sha != "abc" || r.Attempt != 2 || r.Updated.Sub(r.Started) != 19*time.Minute+4*time.Second { + t.Errorf("run %+v", r) + } + jobs, err := RunJobs(ctx, t.TempDir(), 43) + if err != nil || len(jobs) != 1 || jobs[0].Name != "build" || jobs[0].Completed.Sub(jobs[0].Started) != 36*time.Second { + t.Errorf("jobs %+v %v", jobs, err) + } + if err := Rerun(ctx, t.TempDir(), 43); err != nil { + t.Errorf("rerun: %v", err) + } + if err := Rerun(ctx, t.TempDir(), 44); err == nil { + t.Error("a rerun gh refused said nothing") + } +} + +func TestRunsFailures(t *testing.T) { + fakeGH(t, `printf 'oops'`) + if _, err := Runs(context.Background(), t.TempDir(), 10); err == nil || !strings.Contains(err.Error(), "gh run list") { + t.Errorf("bad JSON: %v", err) + } + if _, err := RunJobs(context.Background(), t.TempDir(), 1); err == nil { + t.Error("bad jobs JSON said nothing") + } + t.Setenv("CONCH_GH", "/nonexistent/gh") + if _, err := Runs(context.Background(), t.TempDir(), 10); !errors.Is(err, ErrNoGH) { + t.Errorf("no gh: %v", err) + } +} + +// The newest failed run on a branch, for a re-run asked by branch. +func TestFailedRunOnBranch(t *testing.T) { + runsGH(t, runsJSON) + id, err := FailedRunID(context.Background(), t.TempDir(), "feat", "new") + if err != nil || id != 20 { + t.Fatalf("got %d %v", id, err) + } + if _, err := FailedRunID(context.Background(), t.TempDir(), "feat", "newer"); !errors.Is(err, ErrNoFailedRun) { + t.Errorf("nothing failed there: %v", err) + } +} diff --git a/internal/ghx/runs.go b/internal/ghx/runs.go index 46424ab8..f0bf56ef 100644 --- a/internal/ghx/runs.go +++ b/internal/ghx/runs.go @@ -27,10 +27,26 @@ var ErrNoFailedRun = errors.New("no failed GitHub Actions run on this branch") // repository at dir β€” at commit head when given, so a run about older work // is not mistaken for this one β€” and fetches its failed steps' log. func FailedLog(ctx context.Context, dir, branch, head string) (FailedRun, error) { + runs, err := failedRuns(ctx, dir, branch, head) + if err != nil { + return FailedRun{}, err + } + r := runs[0] + log, err := run(ctx, dir, "run", "view", strconv.FormatInt(r.ID, 10), "--log-failed") + if err != nil { + return FailedRun{}, err + } + return FailedRun{ID: r.ID, Workflow: r.Workflow, URL: r.URL, Log: string(log)}, nil +} + +// failedRuns are the failed Actions runs on branch, newest first β€” at +// commit head when given, so a run about older work is not taken for this +// one β€” or ErrNoFailedRun. +func failedRuns(ctx context.Context, dir, branch, head string) ([]Run, error) { out, err := run(ctx, dir, "run", "list", "--branch", branch, "--limit", "20", "--json", "databaseId,workflowName,url,headSha,conclusion") if err != nil { - return FailedRun{}, err + return nil, err } var runs []struct { ID int64 `json:"databaseId"` @@ -40,8 +56,9 @@ func FailedLog(ctx context.Context, dir, branch, head string) (FailedRun, error) Conclusion string `json:"conclusion"` } if err := json.Unmarshal(out, &runs); err != nil { - return FailedRun{}, fmt.Errorf("gh run list: %w", err) + return nil, fmt.Errorf("gh run list: %w", err) } + var found []Run for _, r := range runs { if !strings.EqualFold(r.Conclusion, "failure") && !strings.EqualFold(r.Conclusion, "timed_out") { continue @@ -49,11 +66,10 @@ func FailedLog(ctx context.Context, dir, branch, head string) (FailedRun, error) if head != "" && r.HeadSha != "" && r.HeadSha != head { continue } - log, err := run(ctx, dir, "run", "view", strconv.FormatInt(r.ID, 10), "--log-failed") - if err != nil { - return FailedRun{}, err - } - return FailedRun{ID: r.ID, Workflow: r.Workflow, URL: r.URL, Log: string(log)}, nil + found = append(found, Run{ID: r.ID, Workflow: r.Workflow, URL: r.URL, Sha: r.HeadSha, Conclusion: r.Conclusion, Branch: branch}) + } + if len(found) == 0 { + return nil, ErrNoFailedRun } - return FailedRun{}, ErrNoFailedRun + return found, nil } diff --git a/internal/gitx/git3_test.go b/internal/gitx/git3_test.go new file mode 100644 index 00000000..65d9bbdf --- /dev/null +++ b/internal/gitx/git3_test.go @@ -0,0 +1,238 @@ +package gitx + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// Git 3.0 makes a new repository SHA-256 with reftable refs on a branch +// called main (Documentation/BreakingChanges). Existing repositories keep +// what they have, so conch meets both kinds for years, side by side. +// These tests make the new kind with today's git and run conch against it. + +// git3 says whether this git can make a Git 3 repository: reftable came +// in 2.45. +func git3(t *testing.T) { + t.Helper() + dir := t.TempDir() + out, err := exec.Command("git", "init", "-q", "--object-format=sha256", "--ref-format=reftable", dir).CombinedOutput() + if err != nil { + t.Skipf("this git cannot make a SHA-256 reftable repository: %v\n%s", err, out) + } +} + +// newGit3Repo is newRepo the way git 3 makes one. +func newGit3Repo(t *testing.T) string { + t.Helper() + git3(t) + dir := filepath.Join(t.TempDir(), "repo") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + dir = resolve(dir) + git(t, dir, "init", "-q", "--object-format=sha256", "--ref-format=reftable", "-b", "main") + configure(t, dir) + commit(t, dir, "README.md", "hello\n", "initial") + return dir +} + +// A reftable repository keeps no refs/heads files: every ref lives in +// reftable/, HEAD included, so a stamp that read only the files backend +// never moved there and a branch on screen went stale. +func TestMetaStampReftable(t *testing.T) { + root := newGit3Repo(t) + common := filepath.Join(root, ".git") + s1 := MetaStamp(common) + if s := MetaStamp(common); s != s1 { + t.Fatal("unstable stamp") + } + git(t, root, "branch", "other") + s2 := MetaStamp(common) + if s2 == s1 { + t.Error("stamp unchanged after a branch was made") + } + git(t, root, "update-ref", "refs/heads/other", "HEAD") // same value: still a write + git(t, root, "branch", "-D", "other") + s3 := MetaStamp(common) + if s3 == s2 { + t.Error("stamp unchanged after a branch was deleted") + } + git(t, root, "checkout", "-q", "-b", "side") + if s := MetaStamp(common); s == s3 { + t.Error("stamp unchanged after checkout") + } + + // A linked worktree keeps its own HEAD in its own reftable. + wt := filepath.Join(filepath.Dir(root), "linked") + git(t, root, "worktree", "add", "-q", "-b", "feat", wt) + s4 := MetaStamp(common) + configure(t, wt) + commit(t, wt, "f.txt", "f\n", "on feat") + git(t, wt, "checkout", "-q", "--detach") + if s := MetaStamp(common); s == s4 { + t.Error("stamp unchanged after a linked worktree moved HEAD") + } +} + +// What the graph, the branch list and the changes view read works the +// same on 64-character hashes and reftable refs. +func TestGit3Repository(t *testing.T) { + root := newGit3Repo(t) + head := git(t, root, "rev-parse", "HEAD") + if len(head) != 64 { + t.Fatalf("not a SHA-256 repository: %q", head) + } + r, err := Discover(ctx, root) + if err != nil || r.Root != root { + t.Fatalf("Discover = %+v, %v", r, err) + } + if b := DefaultBase(ctx, root); b != "main" { + t.Errorf("DefaultBase = %q", b) + } + wt := filepath.Join(filepath.Dir(root), "wt") + if err := AddWorktree(ctx, root, wt, "feat", "main"); err != nil { + t.Fatal(err) + } + configure(t, wt) + commit(t, wt, "a.txt", "a\n", "add a") + write(t, wt, "a.txt", "a\nb\n") + + commits, more, err := Log(ctx, root, 10) + if err != nil || more || len(commits) != 2 { + t.Fatalf("Log = %d commits, more %v, %v", len(commits), more, err) + } + for _, c := range commits { + if len(c.Hash) != 64 { + t.Errorf("hash %q", c.Hash) + } + for _, p := range c.Parents { + if len(p) != 64 { + t.Errorf("parent %q", p) + } + } + } + if commits[0].Parents[0] != head { + t.Errorf("feat's parent %q, want %q", commits[0].Parents[0], head) + } + + bs, err := Branches(ctx, root, "main") + if err != nil { + t.Fatal(err) + } + var feat *Branch + for i := range bs { + if bs[i].Name == "feat" { + feat = &bs[i] + } + } + if feat == nil || feat.BaseAhead != 1 { + t.Errorf("Branches = %+v", bs) + } + wts, err := Worktrees(ctx, root) + if err != nil || len(wts) != 2 { + t.Fatalf("Worktrees = %+v, %v", wts, err) + } + ch, err := WorktreeChanges(ctx, wt, "main") + if err != nil || len(ch.Files) == 0 { + t.Fatalf("WorktreeChanges = %+v, %v", ch, err) + } + d, err := ShowCommit(ctx, root, "feat") + if err != nil || len(d.Hash) != 64 { + t.Fatalf("ShowCommit = %+v, %v", d, err) + } + if Ahead(ctx, root, "feat", "main") != 1 || !Merged(ctx, root, "main", "feat") { + t.Error("ahead/merged wrong on SHA-256") + } + if c := CommitOf(ctx, root, "feat"); len(c) != 64 { + t.Errorf("CommitOf = %q", c) + } + if f := Format(ctx, root); f.Objects != "sha256" || f.Refs != "reftable" { + t.Errorf("Format = %+v", f) + } + if f := Format(ctx, newRepo(t)); f.Objects != "sha1" || f.Refs != "files" { + t.Errorf("Format of a git 2 repository = %+v", f) + } + if f := Format(ctx, t.TempDir()); f != (RepoFormat{}) { + t.Errorf("Format outside a repository = %+v", f) + } + if !isHash(head) { + t.Error("isHash refuses a SHA-256 hash") + } + if got, _ := HaveCommits(ctx, root, []string{head}); len(got) != 1 { + t.Errorf("HaveCommits = %v", got) + } +} + +// A bundle carries its repository's hash. The repository made to take it +// has to be made with the same one, whatever git would make by default β€” +// SHA-1 now, SHA-256 under git 3 β€” or the fetch is refused. +func TestInitFromBundleKeepsObjectFormat(t *testing.T) { + git3(t) + for _, c := range []struct{ src, dflt string }{ + {"sha256", "sha1"}, // a git 3 repository moved to a machine with git 2 + {"sha1", "sha256"}, // an old repository moved to a machine with git 3 + } { + t.Run(c.src+"-into-"+c.dflt, func(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "src") + bundleGit(t, dir, "init", "-q", "--object-format="+c.src, "-b", "main", src) + os.WriteFile(filepath.Join(src, "a.txt"), []byte("a\n"), 0o644) + bundleGit(t, src, "add", "a.txt") + bundleGit(t, src, "commit", "-q", "-m", "one") + file := filepath.Join(dir, "all.bundle") + if err := BundleAll(ctx, src, file); err != nil { + t.Fatal(err) + } + t.Setenv("GIT_DEFAULT_HASH", c.dflt) + dst := filepath.Join(dir, "dst") + if err := InitFromBundle(ctx, file, dst, "main"); err != nil { + t.Fatal(err) + } + if got := bundleGit(t, dst, "rev-parse", "--show-object-format"); got != c.src { + t.Errorf("made a %s repository from a %s bundle", got, c.src) + } + if a, b := bundleGit(t, src, "rev-parse", "HEAD"), bundleGit(t, dst, "rev-parse", "HEAD"); a != b { + t.Errorf("HEAD %s, want %s", b, a) + } + }) + } +} + +func TestBundleObjectFormat(t *testing.T) { + dir := t.TempDir() + for name, c := range map[string]struct{ body, want string }{ + "v2": {"# v2 git bundle\nabc refs/heads/main\n\nPACK", "sha1"}, + "v3 sha256": {"# v3 git bundle\n@object-format=sha256\n@filter=blob:none\nabc refs/heads/main\n\nPACK", "sha256"}, + "v3 no cap": {"# v3 git bundle\nabc refs/heads/main\n\nPACK", "sha1"}, + "empty": {"", "sha1"}, + } { + p := filepath.Join(dir, strings.ReplaceAll(name, " ", "-")) + os.WriteFile(p, []byte(c.body), 0o644) + if got := bundleObjectFormat(p); got != c.want { + t.Errorf("%s: %q, want %q", name, got, c.want) + } + } + if got := bundleObjectFormat(filepath.Join(dir, "missing")); got != "sha1" { + t.Errorf("missing: %q", got) + } +} + +// A git older than 2.45 does not know --show-ref-format, and rev-parse +// prints an option it does not know back as if it were an argument, +// exiting 0 (Apple's git 2.39 does): that is no refs backend. +func TestRefsAnswer(t *testing.T) { + for in, want := range map[string]string{ + "reftable\n": "reftable", + "files\n": "files", + "--show-ref-format\n": "", + "": "", + " \n": "", + } { + if got := refsAnswer(in); got != want { + t.Errorf("refsAnswer(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/gitx/harvest.go b/internal/gitx/harvest.go index adda7fdb..b0d72e77 100644 --- a/internal/gitx/harvest.go +++ b/internal/gitx/harvest.go @@ -430,6 +430,10 @@ func undoMerge(dir string, squash bool) { _, _ = run(ctx, dir, "reset", "--quiet", "--merge") } +// ConflictFiles are the files a merge or rebase stopped on in the +// checkout at dir: those git lists as unmerged. +func ConflictFiles(ctx context.Context, dir string) []string { return conflictFiles(ctx, dir) } + func conflictFiles(ctx context.Context, dir string) []string { out, err := run(ctx, dir, "diff", "--name-only", "--diff-filter=U", "-z") if err != nil { diff --git a/internal/gitx/log.go b/internal/gitx/log.go index d7f28237..8968b5b7 100644 --- a/internal/gitx/log.go +++ b/internal/gitx/log.go @@ -100,3 +100,38 @@ func Remotes(ctx context.Context, dir string) []string { } return strings.Fields(string(out)) } + +// RepoFormat is how a repository stores itself: its object hash (sha1, or +// sha256 as git 3 makes new repositories) and its refs backend (files, or +// reftable). Both are "" outside a repository. +type RepoFormat struct { + Objects string + Refs string +} + +// Format reads dir's repository format. A git older than 2.45 cannot say +// its refs backend, and cannot open a reftable repository either, so the +// refs of one it can read are files. +func Format(ctx context.Context, dir string) RepoFormat { + out, err := run(ctx, dir, "rev-parse", "--show-object-format") + if err != nil { + return RepoFormat{} + } + f := RepoFormat{Objects: strings.TrimSpace(string(out)), Refs: "files"} + if out, err := run(ctx, dir, "rev-parse", "--show-ref-format"); err == nil { + if r := refsAnswer(string(out)); r != "" { + f.Refs = r + } + } + return f +} + +// refsAnswer is rev-parse --show-ref-format's answer, or "" for none: a +// git that does not know the option prints it back, and exits 0. +func refsAnswer(out string) string { + r := strings.TrimSpace(out) + if strings.HasPrefix(r, "-") { + return "" + } + return r +} diff --git a/internal/gitx/move.go b/internal/gitx/move.go index 35c08f15..b17466ae 100644 --- a/internal/gitx/move.go +++ b/internal/gitx/move.go @@ -1,6 +1,7 @@ package gitx import ( + "bufio" "context" "errors" "fmt" @@ -228,6 +229,29 @@ func BundleAll(ctx context.Context, root, file string) error { return err } +// bundleObjectFormat is the hash a bundle's objects are named by. A v3 +// bundle says so in an @object-format line of its header; one that does +// not, and every v2 bundle, is SHA-1. The header ends at its first empty +// line, before the pack. +func bundleObjectFormat(file string) string { + f, err := os.Open(file) + if err != nil { + return "sha1" + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + line := sc.Text() + if line == "" { + break + } + if v, ok := strings.CutPrefix(line, "@object-format="); ok && v != "" { + return v + } + } + return "sha1" +} + // InitFromBundle makes dir, which must not exist yet or be empty, a new // repository holding every branch and tag of bundle, with branch checked // out β€” or, when it has no such branch, its first. It has no remote: a @@ -236,7 +260,10 @@ func InitFromBundle(ctx context.Context, bundle, dir, branch string) error { if err := os.MkdirAll(dir, 0o755); err != nil { return err } - if _, err := run(ctx, dir, "init", "-q"); err != nil { + // The new repository takes the bundle's hash, not this git's default: + // SHA-1 objects cannot be fetched into a SHA-256 repository, and git 3 + // makes SHA-256 ones. + if _, err := run(ctx, dir, "init", "-q", "--object-format="+bundleObjectFormat(bundle)); err != nil { return err } if _, err := run(ctx, dir, "bundle", "verify", "-q", bundle); err != nil { diff --git a/internal/gitx/rebased.go b/internal/gitx/rebased.go new file mode 100644 index 00000000..44ea4589 --- /dev/null +++ b/internal/gitx/rebased.go @@ -0,0 +1,168 @@ +package gitx + +import ( + "context" + "fmt" + "regexp" + "strconv" + "strings" + "time" +) + +// A branch just rebased β€” by an agent asked to resolve a conflict, or by +// anybody β€” is a rewrite nobody has looked at yet: its commits are new +// ones, and the remote still has the old. What follows reads that rewrite +// back from the branch's reflog, so the person can see what the +// resolution changed, push it over the old one, or put the branch back. + +// Rebase is a branch's newest rebase: its tip before and after, and the +// commit it was put on. +type Rebase struct { + Branch string + Before, After string + Onto string + At time.Time +} + +// finished is the reflog's word for a rebase that ended: "rebase +// (finish): refs/heads/x onto ", "rebase -i (finish): …", and the +// "rebase finished: …" of older gits. +var finished = regexp.MustCompile(`^rebase\b.*\bfinish(?:ed)?\)?: refs/heads/(.+) onto ([0-9a-f]+)$`) + +// LastRebase is branch's rebase when that is the newest thing done to it, +// or nil: a commit, reset or push since and it is no longer news. +func LastRebase(ctx context.Context, dir, branch string) (*Rebase, error) { + ref := "refs/heads/" + branch + if CommitOf(ctx, dir, ref) == "" { + return nil, nil + } + out, err := run(ctx, dir, "reflog", "show", "--date=unix", "--format=%H%x00%gd%x00%gs", "-n", "2", ref, "--") + if err != nil { + return nil, nil // a branch without a reflog has no rebase to show + } + lines := strings.Split(strings.TrimSpace(string(out)), "\n") + if len(lines) < 2 { + return nil, nil + } + newest := strings.SplitN(lines[0], "\x00", 3) + prior := strings.SplitN(lines[1], "\x00", 3) + if len(newest) < 3 || len(prior) < 1 { + return nil, nil + } + m := finished.FindStringSubmatch(newest[2]) + if m == nil || m[1] != branch { + return nil, nil + } + r := &Rebase{Branch: branch, Before: prior[0], After: newest[0], Onto: m[2]} + // refs/heads/x@{1731600000} + if i := strings.LastIndex(newest[1], "@{"); i >= 0 { + if s, err := strconv.ParseInt(strings.TrimSuffix(newest[1][i+2:], "}"), 10, 64); err == nil { + r.At = time.Unix(s, 0) + } + } + if r.Before == r.After { + return nil, nil // already on top: nothing was rewritten + } + return r, nil +} + +// How a commit came through a rebase. +const ( + RewriteSame = "same" // the same change on a new parent + RewriteChanged = "changed" // its change is different: a conflict was resolved in it + RewriteDropped = "dropped" // gone: the base had it already, or it was left out + RewriteAdded = "added" // new in the rewrite +) + +// Rewrite is one commit before and after the rebase, by short hash. +type Rewrite struct { + Old, New string + Subject string + Change string +} + +// rangeLine is a header of git range-diff: "1: abc1234 ! 1: def5678 subject". +var rangeLine = regexp.MustCompile(`^\s*(?:\d+|-):\s+([0-9a-f]+|-+)\s+([<>=!])\s+(?:\d+|-):\s+([0-9a-f]+|-+)\s+(.*)$`) + +// Rewritten pairs the branch's commits before the rebase with those +// after, oldest first, saying of each whether its change is what it was. +// A commit whose conflict was resolved is the one that changed. +func Rewritten(ctx context.Context, dir string, r *Rebase) ([]Rewrite, error) { + // The old commits are those Before has and the base it was put on + // does not (the symmetric range's left side, as range-diff reads it). + mb, err := run(ctx, dir, "merge-base", r.Onto, r.Before) + if err != nil { + return nil, fmt.Errorf("%s and %s share no history", short(r.Onto), short(r.Before)) + } + out, err := run(ctx, dir, "range-diff", "--no-color", "--creation-factor=100", "-s", + strings.TrimSpace(string(mb))+".."+r.Before, r.Onto+".."+r.After) + if err != nil { + return nil, err + } + var cs []Rewrite + for _, l := range strings.Split(string(out), "\n") { + m := rangeLine.FindStringSubmatch(l) + if m == nil { + continue + } + c := Rewrite{Subject: m[4]} + if !strings.HasPrefix(m[1], "-") { + c.Old = m[1] + } + if !strings.HasPrefix(m[3], "-") { + c.New = m[3] + } + c.Change = map[string]string{"=": RewriteSame, "!": RewriteChanged, "<": RewriteDropped, ">": RewriteAdded}[m[2]] + cs = append(cs, c) + } + return cs, nil +} + +// cutNote ends a diff cut short. +const cutNote = "\n… (cut short)\n" + +// RewriteDiff is git range-diff's account of the rebase: for each commit +// that changed, the diff of its diff β€” what resolving the conflict did. +// Longer than max (when max > 0) and it is cut there. +func RewriteDiff(ctx context.Context, dir string, r *Rebase, max int) (string, error) { + mb, err := run(ctx, dir, "merge-base", r.Onto, r.Before) + if err != nil { + return "", fmt.Errorf("%s and %s share no history", short(r.Onto), short(r.Before)) + } + out, err := run(ctx, dir, "range-diff", "--no-color", "--creation-factor=100", + strings.TrimSpace(string(mb))+".."+r.Before, r.Onto+".."+r.After) + if err != nil { + return "", err + } + s := string(out) + if max > 0 && len(s) > max { + s = s[:max] + cutNote + } + return s, nil +} + +// UndoRebase puts branch back at before, in dir where it is checked out, +// if it is still at after and has nothing uncommitted: the rewrite stays +// in the reflog, so this too can be undone. +func UndoRebase(ctx context.Context, dir, branch, before, after string) error { + if err := readyToRebase(ctx, dir, branch); err != nil { + return err + } + if head, _ := revParse(ctx, dir, "HEAD"); head != after { + return fmt.Errorf("%s has moved on since the rebase (it is at %s now), so it is not undone", branch, short(head)) + } + if CommitOf(ctx, dir, before) == "" { + return fmt.Errorf("%s, where %s was before the rebase, is not in this repository", short(before), branch) + } + if _, err := run(ctx, dir, "reset", "--keep", "--quiet", before); err != nil { + return err + } + return nil +} + +func short(h string) string { + if len(h) > 8 { + return h[:8] + } + return h +} diff --git a/internal/gitx/rebased_test.go b/internal/gitx/rebased_test.go new file mode 100644 index 00000000..31b11ba4 --- /dev/null +++ b/internal/gitx/rebased_test.go @@ -0,0 +1,144 @@ +package gitx + +import ( + "os" + "os/exec" + "strings" + "testing" +) + +// rebasedRepo is a feat branch, pushed, rebased onto a main that changed +// the same line, with the conflict resolved by hand β€” what an agent asked +// to resolve leaves behind. It returns the tips before and after. +func rebasedRepo(t *testing.T) (root, wt, origin, before, after string) { + t.Helper() + root, wt, origin = ontoRepo(t) + commit(t, wt, "shared.txt", "feat's line\n", "feat edits shared") + commit(t, wt, "own.txt", "own\n", "feat's own file") + if err := Push(ctx, wt, "feat"); err != nil { + t.Fatal(err) + } + pushMain(t, origin, "shared.txt", "main's line\n") + git(t, wt, "fetch", "-q", "origin") + before = git(t, wt, "rev-parse", "HEAD") + cmd := exec.Command("git", "-C", wt, "rebase", "origin/main") + if out, err := cmd.CombinedOutput(); err == nil { + t.Fatalf("expected a conflict:\n%s", out) + } + write(t, wt, "shared.txt", "main's line\nfeat's line\n") + git(t, wt, "add", "shared.txt") + cmd = exec.Command("git", "-C", wt, "rebase", "--continue") + cmd.Env = append(os.Environ(), "GIT_EDITOR=true") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("continue: %v\n%s", err, out) + } + return root, wt, origin, before, git(t, wt, "rev-parse", "HEAD") +} + +func TestLastRebase(t *testing.T) { + _, wt, _, before, after := rebasedRepo(t) + r, err := LastRebase(ctx, wt, "feat") + if err != nil || r == nil { + t.Fatalf("%+v %v", r, err) + } + if r.Before != before || r.After != after || r.Onto != git(t, wt, "rev-parse", "origin/main") { + t.Errorf("tips: %+v (before %s after %s)", r, before, after) + } + if r.At.IsZero() { + t.Error("no time") + } + // A commit after the rebase: it is no longer the newest thing done. + commit(t, wt, "later.txt", "later\n", "later") + if r, err := LastRebase(ctx, wt, "feat"); err != nil || r != nil { + t.Errorf("after a commit: %+v %v", r, err) + } +} + +func TestLastRebaseNone(t *testing.T) { + _, wt := taskRepo(t) + if r, err := LastRebase(ctx, wt, "feat"); err != nil || r != nil { + t.Errorf("never rebased: %+v %v", r, err) + } + commit(t, wt, "a.txt", "a\n", "a") + if r, err := LastRebase(ctx, wt, "feat"); err != nil || r != nil { + t.Errorf("committed: %+v %v", r, err) + } + if r, err := LastRebase(ctx, wt, "nope"); err != nil || r != nil { + t.Errorf("no such branch: %+v %v", r, err) + } +} + +// Each commit before against its rewrite: the one whose conflict was +// resolved changed, the other came across as it was. +func TestRewritten(t *testing.T) { + _, wt, _, before, after := rebasedRepo(t) + r, _ := LastRebase(ctx, wt, "feat") + cs, err := Rewritten(ctx, wt, r) + if err != nil { + t.Fatal(err) + } + if len(cs) != 3 { + t.Fatalf("%+v", cs) + } + byS := map[string]Rewrite{} + for _, c := range cs { + byS[c.Subject] = c + } + if c := byS["feat edits shared"]; c.Change != RewriteChanged || c.Old == "" || c.New == "" || c.Old == c.New { + t.Errorf("resolved: %+v", c) + } + if c := byS["feat's own file"]; c.Change != RewriteSame || !strings.HasPrefix(after, c.New) || !strings.HasPrefix(before, c.Old) { + t.Errorf("unchanged: %+v", c) + } + if c := byS["feat"]; c.Change != RewriteSame { + t.Errorf("first: %+v", c) + } + // Oldest first, as the branch has them. + if cs[2].Subject != "feat's own file" { + t.Errorf("order: %+v", cs) + } + patch, err := RewriteDiff(ctx, wt, r, 0) + if err != nil || !strings.Contains(patch, "feat edits shared") || !strings.Contains(patch, "main's line") { + t.Errorf("diff %v:\n%s", err, patch) + } + if short, _ := RewriteDiff(ctx, wt, r, 40); len(short) > 40+len(cutNote) { + t.Errorf("cut: %d", len(short)) + } +} + +// Undo puts the branch back where it was, keeping the rewrite in the +// reflog; refused once the branch moved on or with changes not committed. +func TestUndoRebase(t *testing.T) { + _, wt, _, before, after := rebasedRepo(t) + write(t, wt, "own.txt", "edited\n") + if err := UndoRebase(ctx, wt, "feat", before, after); err == nil || !strings.Contains(err.Error(), "uncommitted") { + t.Fatalf("dirty: %v", err) + } + git(t, wt, "checkout", "--", "own.txt") + if err := UndoRebase(ctx, wt, "feat", before, "0123456789012345678901234567890123456789"); err == nil { + t.Fatal("moved on") + } + if err := UndoRebase(ctx, wt, "feat", before, after); err != nil { + t.Fatal(err) + } + if got := git(t, wt, "rev-parse", "HEAD"); got != before { + t.Fatalf("head %s, want %s", got, before) + } + if r, _ := LastRebase(ctx, wt, "feat"); r != nil { + t.Errorf("still says rebased: %+v", r) + } +} + +// The rebased branch replaces the pushed one, which the remote still has. +func TestRebasedPushOver(t *testing.T) { + _, wt, origin, before, after := rebasedRepo(t) + if got := PushedHead(ctx, wt, "feat"); got != before { + t.Fatalf("pushed %s", got) + } + if err := PushOver(ctx, wt, "feat", before); err != nil { + t.Fatal(err) + } + if got := git(t, origin, "rev-parse", "feat"); got != after { + t.Errorf("origin has %s", got) + } +} diff --git a/internal/gitx/stamp.go b/internal/gitx/stamp.go index 25a2137e..1cc1ba64 100644 --- a/internal/gitx/stamp.go +++ b/internal/gitx/stamp.go @@ -11,6 +11,9 @@ import ( // MetaStamp is a cheap fingerprint of a repository's git metadata, computed // from file mtimes and sizes without running git. It changes when refs, HEAD, // the index or worktrees change, so callers can skip refreshes otherwise. +// It reads both ref backends: the files one (refs/heads, packed-refs) and +// reftable, git 3's default, where every ref β€” HEAD too β€” is in +// reftable/ and the files above never move. func MetaStamp(commonDir string) string { h := fnv.New64a() add := func(path string) { @@ -20,9 +23,17 @@ func MetaStamp(commonDir string) string { } fmt.Fprintf(h, "%s\x00%d\x00%d\x00", path, info.Size(), info.ModTime().UnixNano()) } + // Every reftable write adds a table and rewrites tables.list with its + // name, so the list's text moves even when its size and mtime might not. + list := func(dir string) { + if b, err := os.ReadFile(filepath.Join(dir, "reftable", "tables.list")); err == nil { + fmt.Fprintf(h, "%s\x00%s\x00", dir, b) + } + } for _, name := range []string{"HEAD", "index", "packed-refs", "FETCH_HEAD"} { add(filepath.Join(commonDir, name)) } + list(commonDir) // A deleted branch only shows as a missing path, which the hash of // present paths captures. filepath.WalkDir(filepath.Join(commonDir, "refs", "heads"), func(p string, d fs.DirEntry, err error) error { @@ -35,6 +46,7 @@ func MetaStamp(commonDir string) string { for _, wt := range wts { add(filepath.Join(wt, "HEAD")) add(filepath.Join(wt, "index")) + list(wt) } return fmt.Sprintf("%016x", h.Sum64()) } diff --git a/internal/proto/autopilot.go b/internal/proto/autopilot.go index 1872575d..5519db44 100644 --- a/internal/proto/autopilot.go +++ b/internal/proto/autopilot.go @@ -3,6 +3,7 @@ package proto import ( "fmt" "strings" + "time" "github.com/charmbracelet/x/ansi" ) @@ -105,6 +106,34 @@ type AutopilotNote struct { Text string `json:"text"` Error bool `json:"error,omitempty"` Merged bool `json:"merged,omitempty"` + // Kind is what the autopilot was doing (an Activity… word) and At + // when; both absent from an older server. + Kind string `json:"kind,omitempty"` + At time.Time `json:"at,omitempty"` +} + +// What a note is about, for the activity feed to group and mark. +const ( + ActivityCI = "ci" // a failed CI run sent to the agent, or not + ActivityCheck = "check" // the project's own check + ActivityShip = "ship" // pushed, a pull request opened or marked ready + ActivityMerge = "merge" // merged, or held back from merging + ActivityResolve = "resolve" // a conflict with the base rebased or sent to the agent + ActivityIntake = "intake" // an issue taken as a task + ActivityTriage = "triage" // an issue read and labelled +) + +// AutopilotActivityParams asks for what the autopilot did, newest first: +// in one project, or everywhere when ProjectID is empty; Limit at most +// (100 when 0). +type AutopilotActivityParams struct { + ProjectID string `json:"project_id,omitempty"` + Limit int `json:"limit,omitempty"` +} + +// AutopilotActivity is the autopilot's notes, newest first. +type AutopilotActivity struct { + Notes []AutopilotNote `json:"notes"` } // A failure sent to an agent is bounded: enough of the end of the output diff --git a/internal/proto/proto.go b/internal/proto/proto.go index bdaffd4e..bd15fb66 100644 --- a/internal/proto/proto.go +++ b/internal/proto/proto.go @@ -35,7 +35,7 @@ const ProtocolVersion = 1 var Capabilities = []string{ "pane.v1", "pane.frame.v1", "events.v1", "agent.v1", "project.v1", "pane.scroll.v1", "project.pr.v1", "pane.default_shell.v1", - "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapBranchPrune, CapBranchPruneMerged, CapPaneTeam, CapWorktreeOperation, + "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapBranchPrune, CapBranchPruneMerged, CapPaneTeam, CapWorktreeOperation, CapCIStats, CapCIRerun, CapAutopilotActivity, CapBranchRebased, CapBranchResolving, } // The tiers an agent can be in, as agent.list reports them. They are in @@ -225,6 +225,31 @@ const CapWorktreeSetup = "worktree.setup.v1" // read through gh on the machine the branch is on, for handing to its agent. const CapBranchCILog = "branch.ci_log.v1" +// CapAutopilotActivity is autopilot.activity: what the autopilot did, +// kept by the server across restarts, and each note's kind and time. +const CapAutopilotActivity = "autopilot.activity.v1" + +// CapCIStats is ci.stats: a project's GitHub Actions history over a +// period of days, added up for the CI panel β€” pass rate, run and queue +// times, runs per day, each job's time, flaky jobs, failures to re-run. +const CapCIStats = "ci.stats.v1" + +// CapCIRerun is ci.rerun: a failed run's failed jobs run again, through +// gh on the machine the project is on. +const CapCIRerun = "ci.rerun.v1" + +// CapBranchRebased is branch.rebased and branch.rebase_undo: a branch's +// newest rebase read back β€” each commit before and after, and what +// resolving its conflicts changed β€” then pushed over the old branch with +// a lease (BranchPushParams.Over) or undone. +const CapBranchRebased = "branch.rebased.v1" + +// CapBranchResolving is branch.resolving and WorktreeInfo.Resolve: which +// agent was asked to resolve a branch's conflict with the base β€” by the +// person or the autopilot β€” kept while the conflict is there, so a client +// can say the agent is at it rather than that the branch is stuck. +const CapBranchResolving = "branch.resolving.v1" + // CapAgentReply is agent.reply: an agent's last answer, whole, from its // saved conversation rather than off its screen. const CapAgentReply = "agent.reply.v1" @@ -643,6 +668,20 @@ const ( // MethodBranchCILog is the log of the failed steps of a branch's // newest failed GitHub Actions run (CapBranchCILog). MethodBranchCILog = "branch.ci_log" + // MethodCIStats adds up a project's GitHub Actions runs (CapCIStats). + // MethodAutopilotActivity lists what the autopilot did + // (CapAutopilotActivity). + MethodAutopilotActivity = "autopilot.activity" + MethodCIStats = "ci.stats" + // MethodCIRerun runs a failed run's failed jobs again (CapCIRerun). + MethodCIRerun = "ci.rerun" + // MethodBranchRebased reads back the agents' branches' newest + // rebases, and MethodBranchRebaseUndo puts one back (CapBranchRebased). + MethodBranchRebased = "branch.rebased" + MethodBranchRebaseUndo = "branch.rebase_undo" + // MethodBranchResolving says which agent was asked to resolve a + // branch's conflict, or that nobody is any more (CapBranchResolving). + MethodBranchResolving = "branch.resolving" // Leftover worktrees: list what each would lose, and remove them. MethodWorktreeStale = "worktree.stale" MethodWorktreeCleanup = "worktree.cleanup" @@ -995,7 +1034,8 @@ type WorktreeInfo struct { // Overlaps are the other checkouts of the project that have touched // files this one has too: two agents heading for the same merge // conflict. Conflicts are the files merging this branch into the base - // would conflict in, tried without merging. Both are absent from older + // would conflict in, tried without merging β€” or, in a checkout stopped + // mid-rebase or merge, the files it stopped on. Both are absent from older // servers, and Conflicts where git is older than 2.38. Overlaps []Overlap `json:"overlaps,omitempty"` Conflicts []string `json:"conflicts,omitempty"` @@ -1005,6 +1045,23 @@ type WorktreeInfo struct { // shows the checkout under that branch. Absent from older servers // (CapWorktreeOperation). Operation string `json:"operation,omitempty"` + // Rebasing is the branch a rebase left unfinished in this checkout is + // rewriting, which Branch also names (CapWorktreeOperation): git + // detaches HEAD while it works. Absent from older servers. + Rebasing string `json:"rebasing,omitempty"` + // Resolve is the agent asked to resolve the branch's conflict with + // the base, while that conflict is there (CapBranchResolving). + Resolve *ResolveAsk `json:"resolve,omitempty"` +} + +// ResolveAsk is an agent asked to resolve a branch's conflict: its pane, +// who asked ("autopilot", or empty for the person), when, and the files +// that conflicted then. +type ResolveAsk struct { + Pane string `json:"pane"` + By string `json:"by,omitempty"` + At time.Time `json:"at"` + Files []string `json:"files,omitempty"` } // Overlap is another branch's checkout touching the same files. @@ -1671,6 +1728,16 @@ type LogResult struct { // remote's branch (fork/main) from a local one with a slash. Absent // from an older server: clients then take origin and upstream. Remotes []string `json:"remotes,omitempty"` + // Format is how the repository stores itself β€” sha1 or sha256 + // objects, files or reftable refs β€” absent from an older server. + Format *RepoFormat `json:"format,omitempty"` +} + +// RepoFormat is a repository's object hash and refs backend: git 3 makes +// new repositories sha256 and reftable, and conch meets both kinds. +type RepoFormat struct { + Objects string `json:"objects,omitempty"` + Refs string `json:"refs,omitempty"` } // CommitParams asks project.commit about Hash: the commit itself; with @@ -1761,10 +1828,73 @@ type BranchRef struct { // of takes the remote's commits first and puts the branch's own on top; // without it such a push comes back as ErrPushRejected. It is a BranchRef // with a field added, so an older server reads it as one. +// +// Over is the commit the remote is expected to have for the branch: the +// push replaces it, and only it (--force-with-lease), which is how a +// rebased branch goes up over the one it rewrote (CapBranchRebased). An +// older server ignores it, and a plain push of a rewrite is rejected. type BranchPushParams struct { ProjectID string `json:"project_id"` Branch string `json:"branch"` Rebase bool `json:"rebase,omitempty"` + Over string `json:"over,omitempty"` +} + +// BranchRebasedParams asks for the newest rebase of each branch checked +// out in the project β€” or of Branch alone β€” that has not been pushed +// yet. Diff adds git range-diff's account of what changed. +type BranchRebasedParams struct { + ProjectID string `json:"project_id"` + Branch string `json:"branch,omitempty"` + Diff bool `json:"diff,omitempty"` +} + +// BranchRebased lists the branches rebased and not pushed since. +type BranchRebased struct { + Rebases []BranchRebase `json:"rebases"` +} + +// BranchRebase is a branch's newest rebase: its tip before and after, +// the commit it went onto, when, and each commit's fate. Remote is the +// commit the remote has for the branch as the checkout last saw it, "" +// when it was never pushed: Before means the push replaces the old +// branch, anything else that somebody pushed since. +type BranchRebase struct { + Branch string `json:"branch"` + Before string `json:"before"` + After string `json:"after"` + Onto string `json:"onto"` + At time.Time `json:"at,omitempty"` + Commits []RebasedCommit `json:"commits,omitempty"` + Remote string `json:"remote,omitempty"` + Diff string `json:"diff,omitempty"` +} + +// RebasedCommit is one commit before (Old) and after (New), short +// hashes; Change is "same", "changed" (a conflict was resolved in it), +// "dropped" or "added". +type RebasedCommit struct { + Old string `json:"old,omitempty"` + New string `json:"new,omitempty"` + Subject string `json:"subject"` + Change string `json:"change"` +} + +// BranchRebaseUndoParams puts Branch back at Before, if it is still at +// After. +type BranchRebaseUndoParams struct { + ProjectID string `json:"project_id"` + Branch string `json:"branch"` + Before string `json:"before"` + After string `json:"after"` +} + +// BranchResolvingParams names the agent (its pane) asked to resolve +// Branch's conflict; an empty PaneID says nobody is any more. +type BranchResolvingParams struct { + ProjectID string `json:"project_id"` + Branch string `json:"branch"` + PaneID string `json:"pane_id,omitempty"` } // BranchPushResult says what a push did: Took counts the commits a rebase @@ -1862,6 +1992,95 @@ type BranchDiscardParams struct { Force bool `json:"force,omitempty"` } +// CIStatsParams asks for a project's CI over the last Days days, today +// included (14 when 0, 90 at most). +type CIStatsParams struct { + ProjectID string `json:"project_id"` + Days int `json:"days,omitempty"` +} + +// CIStats is a project's GitHub Actions over a period of whole days, and +// the same number of days before it for comparison. Seconds are medians. +type CIStats struct { + Days int `json:"days"` + // Finished runs that passed or failed (a cancelled one is neither). + Runs int `json:"runs"` + Passed int `json:"passed"` + Failed int `json:"failed"` + PrevRuns int `json:"prev_runs"` + PrevPassed int `json:"prev_passed"` + // A run's time from start to finish, and its wait in the queue. + MedianSeconds int `json:"median_seconds"` + PrevMedianSeconds int `json:"prev_median_seconds"` + QueueSeconds int `json:"queue_seconds"` + // From a failed run to the next passing run of the same workflow on + // the same branch, and how many times a branch went from red to green. + RedToGreenSeconds int `json:"red_to_green_seconds"` + RedToGreenCount int `json:"red_to_green_count"` + // One a day, oldest first, today last. + Daily []CIDay `json:"daily"` + // Each job, the slowest first. + Jobs []CIJob `json:"jobs,omitempty"` + // Jobs that failed and passed with nothing changed, and runs that + // passed only on a later attempt. + Flaky []CIFlaky `json:"flaky,omitempty"` + // Each workflow's newest run on each branch, where it failed. + Failing []CIRun `json:"failing,omitempty"` + // JobsPending is how many of the period's runs have not had their jobs + // read yet: a few dozen are read per call, so asking again fills in + // the job times. + JobsPending int `json:"jobs_pending,omitempty"` +} + +// CIDay is a day's finished runs; Date is YYYY-MM-DD where the server is. +type CIDay struct { + Date string `json:"date"` + Passed int `json:"passed"` + Failed int `json:"failed"` +} + +// CIJob is one job over the period. +type CIJob struct { + Name string `json:"name"` + Runs int `json:"runs"` + Failed int `json:"failed"` + MedianSeconds int `json:"median_seconds"` + P90Seconds int `json:"p90_seconds"` +} + +// CIFlaky is a job, or a whole run, that failed and passed without a change. +type CIFlaky struct { + Name string `json:"name"` + Times int `json:"times"` + How string `json:"how"` + Last time.Time `json:"last"` +} + +// CIRun is one workflow run. +type CIRun struct { + ID int64 `json:"id"` + Workflow string `json:"workflow"` + Branch string `json:"branch,omitempty"` + Sha string `json:"sha,omitempty"` + Conclusion string `json:"conclusion,omitempty"` + Attempt int `json:"attempt,omitempty"` + URL string `json:"url,omitempty"` + At time.Time `json:"at"` +} + +// CIRerunParams names the run whose failed jobs to run again, or a branch +// whose newest failed run (at its pull request's head) it is. +type CIRerunParams struct { + ProjectID string `json:"project_id"` + RunID int64 `json:"run_id,omitempty"` + Branch string `json:"branch,omitempty"` +} + +// CIRerunResult is the run started again. +type CIRerunResult struct { + RunID int64 `json:"run_id"` +} + // BranchCILogParams names the branch whose failed CI run to read. type BranchCILogParams struct { ProjectID string `json:"project_id"` diff --git a/internal/server/activity.go b/internal/server/activity.go new file mode 100644 index 00000000..f13fde96 --- /dev/null +++ b/internal/server/activity.go @@ -0,0 +1,146 @@ +package server + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "log" + "os" + "path/filepath" + "sync" + "time" + + "github.com/Amitgb14/conch/internal/proto" +) + +// The autopilot's activity: every note it makes, kept so the person can +// see later what it did while nobody was looking β€” which is the point of +// an autopilot. Notes are appended a line each to a file in the config +// directory, so a restart or a reload keeps them, and the file is +// rewritten to the newest activityMax once it is twice that. + +const ( + activityFile = "autopilot-activity.jsonl" + activityMax = 500 + // activityDefault is how many a list gives when not told. + activityDefault = 100 +) + +type activityLog struct { + file string + + mu sync.Mutex + notes []proto.AutopilotNote // oldest first + lines int // lines in the file + // needNL is a file whose last line was cut short: the next line + // written starts a line of its own rather than finishing that one. + needNL bool +} + +func loadActivity(configDir string) *activityLog { + l := &activityLog{file: filepath.Join(configDir, activityFile)} + raw, err := os.ReadFile(l.file) + if err != nil { + if !errors.Is(err, os.ErrNotExist) { + log.Printf("autopilot activity: %v", err) + } + return l + } + l.needNL = len(raw) > 0 && raw[len(raw)-1] != '\n' + sc := bufio.NewScanner(bytes.NewReader(raw)) + sc.Buffer(make([]byte, 64<<10), 1<<20) + for sc.Scan() { + l.lines++ + var n proto.AutopilotNote + if json.Unmarshal(sc.Bytes(), &n) == nil { + l.notes = append(l.notes, n) + } + } + if len(l.notes) > activityMax { + l.notes = l.notes[len(l.notes)-activityMax:] + } + return l +} + +// add keeps a note, stamped now unless it has a time, and returns it. +func (l *activityLog) add(n proto.AutopilotNote) proto.AutopilotNote { + if n.At.IsZero() { + n.At = time.Now() + } + l.mu.Lock() + defer l.mu.Unlock() + l.notes = append(l.notes, n) + if len(l.notes) > activityMax { + l.notes = append([]proto.AutopilotNote(nil), l.notes[len(l.notes)-activityMax:]...) + } + line, err := json.Marshal(n) + if err != nil { + return n + } + if l.lines+1 > 2*activityMax { + l.rewriteLocked() + return n + } + f, err := os.OpenFile(l.file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) + if err != nil { + log.Printf("autopilot activity: %v", err) + return n + } + defer f.Close() + if l.needNL { + line = append([]byte("\n"), line...) + } + if _, err := f.Write(append(line, '\n')); err != nil { + log.Printf("autopilot activity: %v", err) + return n + } + l.needNL = false + l.lines++ + return n +} + +// rewriteLocked writes the notes kept, and only those, through a file +// moved into place, so a crash leaves the old file or the new one. +func (l *activityLog) rewriteLocked() { + var b bytes.Buffer + for _, n := range l.notes { + if line, err := json.Marshal(n); err == nil { + b.Write(line) + b.WriteByte('\n') + } + } + tmp := l.file + ".tmp" + if err := os.WriteFile(tmp, b.Bytes(), 0o600); err != nil { + log.Printf("autopilot activity: %v", err) + return + } + if err := os.Rename(tmp, l.file); err != nil { + log.Printf("autopilot activity: %v", err) + return + } + l.lines, l.needNL = len(l.notes), false +} + +// list is the newest notes first, of one project or of all of them. +func (l *activityLog) list(projectID string, limit int) []proto.AutopilotNote { + switch { + case limit <= 0: + limit = activityDefault + case limit > activityMax: + limit = activityMax + } + l.mu.Lock() + defer l.mu.Unlock() + out := []proto.AutopilotNote{} + for i := len(l.notes) - 1; i >= 0 && len(out) < limit; i-- { + if projectID == "" || l.notes[i].ProjectID == projectID { + out = append(out, l.notes[i]) + } + } + return out +} + +func (s *Server) autopilotActivity(p proto.AutopilotActivityParams) proto.AutopilotActivity { + return proto.AutopilotActivity{Notes: s.autopilot.activity.list(p.ProjectID, p.Limit)} +} diff --git a/internal/server/activity_test.go b/internal/server/activity_test.go new file mode 100644 index 00000000..9d8d0aee --- /dev/null +++ b/internal/server/activity_test.go @@ -0,0 +1,107 @@ +package server + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Amitgb14/conch/internal/proto" +) + +// What the autopilot did is kept, newest first, each with when it was and +// what kind of thing it was; asked for by project, a project gets its own. +func TestActivityKept(t *testing.T) { + dir := t.TempDir() + l := loadActivity(dir) + before := time.Now() + l.add(proto.AutopilotNote{ProjectID: "a", Branch: "x", Kind: proto.ActivityCI, Text: "one"}) + l.add(proto.AutopilotNote{ProjectID: "b", Branch: "y", Kind: proto.ActivityMerge, Text: "two", Merged: true}) + l.add(proto.AutopilotNote{ProjectID: "a", Branch: "z", Kind: proto.ActivityResolve, Text: "three", Error: true}) + got := l.list("a", 0) + if len(got) != 2 || got[0].Text != "three" || got[1].Text != "one" { + t.Fatalf("project a: %+v", got) + } + if got[0].At.Before(before) || got[0].Kind != proto.ActivityResolve || !got[0].Error { + t.Errorf("stamped: %+v", got[0]) + } + if all := l.list("", 0); len(all) != 3 || all[0].Text != "three" { + t.Errorf("every project: %+v", all) + } + if one := l.list("", 1); len(one) != 1 || one[0].Text != "three" { + t.Errorf("limit 1: %+v", one) + } + // A restart keeps it. + again := loadActivity(dir).list("b", 0) + if len(again) != 1 || !again[0].Merged || again[0].Kind != proto.ActivityMerge { + t.Fatalf("after a restart: %+v", again) + } +} + +// The log is bounded in memory and on disk, and the newest stay. +func TestActivityCapped(t *testing.T) { + dir := t.TempDir() + l := loadActivity(dir) + for i := range activityMax*2 + 10 { + l.add(proto.AutopilotNote{ProjectID: "a", Text: fmt.Sprint(i)}) + } + got := l.list("", activityMax+50) + if len(got) != activityMax || got[0].Text != fmt.Sprint(activityMax*2+9) { + t.Fatalf("kept %d, newest %q", len(got), got[0].Text) + } + raw, _ := os.ReadFile(filepath.Join(dir, activityFile)) + if n := strings.Count(string(raw), "\n"); n > activityMax*2 { + t.Errorf("%d lines on disk", n) + } + if again := loadActivity(dir).list("", activityMax); len(again) != activityMax || again[0].Text != got[0].Text { + t.Errorf("reloaded %d, newest %q", len(again), again[0].Text) + } +} + +// A damaged line β€” a write cut short, a hand edit β€” loses that line and +// nothing else; a missing file is an empty log. +func TestActivityDamagedFile(t *testing.T) { + dir := t.TempDir() + if got := loadActivity(dir).list("", 0); len(got) != 0 { + t.Fatalf("no file: %+v", got) + } + good := `{"project_id":"a","branch":"x","text":"kept","at":"2026-11-14T10:00:00Z"}` + os.WriteFile(filepath.Join(dir, activityFile), []byte(good+"\n{\"project_id\":\"a\",\"tex\n"+good+"\n"), 0o600) + l := loadActivity(dir) + if got := l.list("a", 0); len(got) != 2 || got[0].Text != "kept" { + t.Fatalf("damaged: %+v", got) + } + // Writing on after a damaged line starts a line of its own. + l.add(proto.AutopilotNote{ProjectID: "a", Text: "new"}) + if got := loadActivity(dir).list("a", 0); len(got) != 3 || got[0].Text != "new" { + t.Errorf("after writing on: %+v", got) + } +} + +// The autopilot's own notes land in the log with their kind: a pull +// request held, then merged. +func TestActivityFromTheAutopilot(t *testing.T) { + s, p := afterFixture(t) + quietPRs(t, p) + fakeMergeGH(t) + s.autopilot.set(proto.AutopilotPolicy{AutoMerge: true}) + head := apBranch(t, p, "feat") + apPR(s, p, "feat", proto.PRInfo{Number: 5, Checks: "pending", Draft: true, Head: head}) + apPR(s, p, "feat", proto.PRInfo{Number: 5, Checks: "pass", Draft: true, Head: head}) + p.mu.Lock() + pr := p.prs["feat"] + pr.Draft = false + p.prs["feat"] = pr + p.mu.Unlock() + s.autopilotMerges() + a5WaitFor(t, "the merge in the log", func() bool { + got := s.autopilotActivity(proto.AutopilotActivityParams{ProjectID: p.id}).Notes + return len(got) >= 2 && got[0].Merged && got[0].Kind == proto.ActivityMerge && got[0].Branch == "feat" + }) + got := s.autopilotActivity(proto.AutopilotActivityParams{ProjectID: p.id}).Notes + if !strings.Contains(got[1].Text, "draft") || got[1].Kind != proto.ActivityMerge { + t.Errorf("the hold: %+v", got[1]) + } +} diff --git a/internal/server/autopilot.go b/internal/server/autopilot.go index 4660dbd1..00d6e0a8 100644 --- a/internal/server/autopilot.go +++ b/internal/server/autopilot.go @@ -40,6 +40,8 @@ const autopilotTick = 5 * time.Second type autopilot struct { file string + // activity is every note made, kept across restarts. + activity *activityLog mu sync.Mutex saved autopilotFile @@ -158,7 +160,7 @@ func loadAutopilot(configDir string) *autopilot { a := &autopilot{file: filepath.Join(configDir, "autopilot.json"), merging: map[string]bool{}, shipping: map[string]bool{}, unshipped: map[string]string{}, lastCheck: map[string]string{}, resolving: map[string]bool{}, starting: map[string]bool{}, capSaid: map[string]bool{}, recheck: map[string]bool{}, reship: map[string]bool{}, - gateMemo: map[string]gateResult{}, said: map[string]string{}} + gateMemo: map[string]gateResult{}, said: map[string]string{}, activity: loadActivity(configDir)} raw, err := os.ReadFile(a.file) if err != nil && !errors.Is(err, os.ErrNotExist) { log.Printf("autopilot: %v", err) @@ -537,7 +539,7 @@ func (a *autopilot) checked(key, head string, passed bool) { // note tells every client what the autopilot did, and the log. func (s *Server) autopilotNote(n proto.AutopilotNote) { log.Printf("autopilot: %s %s: %s", n.ProjectID, n.Branch, n.Text) - s.broadcast(proto.EventAutopilotNote, n) + s.broadcast(proto.EventAutopilotNote, s.autopilot.activity.add(n)) } // autopilotPrompt is a message from the autopilot to an agent. @@ -656,6 +658,10 @@ func (s *Server) autopilotFix(projectID, branch, what string, text func() (strin if s.autopilot.policy().AutoFix <= 0 { return } + kind := proto.ActivityCheck + if what == "CI" { + kind = proto.ActivityCI + } agent := s.freeAgent(projectID, branch) if agent == nil { if waiting := s.busyAgent(projectID, branch); waiting != nil && what == "CI" { @@ -667,7 +673,7 @@ func (s *Server) autopilotFix(projectID, branch, what string, text func() (strin s.autopilot.saveLocked() s.autopilot.mu.Unlock() if !already { - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: kind, Text: fmt.Sprintf("CI failed on %s; it goes to %s once it is free", branch, waiting.DisplayName())}) } } @@ -676,7 +682,7 @@ func (s *Server) autopilotFix(projectID, branch, what string, text func() (strin ci := what == "CI" ok, capped, limit := s.autopilot.takeFix(key, ci) if capped { - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, Kind: kind, Text: fmt.Sprintf("%s failed on %s again; auto_fix tried %d times, so it's yours now", what, branch, limit)}) } if !ok { @@ -692,11 +698,11 @@ func (s *Server) autopilotFix(projectID, branch, what string, text func() (strin } if err != nil { s.autopilot.giveBack(key, ci) - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, Kind: kind, Text: fmt.Sprintf("%s failed on %s, and could not go to %s: %v", what, branch, agent.DisplayName(), err)}) return } - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: kind, Text: fmt.Sprintf("%s failed on %s: sent it to %s to fix", what, branch, agent.DisplayName())}) }() } @@ -843,7 +849,7 @@ func (s *Server) autopilotMerge(key string) { a.saveLocked() } a.mu.Unlock() - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: proto.ActivityMerge, Text: fmt.Sprintf("%s is green but not merged: %s", branch, why)}) } return @@ -866,11 +872,11 @@ func (s *Server) autopilotMerge(key string) { a.saveLocked() a.mu.Unlock() if perr != nil { - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, Kind: proto.ActivityMerge, Text: fmt.Sprintf("#%d is green but GitHub would not merge it: %s", pr.Number, perr.Message)}) return } - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Merged: true, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Merged: true, Kind: proto.ActivityMerge, Text: fmt.Sprintf("merged #%d on GitHub (%s), green", pr.Number, res.Method)}) }() } diff --git a/internal/server/autopilot_resolve.go b/internal/server/autopilot_resolve.go index 35a050a4..79654ac9 100644 --- a/internal/server/autopilot_resolve.go +++ b/internal/server/autopilot_resolve.go @@ -204,7 +204,8 @@ func (s *Server) noteOnce(key, what, text string, isErr bool) { return } projectID, branch, _ := strings.Cut(key, "\x00") - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Text: text, Error: isErr}) + kind := map[string]string{"check": proto.ActivityCheck, "ready": proto.ActivityShip, "resolve": proto.ActivityResolve}[what] + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Text: text, Error: isErr, Kind: kind}) } // unsay forgets the last thing said about a branch's what, so it is said @@ -267,6 +268,9 @@ func (s *Server) askToResolve(p *project, branch string, rw rewrite, files []str note(fmt.Sprintf("%s conflicts with %s, and asking %s to resolve it failed: %s", branch, rw.Base, agent.DisplayName(), perr.Message), true) return } + ask := newAsk(ctx, p, branch, wt.Path, agent.ID, "autopilot") + ask.Files = files // what the rebase onto the remote's base stopped on + s.projects.noteResolveAsk(p, branch, ask) note(fmt.Sprintf("%s conflicts with %s in %s: asked %s to resolve it", branch, rw.Base, strings.Join(files, ", "), agent.DisplayName()), false) } @@ -338,7 +342,7 @@ func (s *Server) shipRewrite(p *project, branch, dir string, rw rewrite, prNumbe a.mu.Unlock() s.projects.request(p) s.projects.requestPRs(p) - s.autopilotNote(proto.AutopilotNote{ProjectID: p.id, Branch: branch, + s.autopilotNote(proto.AutopilotNote{ProjectID: p.id, Branch: branch, Kind: proto.ActivityResolve, Text: fmt.Sprintf("pushed %s, rebased onto %s, to #%d", branch, rw.Base, prNumber)}) return "" } diff --git a/internal/server/autopilot_ship.go b/internal/server/autopilot_ship.go index acb8d240..f9bb1c45 100644 --- a/internal/server/autopilot_ship.go +++ b/internal/server/autopilot_ship.go @@ -217,9 +217,9 @@ func (s *Server) autopilotCheckDone(key, head, cmd string, info proto.PaneInfo, return } if info.ExitCode == 0 { - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Text: "check passed on " + branch}) + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: proto.ActivityCheck, Text: "check passed on " + branch}) } else { - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, Kind: proto.ActivityCheck, Text: fmt.Sprintf("check failed on %s (exit %d) β€” its terminal has the output", branch, info.ExitCode)}) } s.autopilotCheckEnded(p, proto.AutopilotCheck{ProjectID: projectID, Branch: branch, Pane: info.ID, Command: cmd, Exit: info.ExitCode}, output, head) @@ -270,7 +270,7 @@ func (s *Server) autopilotShip(projectID, branch string) { } a.mu.Unlock() if why != "" && why != was { - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Text: branch + " is finished but not pushed: " + why}) + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: proto.ActivityShip, Text: branch + " is finished but not pushed: " + why}) } } @@ -364,7 +364,7 @@ func (s *Server) ship(projectID, branch string) string { if _, perr := s.projects.pushBranch(proto.BranchPushParams{ProjectID: projectID, Branch: branch}); perr != nil { return "pushing it failed: " + perr.Message } - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: proto.ActivityShip, Text: fmt.Sprintf("pushed %s to #%d", branch, pr.Number)}) } return s.markReady(p, projectID, branch, wt.Path, info.Base, wt.Head, *pr) @@ -389,7 +389,7 @@ func (s *Server) ship(projectID, branch string) string { a.mu.Unlock() text += " as a draft, since " + strings.Join(unmet, " and ") + "; it is marked ready once that changes" } - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Text: text}) + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: proto.ActivityShip, Text: text}) } return "" } @@ -432,7 +432,7 @@ func (s *Server) markReady(p *project, projectID, branch, dir, base, head string a.mu.Unlock() s.unsay(key, "ready") s.projects.requestPRs(p) - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Kind: proto.ActivityShip, Text: fmt.Sprintf("marked #%d ready: what held it as a draft is met", pr.Number)}) return "" } @@ -533,7 +533,7 @@ func (s *Server) askForTest(projectID, branch string) { delete(a.saved.TestAsked, key) a.saveLocked() a.mu.Unlock() - s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, + s.autopilotNote(proto.AutopilotNote{ProjectID: projectID, Branch: branch, Error: true, Kind: proto.ActivityShip, Text: "asking " + agent.DisplayName() + " for a test on " + branch + " failed: " + perr.Message}) } } diff --git a/internal/server/autopilot_test.go b/internal/server/autopilot_test.go index e81f8f7c..c1ff5764 100644 --- a/internal/server/autopilot_test.go +++ b/internal/server/autopilot_test.go @@ -6,6 +6,7 @@ import ( "os/exec" "path/filepath" "reflect" + "slices" "strings" "testing" "time" @@ -840,6 +841,16 @@ func TestAutopilotResolveAsksTheAgent(t *testing.T) { if apGit(t, origin, "rev-parse", "api/model") != pushed { t.Fatal("pushed before the agent resolved it") } + // Said on the branch's worktree, so a client shows the agent at it. + var ask *proto.ResolveAsk + for _, w := range p.snapshot().Worktrees { + if w.Path == wt { + ask = w.Resolve + } + } + if ask == nil || ask.Pane != e.p.ID() || ask.By != "autopilot" || !slices.Equal(ask.Files, []string{"model.go"}) { + t.Errorf("ask: %+v", ask) + } a5WaitFor(t, "the request submitted", func() bool { st, _ := agentState(e); return st == proto.AgentIdle }) // The agent resolves it, keeping both sides, and finishes. diff --git a/internal/server/ci.go b/internal/server/ci.go new file mode 100644 index 00000000..a3709575 --- /dev/null +++ b/internal/server/ci.go @@ -0,0 +1,168 @@ +package server + +import ( + "context" + "errors" + "sync" + "time" + + "github.com/Amitgb14/conch/internal/ghx" + "github.com/Amitgb14/conch/internal/proto" +) + +// The CI panel's numbers: a project's GitHub Actions history read through +// gh and added up (ghx.ComputeStats), and a failed run's jobs run again. + +const ( + ciDaysDefault = 14 + ciDaysMax = 90 + // ciJobsPerCall bounds how many runs' jobs one ci.stats reads: each is + // a gh call, and a first look at a busy repository could need hundreds. + // The rest are said to be pending, and the next call reads more. + ciJobsPerCall = 40 + ciJobsWorkers = 4 + // ciJobsKept bounds the jobs kept per project. + ciJobsKept = 3000 +) + +type ciRunKey struct { + id int64 + attempt int +} + +func ciNoGH(err error) *proto.Error { + if errors.Is(err, ghx.ErrNoGH) { + return proto.Errorf(proto.ErrBadRequest, "gh is not installed on this machine: install the GitHub CLI and run gh auth login to see CI") + } + return proto.Errorf(proto.ErrBadRequest, "%v", err) +} + +func (pm *projectManager) ciStats(sp proto.CIStatsParams) (proto.CIStats, *proto.Error) { + p, perr := pm.gitProject(sp.ProjectID) + if perr != nil { + return proto.CIStats{}, perr + } + days := sp.Days + switch { + case days <= 0: + days = ciDaysDefault + case days > ciDaysMax: + days = ciDaysMax + } + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + // Two periods' worth: this one and the one it is compared with. + runs, err := ghx.Runs(ctx, p.root, min(200+days*2*20, 1000)) + if err != nil { + return proto.CIStats{}, ciNoGH(err) + } + now := time.Now() + start := now.AddDate(0, 0, -days) + + p.mu.Lock() + if p.ciJobs == nil { + p.ciJobs = map[ciRunKey][]ghx.Job{} + } + jobs := map[int64][]ghx.Job{} + var want []ghx.Run + for _, r := range runs { + if r.Status != "completed" || r.Created.Before(start) { + continue + } + if js, ok := p.ciJobs[ciRunKey{r.ID, r.Attempt}]; ok { + jobs[r.ID] = js + } else { + want = append(want, r) + } + } + p.mu.Unlock() + + pending := max(len(want)-ciJobsPerCall, 0) + want = want[:min(len(want), ciJobsPerCall)] + var mu sync.Mutex + var wg sync.WaitGroup + next := make(chan ghx.Run) + for range min(ciJobsWorkers, len(want)) { + wg.Add(1) + go func() { + defer wg.Done() + for r := range next { + js, err := ghx.RunJobs(ctx, p.root, r.ID) + mu.Lock() + if err != nil { + pending++ + } else { + jobs[r.ID] = js + } + mu.Unlock() + if err == nil { + p.mu.Lock() + if len(p.ciJobs) >= ciJobsKept { + clear(p.ciJobs) + } + p.ciJobs[ciRunKey{r.ID, r.Attempt}] = js + p.mu.Unlock() + } + } + }() + } + for _, r := range want { + next <- r + } + close(next) + wg.Wait() + + st := ghx.ComputeStats(runs, jobs, now, days, time.Local) + out := proto.CIStats{ + Days: st.Days, Runs: st.Runs, Passed: st.Passed, Failed: st.Failed, PrevRuns: st.PrevRuns, PrevPassed: st.PrevPassed, + MedianSeconds: st.MedianSeconds, PrevMedianSeconds: st.PrevMedianSeconds, QueueSeconds: st.QueueSeconds, + RedToGreenSeconds: st.RedToGreenSeconds, RedToGreenCount: st.RedToGreenCount, JobsPending: pending, + } + for _, d := range st.Daily { + out.Daily = append(out.Daily, proto.CIDay{Date: d.Date, Passed: d.Passed, Failed: d.Failed}) + } + for _, j := range st.Jobs { + out.Jobs = append(out.Jobs, proto.CIJob{Name: j.Name, Runs: j.Runs, Failed: j.Failed, MedianSeconds: j.MedianSeconds, P90Seconds: j.P90Seconds}) + } + for _, f := range st.Flaky { + out.Flaky = append(out.Flaky, proto.CIFlaky{Name: f.Name, Times: f.Times, How: f.How, Last: f.Last}) + } + for _, r := range st.Failing { + out.Failing = append(out.Failing, proto.CIRun{ID: r.ID, Workflow: r.Workflow, Branch: r.Branch, Sha: r.Sha, + Conclusion: r.Conclusion, Attempt: r.Attempt, URL: r.URL, At: r.Updated}) + } + return out, nil +} + +func (pm *projectManager) ciRerun(rp proto.CIRerunParams) (proto.CIRerunResult, *proto.Error) { + p, perr := pm.gitProject(rp.ProjectID) + if perr != nil { + return proto.CIRerunResult{}, perr + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + id := rp.RunID + if id == 0 { + if rp.Branch == "" { + return proto.CIRerunResult{}, proto.Errorf(proto.ErrBadRequest, "no run or branch given") + } + p.mu.Lock() + head := p.prs[rp.Branch].Head + p.mu.Unlock() + found, err := ghx.FailedRunID(ctx, p.root, rp.Branch, head) + switch { + case errors.Is(err, ghx.ErrNoFailedRun): + return proto.CIRerunResult{}, proto.Errorf(proto.ErrNotFound, + "no failed GitHub Actions run on %s to run again: the failing check is another service's, or it was already re-run", rp.Branch) + case err != nil: + return proto.CIRerunResult{}, ciNoGH(err) + } + id = found + } + if err := ghx.Rerun(ctx, p.root, id); err != nil { + return proto.CIRerunResult{}, ciNoGH(err) + } + // Its checks are pending again: the pull request says so sooner. + pm.requestPRs(p) + return proto.CIRerunResult{RunID: id}, nil +} diff --git a/internal/server/ci_test.go b/internal/server/ci_test.go new file mode 100644 index 00000000..01be3349 --- /dev/null +++ b/internal/server/ci_test.go @@ -0,0 +1,128 @@ +package server_test + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Amitgb14/conch/internal/proto" +) + +// fakeCIGH puts a gh on CONCH_GH that lists runs, answers each run's jobs +// (writing down which it was asked for) and records re-runs, so a test can +// see what the server asked GitHub for. +func fakeCIGH(t *testing.T, runs string) (dir string) { + t.Helper() + dir = t.TempDir() + os.WriteFile(filepath.Join(dir, "runs"), []byte(runs), 0o600) + script := `#!/bin/sh +d="` + dir + `" +case "$1 $2" in +"pr list") echo '[]' ;; +"run list") + if [ "$3" = --branch ]; then echo '[{"databaseId": 8, "workflowName": "ci", "url": "u8", "headSha": "h", "conclusion": "failure"}]'; else cat "$d/runs"; fi ;; +"run view") echo "$3" >> "$d/viewed" + echo '{"jobs":[{"name":"test","conclusion":"success","startedAt":"2026-11-01T00:00:00Z","completedAt":"2026-11-01T00:05:00Z"}]}' ;; +"run rerun") echo "$3 $4" >> "$d/reruns"; [ "$3" = 404 ] && { echo "run 404 not found" >&2; exit 1; } ; true ;; +*) exit 7 ;; +esac +` + gh := filepath.Join(dir, "gh") + os.WriteFile(gh, []byte(script), 0o755) + t.Setenv("CONCH_GH", gh) + return dir +} + +func ciRunJSON(id int, conclusion string, ago time.Duration) string { + created := time.Now().Add(-ago).UTC().Format(time.RFC3339) + done := time.Now().Add(-ago + 3*time.Minute).UTC().Format(time.RFC3339) + return fmt.Sprintf(`{"databaseId":%d,"workflowName":"ci","headBranch":"main","headSha":"s%d","event":"push","status":"completed","conclusion":%q,"attempt":1,"url":"u%d","createdAt":%q,"startedAt":%q,"updatedAt":%q}`, + id, id, conclusion, id, created, created, done) +} + +func TestCIStats(t *testing.T) { + runs := "[" + strings.Join([]string{ + ciRunJSON(3, "success", time.Hour), + ciRunJSON(2, "failure", 2*time.Hour), + ciRunJSON(1, "success", 3*time.Hour), + }, ",") + "]" + dir := fakeCIGH(t, runs) + c, _, proj := setupRepo(t) + if miss := c.MissingCapabilities([]string{proto.CapCIStats, proto.CapCIRerun}); len(miss) > 0 { + t.Fatalf("capabilities missing: %v", miss) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + var s proto.CIStats + if err := c.Call(ctx, proto.MethodCIStats, proto.CIStatsParams{ProjectID: proj.ID, Days: 7}, &s); err != nil { + t.Fatal(err) + } + if s.Days != 7 || s.Runs != 3 || s.Passed != 2 || s.Failed != 1 || len(s.Daily) != 7 || s.MedianSeconds != 180 { + t.Fatalf("stats: %+v", s) + } + if len(s.Jobs) != 1 || s.Jobs[0].Name != "test" || s.Jobs[0].MedianSeconds != 300 || s.JobsPending != 0 { + t.Errorf("jobs: %+v pending %d", s.Jobs, s.JobsPending) + } + // A finished run's jobs never change: asked for once, then kept. + if err := c.Call(ctx, proto.MethodCIStats, proto.CIStatsParams{ProjectID: proj.ID}, &s); err != nil { + t.Fatal(err) + } + if s.Days != 14 { + t.Errorf("no days given is 14: %d", s.Days) + } + viewed, _ := os.ReadFile(filepath.Join(dir, "viewed")) + if n := len(strings.Fields(string(viewed))); n != 3 { + t.Errorf("jobs read %d times for 3 runs: %q", n, viewed) + } + // Too many days is held to 90. + if err := c.Call(ctx, proto.MethodCIStats, proto.CIStatsParams{ProjectID: proj.ID, Days: 1000}, &s); err != nil || s.Days != 90 { + t.Errorf("1000 days: %d %v", s.Days, err) + } +} + +func TestCIStatsRefusals(t *testing.T) { + fakeCIGH(t, `oops`) + c, _, proj := setupRepo(t) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + var s proto.CIStats + if err := c.Call(ctx, proto.MethodCIStats, proto.CIStatsParams{ProjectID: proj.ID}, &s); err == nil || !strings.Contains(err.Error(), "gh run list") { + t.Errorf("gh's bad answer: %v", err) + } + if err := c.Call(ctx, proto.MethodCIStats, proto.CIStatsParams{ProjectID: "nope"}, &s); err == nil { + t.Error("an unknown project was answered") + } + t.Setenv("CONCH_GH", filepath.Join(t.TempDir(), "no-gh")) + if err := c.Call(ctx, proto.MethodCIStats, proto.CIStatsParams{ProjectID: proj.ID}, &s); err == nil || !strings.Contains(err.Error(), "gh") { + t.Errorf("no gh: %v", err) + } +} + +func TestCIRerun(t *testing.T) { + dir := fakeCIGH(t, `[]`) + c, _, proj := setupRepo(t) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + var r proto.CIRerunResult + if err := c.Call(ctx, proto.MethodCIRerun, proto.CIRerunParams{ProjectID: proj.ID, RunID: 42}, &r); err != nil || r.RunID != 42 { + t.Fatalf("by run: %+v %v", r, err) + } + // By branch: its newest failed run. + if err := c.Call(ctx, proto.MethodCIRerun, proto.CIRerunParams{ProjectID: proj.ID, Branch: "main"}, &r); err != nil || r.RunID != 8 { + t.Fatalf("by branch: %+v %v", r, err) + } + reruns, _ := os.ReadFile(filepath.Join(dir, "reruns")) + if string(reruns) != "42 --failed\n8 --failed\n" { + t.Errorf("gh was asked %q", reruns) + } + if err := c.Call(ctx, proto.MethodCIRerun, proto.CIRerunParams{ProjectID: proj.ID}, &r); err == nil { + t.Error("neither a run nor a branch was taken") + } + if err := c.Call(ctx, proto.MethodCIRerun, proto.CIRerunParams{ProjectID: proj.ID, RunID: 404}, &r); err == nil || !strings.Contains(err.Error(), "not found") { + t.Errorf("gh's refusal: %v", err) + } +} diff --git a/internal/server/harvest.go b/internal/server/harvest.go index e67a94b8..11808c50 100644 --- a/internal/server/harvest.go +++ b/internal/server/harvest.go @@ -141,7 +141,11 @@ func (pm *projectManager) pushBranch(pp proto.BranchPushParams) (proto.BranchPus defer cancel() var took int var err error - if pp.Rebase { + switch { + case pp.Over != "": + // A rewrite going up over what the remote has: that, and only that. + err = gitx.PushOver(ctx, p.root, pp.Branch, pp.Over) + case pp.Rebase: // A rebase needs the branch checked out; pushing alone does not. // Asked of git, not the last snapshot: one taken while a rebase // was under way saw the worktree detached, and refused the next. @@ -155,7 +159,7 @@ func (pm *projectManager) pushBranch(pp proto.BranchPushParams) (proto.BranchPus "%s is not checked out here, so its commits cannot be rebased onto the remote's", pp.Branch) } took, err = gitx.PushRebase(ctx, wt.Path, pp.Branch) - } else { + default: err = gitx.Push(ctx, p.root, pp.Branch) } pm.request(p) diff --git a/internal/server/intake.go b/internal/server/intake.go index 7eae0a5d..1ad04fdd 100644 --- a/internal/server/intake.go +++ b/internal/server/intake.go @@ -223,6 +223,8 @@ func (s *Server) intakeProject(id, label string, wip int) { rec.Item = it.ID room-- log.Printf("intake: took #%d %q of %s (label %s)", is.Number, is.Title, info.Name, label) + s.autopilotNote(proto.AutopilotNote{ProjectID: id, Kind: proto.ActivityIntake, + Text: fmt.Sprintf("took #%d %s as a queued task (label %s)", is.Number, is.Title, label)}) msg := fmt.Sprintf("conch took this from the `%s` label: it is queued as a task, and starts once fewer than %d agents are busy in the project. Its pull request will say Fixes #%d.", label, wip, is.Number) if err := ghx.CommentIssue(ctx, p.root, is.Number, msg); err != nil { log.Printf("intake: comment on #%d: %v", is.Number, err) diff --git a/internal/server/log.go b/internal/server/log.go index e492c146..a5bccf59 100644 --- a/internal/server/log.go +++ b/internal/server/log.go @@ -34,6 +34,9 @@ func (pm *projectManager) log(lp proto.LogParams) (proto.LogResult, *proto.Error return proto.LogResult{}, proto.Errorf(proto.ErrBadRequest, "%v", err) } res := proto.LogResult{Commits: make([]proto.LogCommit, 0, len(commits)), More: more, Remotes: gitx.Remotes(ctx, p.root)} + if f := gitx.Format(ctx, p.root); f.Objects != "" { + res.Format = &proto.RepoFormat{Objects: f.Objects, Refs: f.Refs} + } for _, c := range commits { res.Commits = append(res.Commits, proto.LogCommit{Hash: c.Hash, Parents: c.Parents, Subject: c.Subject, Author: c.Author, Time: c.Time, Refs: c.Refs}) diff --git a/internal/server/log_test.go b/internal/server/log_test.go index 8d0033cb..6e2b3bb0 100644 --- a/internal/server/log_test.go +++ b/internal/server/log_test.go @@ -2,8 +2,10 @@ package server_test import ( "os" + "os/exec" "path/filepath" "slices" + "strings" "testing" "github.com/Amitgb14/conch/internal/proto" @@ -41,6 +43,11 @@ func TestProjectLog(t *testing.T) { if len(res.Commits) != 1 || !res.More || res.Commits[0].Subject != "on feat" { t.Errorf("limit 1: %+v", res) } + // The repository's format comes with it: a SHA-1 repository with the + // files backend, as git 2 makes them. + if res.Format == nil || res.Format.Objects != "sha1" || res.Format.Refs != "files" { + t.Errorf("format: %+v", res.Format) + } } // An unknown project is an error, as everywhere else; so is one that is @@ -61,3 +68,57 @@ func TestProjectLogRefusals(t *testing.T) { t.Error("not a repository: no error") } } + +// A rebase that stops on a conflict detaches the worktree's HEAD, so git +// names no branch there; the worktree says which branch the rebase is +// rewriting, or a client could not tell whose conflict it is. +func TestWorktreeRebasingBranch(t *testing.T) { + c, proj, repo, wt, _ := harvestFixture(t) + git(t, wt, "config", "user.name", "t") + git(t, wt, "config", "user.email", "t@example.com") + os.WriteFile(filepath.Join(wt, "a.txt"), []byte("feat\n"), 0o644) + git(t, wt, "commit", "-q", "-am", "on feat") + os.WriteFile(filepath.Join(repo, "a.txt"), []byte("main\n"), 0o644) + git(t, repo, "commit", "-q", "-am", "on main") + if out, err := exec.Command("git", "-C", wt, "rebase", "main").CombinedOutput(); err == nil { + t.Fatalf("rebase did not stop: %s", out) + } + call(t, c, proto.MethodProjectRefresh, proto.ProjectRef{ID: proj.ID}, nil) + p := waitProject(t, c, func(p proto.ProjectInfo) bool { + for _, w := range p.Worktrees { + // Its conflicts are the files the rebase stopped on. + if w.Path == wt && w.Rebasing == "feat" && w.Status != nil && w.Status.Conflicts > 0 && slices.Equal(w.Conflicts, []string{"a.txt"}) { + return true + } + } + return false + }) + for _, w := range p.Worktrees { + if w.Main && w.Rebasing != "" { + t.Errorf("the main checkout is not rebasing: %+v", w) + } + } +} + +// A commit handed to an agent from the graph: the new branch starts at +// that commit, not at the base's newest. +func TestWorktreeFromCommit(t *testing.T) { + c, proj, repo, _, _ := harvestFixture(t) + head := func(dir string) string { + out, err := exec.Command("git", "-C", dir, "rev-parse", "HEAD").Output() + if err != nil { + t.Fatal(err) + } + return strings.TrimSpace(string(out)) + } + first := head(repo) + os.WriteFile(filepath.Join(repo, "a.txt"), []byte("later\n"), 0o644) + git(t, repo, "commit", "-q", "-am", "later") + var res proto.WorktreeResult + if err := call(t, c, proto.MethodWorktreeAdd, proto.WorktreeAddParams{ProjectID: proj.ID, Branch: "from-old", Base: first}, &res); err != nil { + t.Fatal(err) + } + if got := head(res.Path); got != first { + t.Errorf("the branch starts at %s, want %s", got, first) + } +} diff --git a/internal/server/overlap.go b/internal/server/overlap.go index 4b113f3e..cdcbedda 100644 --- a/internal/server/overlap.go +++ b/internal/server/overlap.go @@ -22,6 +22,12 @@ const maxOverlapFiles = 5 func noteOverlaps(ctx context.Context, root string, info *proto.ProjectInfo) { touched := map[int][]string{} for i, wt := range info.Worktrees { + // A checkout stopped mid-rebase or merge: its conflicts are the + // files it stopped on, not a merge still to be tried. + if wt.Status != nil && wt.Status.Conflicts > 0 { + info.Worktrees[i].Conflicts = gitx.ConflictFiles(ctx, wt.Path) + continue + } if wt.Main || wt.Branch == "" { continue } diff --git a/internal/server/projects.go b/internal/server/projects.go index 1d25105e..83723fbb 100644 --- a/internal/server/projects.go +++ b/internal/server/projects.go @@ -166,7 +166,10 @@ type project struct { // is older than info and is not applied (refresh). gen uint64 - prs map[string]proto.PRInfo // by head branch + prs map[string]proto.PRInfo // by head branch + // ciJobs are finished Actions runs' jobs, by run and attempt, read + // for the CI panel: they never change, so each is asked for once. + ciJobs map[ciRunKey][]ghx.Job prStatus string prAt time.Time // last fetch prNext time.Time // no fetch before this (after errors) @@ -179,6 +182,9 @@ type project struct { prOpen map[string]bool baseOwed map[string]bool baseFetching bool + // asks are the agents asked to resolve a branch's conflict, by + // branch (resolving.go). + asks map[string]resolveAsk } type catalog struct { @@ -628,6 +634,7 @@ func (pm *projectManager) apply(p *project, info proto.ProjectInfo, stamp string } p.gen++ p.applyPRs(&info) + p.applyAsks(&info, time.Now(), true) old := p.info info.LocalFiles, info.LocalFilesDefault = old.LocalFiles, old.LocalFilesDefault info.Setup = old.Setup @@ -902,6 +909,7 @@ func (p *project) load() proto.ProjectInfo { wi.Operation = op if wt.Detached && rebasing != "" { wi.Branch = rebasing + wi.Rebasing = rebasing } } if st, err := gitx.WorktreeStatus(ctx, wt.Path); err == nil { diff --git a/internal/server/rebased.go b/internal/server/rebased.go new file mode 100644 index 00000000..26428e6c --- /dev/null +++ b/internal/server/rebased.go @@ -0,0 +1,91 @@ +package server + +import ( + "context" + "log" + "time" + + "github.com/Amitgb14/conch/internal/gitx" + "github.com/Amitgb14/conch/internal/proto" +) + +// A branch rebased β€” an agent asked to resolve its conflict with the base +// does this β€” and not yet pushed: read back for the person to review +// before it goes up over the branch it rewrote, or to put back. + +// rebasedDiffMax caps the range-diff handed to a client: a rebase that +// rewrote a great deal is better read in a terminal than in a panel. +const rebasedDiffMax = 256 << 10 + +func (pm *projectManager) branchRebased(rp proto.BranchRebasedParams) (proto.BranchRebased, *proto.Error) { + out := proto.BranchRebased{Rebases: []proto.BranchRebase{}} + p, perr := pm.gitProject(rp.ProjectID) + if perr != nil { + return out, perr + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + wts, err := gitx.Worktrees(ctx, p.root) + if err != nil { + return out, proto.Errorf(proto.ErrBadRequest, "%v", err) + } + base := p.baseBranch(ctx) + seen := map[string]bool{} + for _, wt := range wts { + if wt.Branch == "" || wt.Prunable || wt.Branch == base || seen[wt.Branch] || (rp.Branch != "" && wt.Branch != rp.Branch) { + continue + } + seen[wt.Branch] = true + r, err := gitx.LastRebase(ctx, wt.Path, wt.Branch) + if err != nil || r == nil { + continue + } + remote := gitx.PushedHead(ctx, wt.Path, wt.Branch) + if remote == r.After { + continue // pushed already + } + b := proto.BranchRebase{Branch: r.Branch, Before: r.Before, After: r.After, Onto: r.Onto, At: r.At, Remote: remote} + if cs, err := gitx.Rewritten(ctx, wt.Path, r); err == nil { + for _, c := range cs { + b.Commits = append(b.Commits, proto.RebasedCommit{Old: c.Old, New: c.New, Subject: c.Subject, Change: c.Change}) + } + } else { + log.Printf("project %s: reading the rebase of %s: %v", p.id, r.Branch, err) + } + if rp.Diff && rp.Branch != "" { + if d, err := gitx.RewriteDiff(ctx, wt.Path, r, rebasedDiffMax); err == nil { + b.Diff = d + } else { + return out, proto.Errorf(proto.ErrBadRequest, "%v", err) + } + } + out.Rebases = append(out.Rebases, b) + } + return out, nil +} + +func (pm *projectManager) undoRebase(up proto.BranchRebaseUndoParams) (struct{}, *proto.Error) { + p, perr := pm.gitProject(up.ProjectID) + if perr != nil { + return struct{}{}, perr + } + if up.Before == "" || up.After == "" { + return struct{}{}, proto.Errorf(proto.ErrBadRequest, "say where %s was before the rebase and after it", up.Branch) + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + wt, ok, perr := checkout(ctx, p, up.Branch) + if perr != nil { + return struct{}{}, perr + } + if !ok { + return struct{}{}, proto.Errorf(proto.ErrBadRequest, "%s is not checked out here, so its rebase cannot be undone", up.Branch) + } + err := gitx.UndoRebase(ctx, wt.Path, up.Branch, up.Before, up.After) + pm.request(p) + if err != nil { + return struct{}{}, proto.Errorf(proto.ErrBadRequest, "%v", err) + } + log.Printf("project %s: put %s back where it was before its rebase", p.id, up.Branch) + return struct{}{}, nil +} diff --git a/internal/server/rebased_test.go b/internal/server/rebased_test.go new file mode 100644 index 00000000..ef175939 --- /dev/null +++ b/internal/server/rebased_test.go @@ -0,0 +1,122 @@ +package server_test + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/Amitgb14/conch/internal/client" + "github.com/Amitgb14/conch/internal/proto" +) + +// rebasedFixture is feat pushed, then rebased onto a main that changed +// the same line, its conflict resolved in feat's worktree β€” as an agent +// asked to resolve it leaves things. It returns feat's tips before and +// after. +func rebasedFixture(t *testing.T) (c *client.Client, proj proto.ProjectInfo, wt, origin, before, after string) { + t.Helper() + c, proj, repo, wt, origin := harvestFixture(t) + git(t, repo, "push", "-q", "origin", "main") + os.WriteFile(filepath.Join(wt, "a.txt"), []byte("feat\n"), 0o644) + git(t, wt, "commit", "-qam", "feat edits a") + os.WriteFile(filepath.Join(wt, "b.txt"), []byte("b\n"), 0o644) + git(t, wt, "add", "b.txt") + git(t, wt, "commit", "-qm", "feat adds b") + if err := call(t, c, proto.MethodBranchPush, proto.BranchPushParams{ProjectID: proj.ID, Branch: "feat"}, nil); err != nil { + t.Fatal(err) + } + os.WriteFile(filepath.Join(repo, "a.txt"), []byte("main\n"), 0o644) + git(t, repo, "commit", "-qam", "main edits a") + before = gitOut(t, wt, "rev-parse", "HEAD") + cmd := exec.Command("git", "-C", wt, "rebase", "main") + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err == nil { + t.Fatalf("expected a conflict:\n%s", out) + } + os.WriteFile(filepath.Join(wt, "a.txt"), []byte("main\nfeat\n"), 0o644) + git(t, wt, "add", "a.txt") + cmd = exec.Command("git", "-C", wt, "rebase", "--continue") + cmd.Env = append(os.Environ(), "GIT_EDITOR=true", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("continue: %v\n%s", err, out) + } + return c, proj, wt, origin, before, gitOut(t, wt, "rev-parse", "HEAD") +} + +// A resolved rebase is read back for review, pushed over the old branch +// with a lease, and then no longer listed. +func TestBranchRebasedReviewAndPush(t *testing.T) { + c, proj, wt, origin, before, after := rebasedFixture(t) + if miss := c.MissingCapabilities([]string{proto.CapBranchRebased}); len(miss) > 0 { + t.Fatalf("missing %v", miss) + } + var got proto.BranchRebased + if err := call(t, c, proto.MethodBranchRebased, proto.BranchRebasedParams{ProjectID: proj.ID}, &got); err != nil { + t.Fatal(err) + } + if len(got.Rebases) != 1 { + t.Fatalf("%+v", got) + } + r := got.Rebases[0] + if r.Branch != "feat" || r.Before != before || r.After != after || r.Remote != before || r.At.IsZero() || r.Diff != "" { + t.Errorf("rebase: %+v", r) + } + if len(r.Commits) != 2 || r.Commits[0].Change != "changed" || r.Commits[0].Subject != "feat edits a" || r.Commits[1].Change != "same" { + t.Errorf("commits: %+v", r.Commits) + } + // The resolution itself, asked of one branch. + if err := call(t, c, proto.MethodBranchRebased, proto.BranchRebasedParams{ProjectID: proj.ID, Branch: "feat", Diff: true}, &got); err != nil { + t.Fatal(err) + } + if len(got.Rebases) != 1 || !strings.Contains(got.Rebases[0].Diff, "main") { + t.Errorf("diff: %+v", got) + } + if err := call(t, c, proto.MethodBranchRebased, proto.BranchRebasedParams{ProjectID: proj.ID, Branch: "main"}, &got); err != nil || len(got.Rebases) != 0 { + t.Errorf("main was not rebased: %+v %v", got, err) + } + + // A plain push of the rewrite is refused, and so is one over a commit + // the remote does not have. + err := call(t, c, proto.MethodBranchPush, proto.BranchPushParams{ProjectID: proj.ID, Branch: "feat"}, nil) + wantErr(t, err, "") + err = call(t, c, proto.MethodBranchPush, proto.BranchPushParams{ProjectID: proj.ID, Branch: "feat", Over: after}, nil) + wantErr(t, err, "") + if gitOut(t, origin, "rev-parse", "feat") != before { + t.Fatal("the remote's branch was replaced") + } + if err := call(t, c, proto.MethodBranchPush, proto.BranchPushParams{ProjectID: proj.ID, Branch: "feat", Over: before}, nil); err != nil { + t.Fatal(err) + } + if gitOut(t, origin, "rev-parse", "feat") != after { + t.Fatal("the rebased branch was not pushed") + } + if err := call(t, c, proto.MethodBranchRebased, proto.BranchRebasedParams{ProjectID: proj.ID}, &got); err != nil || len(got.Rebases) != 0 { + t.Errorf("pushed, still listed: %+v %v", got, err) + } + _ = wt +} + +// Undoing puts the branch back where it was, once. +func TestBranchRebaseUndo(t *testing.T) { + c, proj, wt, _, before, after := rebasedFixture(t) + undo := proto.BranchRebaseUndoParams{ProjectID: proj.ID, Branch: "feat", Before: before, After: after} + os.WriteFile(filepath.Join(wt, "b.txt"), []byte("dirty\n"), 0o644) + wantErr(t, call(t, c, proto.MethodBranchRebaseUndo, undo, nil), "uncommitted") + git(t, wt, "checkout", "--", "b.txt") + if err := call(t, c, proto.MethodBranchRebaseUndo, undo, nil); err != nil { + t.Fatal(err) + } + if gitOut(t, wt, "rev-parse", "HEAD") != before { + t.Fatal("not put back") + } + wantErr(t, call(t, c, proto.MethodBranchRebaseUndo, undo, nil), "moved on") + var got proto.BranchRebased + if err := call(t, c, proto.MethodBranchRebased, proto.BranchRebasedParams{ProjectID: proj.ID}, &got); err != nil || len(got.Rebases) != 0 { + t.Errorf("undone, still listed: %+v %v", got, err) + } + wantErr(t, call(t, c, proto.MethodBranchRebaseUndo, proto.BranchRebaseUndoParams{ProjectID: proj.ID, Branch: "nope", Before: before, After: after}, nil), "not checked out") + wantErr(t, call(t, c, proto.MethodBranchRebaseUndo, proto.BranchRebaseUndoParams{ProjectID: proj.ID, Branch: "feat"}, nil), "") + wantErr(t, call(t, c, proto.MethodBranchRebased, proto.BranchRebasedParams{ProjectID: "nope"}, &got), "") +} diff --git a/internal/server/resolving.go b/internal/server/resolving.go new file mode 100644 index 00000000..2a99e1ae --- /dev/null +++ b/internal/server/resolving.go @@ -0,0 +1,140 @@ +package server + +import ( + "context" + "log" + "time" + + "github.com/Amitgb14/conch/internal/gitx" + "github.com/Amitgb14/conch/internal/proto" +) + +// An agent asked to resolve a branch's conflict with the base works for a +// while, and all git shows meanwhile is a branch stuck mid-rebase β€” or, +// before it has started, one that will conflict. So who was asked is +// kept on the branch's worktree (WorktreeInfo.Resolve) for as long as the +// conflict is there, and a client can say the agent is at it. +// +// It is kept in memory: a reload forgets it, and a client then goes by an +// agent working in a worktree stopped mid-rebase, which is nearly always +// the same thing. + +// askGrace is how long an ask outlives a conflict git no longer shows, +// while the branch has not moved: the agent has not started the rebase +// yet (the autopilot undoes its own before asking), or merge-tree could +// not say there was a conflict (git before 2.38). +const askGrace = 2 * time.Minute + +// resolveAsk is an ask and where the branch was when it was made. +type resolveAsk struct { + proto.ResolveAsk + head string +} + +// stillConflicts is whether a worktree shows a conflict with the base: +// stopped mid-rebase or merge, or one merging it would meet. +func stillConflicts(w proto.WorktreeInfo) bool { + return w.Rebasing != "" || (w.Status != nil && w.Status.Conflicts > 0) || len(w.Conflicts) > 0 +} + +// applyAsks puts each ask on its branch's worktree in info and, when info +// is a fresh read of git (fresh), forgets those whose conflict is over: +// an older read can predate the very rebase the agent was asked about. +// The caller holds p.mu, and info's Worktrees are its own to change. +func (p *project) applyAsks(info *proto.ProjectInfo, now time.Time, fresh bool) { + seen := map[string]bool{} + for i, w := range info.Worktrees { + info.Worktrees[i].Resolve = nil + name := w.Branch + if name == "" { + name = w.Rebasing + } + a, ok := p.asks[name] + if !ok || name == "" { + continue + } + seen[name] = true + if fresh && !stillConflicts(w) && (w.Head != a.head || now.Sub(a.At) > askGrace) { + delete(p.asks, name) // resolved, given up on, or never needed + continue + } + r := a.ResolveAsk + info.Worktrees[i].Resolve = &r + } + for name := range p.asks { + if fresh && !seen[name] { + delete(p.asks, name) // its worktree is gone + } + } +} + +// noteResolveAsk records ask (nil: nobody) for branch and says so to the +// clients at once rather than at the next refresh. +func (pm *projectManager) noteResolveAsk(p *project, branch string, ask *resolveAsk) { + p.mu.Lock() + if ask == nil { + delete(p.asks, branch) + } else { + if p.asks == nil { + p.asks = map[string]resolveAsk{} + } + p.asks[branch] = *ask + } + info := p.info + info.Worktrees = append([]proto.WorktreeInfo(nil), info.Worktrees...) + p.applyAsks(&info, time.Now(), false) + p.info = info + p.gen++ // a read of git begun before this is older than it + p.mu.Unlock() + if pm.s.projectRegistered(p) { + pm.s.broadcast(proto.EventProjectUpdated, info) + } +} + +// newAsk is pane asked to resolve branch, checked out at dir, by by. +func newAsk(ctx context.Context, p *project, branch, dir, pane, by string) *resolveAsk { + // The files a stopped rebase is waiting on; else those merging it + // would conflict in, from the last refresh. + files := gitx.ConflictFiles(ctx, dir) + for _, w := range p.snapshot().Worktrees { + if w.Path == dir && len(files) == 0 { + files = w.Conflicts + } + } + return &resolveAsk{ + ResolveAsk: proto.ResolveAsk{Pane: pane, By: by, At: time.Now(), Files: files}, + head: gitx.CommitOf(ctx, dir, "HEAD"), + } +} + +func (s *Server) branchResolving(rp proto.BranchResolvingParams) (struct{}, *proto.Error) { + p, perr := s.projects.gitProject(rp.ProjectID) + if perr != nil { + return struct{}{}, perr + } + if rp.Branch == "" { + return struct{}{}, proto.Errorf(proto.ErrBadRequest, "say which branch") + } + if rp.PaneID == "" { + s.projects.noteResolveAsk(p, rp.Branch, nil) + return struct{}{}, nil + } + if _, perr := s.get(rp.PaneID); perr != nil { + return struct{}{}, perr + } + // Mid-rebase git names no branch: the worktree rewriting it is the one. + dir := "" + for _, w := range p.snapshot().Worktrees { + if w.Branch == rp.Branch || (w.Branch == "" && w.Rebasing == rp.Branch) { + dir = w.Path + } + } + if dir == "" { + return struct{}{}, proto.Errorf(proto.ErrBadRequest, "%s is not checked out here", rp.Branch) + } + ctx, cancel := context.WithTimeout(context.Background(), gitTimeout) + defer cancel() + s.projects.noteResolveAsk(p, rp.Branch, newAsk(ctx, p, rp.Branch, dir, rp.PaneID, "")) + log.Printf("project %s: pane %s is resolving %s's conflict", p.id, rp.PaneID, rp.Branch) + return struct{}{}, nil +} diff --git a/internal/server/resolving_internal_test.go b/internal/server/resolving_internal_test.go new file mode 100644 index 00000000..c5355716 --- /dev/null +++ b/internal/server/resolving_internal_test.go @@ -0,0 +1,68 @@ +package server + +import ( + "testing" + "time" + + "github.com/Amitgb14/conch/internal/proto" +) + +// When an ask is forgotten: only on a fresh read of git, once the branch +// shows no conflict and has moved, or has not moved for askGrace; and +// with its worktree. +func TestApplyAsks(t *testing.T) { + now := time.Now() + ask := func(head string, at time.Time) resolveAsk { + return resolveAsk{ResolveAsk: proto.ResolveAsk{Pane: "p1", At: at}, head: head} + } + info := func(ws ...proto.WorktreeInfo) proto.ProjectInfo { return proto.ProjectInfo{Worktrees: ws} } + stopped := proto.WorktreeInfo{Path: "/w/a", Rebasing: "a", Head: "h2", Status: &proto.GitStatus{Conflicts: 1}} + clean := proto.WorktreeInfo{Path: "/w/a", Branch: "a", Head: "h1"} + moved := proto.WorktreeInfo{Path: "/w/a", Branch: "a", Head: "h3"} + coming := proto.WorktreeInfo{Path: "/w/a", Branch: "a", Head: "h3", Conflicts: []string{"x.go"}} + + cases := []struct { + name string + w proto.WorktreeInfo + at time.Time + fresh bool + kept bool + }{ + {"stopped mid-rebase", stopped, now.Add(-time.Hour), true, true}, + {"will conflict", coming, now.Add(-time.Hour), true, true}, + {"not started yet", clean, now, true, true}, + {"never started", clean, now.Add(-askGrace - time.Second), true, false}, + {"rebase finished", moved, now, true, false}, + {"an older read", moved, now, false, true}, + } + for _, c := range cases { + p := &project{asks: map[string]resolveAsk{"a": ask("h1", c.at)}} + in := info(c.w) + p.applyAsks(&in, now, c.fresh) + if got := in.Worktrees[0].Resolve != nil; got != c.kept { + t.Errorf("%s: shown %v, want %v", c.name, got, c.kept) + } + if _, got := p.asks["a"]; got != c.kept { + t.Errorf("%s: kept %v, want %v", c.name, got, c.kept) + } + } + + // Its worktree gone: forgotten, but not on an older read. + p := &project{asks: map[string]resolveAsk{"a": ask("h1", now)}} + in := info(proto.WorktreeInfo{Path: "/w/b", Branch: "b", Resolve: &proto.ResolveAsk{Pane: "stale"}}) + p.applyAsks(&in, now, false) + if len(p.asks) != 1 || in.Worktrees[0].Resolve != nil { + t.Errorf("older read: %v %+v", p.asks, in.Worktrees[0].Resolve) + } + p.applyAsks(&in, now, true) + if len(p.asks) != 0 { + t.Errorf("worktree gone, still asked: %v", p.asks) + } + // Nothing asked: nothing shown, and a nil map is fine. + p = &project{} + in = info(stopped) + p.applyAsks(&in, now, true) + if in.Worktrees[0].Resolve != nil { + t.Error("shown with no ask") + } +} diff --git a/internal/server/resolving_test.go b/internal/server/resolving_test.go new file mode 100644 index 00000000..439ecb8b --- /dev/null +++ b/internal/server/resolving_test.go @@ -0,0 +1,87 @@ +package server_test + +import ( + "os" + "os/exec" + "path/filepath" + "slices" + "testing" + + "github.com/Amitgb14/conch/internal/proto" +) + +// resolveOf is the ask on the worktree at path, as the project says. +func resolveOf(p proto.ProjectInfo, path string) *proto.ResolveAsk { + for _, w := range p.Worktrees { + if w.Path == path { + return w.Resolve + } + } + return nil +} + +// Who was asked to resolve a branch's conflict is on its worktree for as +// long as the conflict is there, so a client can say an agent is at it, +// and gone once the rebase is finished. +func TestBranchResolving(t *testing.T) { + c, proj, repo, wt, _ := harvestFixture(t) + if miss := c.MissingCapabilities([]string{proto.CapBranchResolving}); len(miss) > 0 { + t.Fatalf("missing %v", miss) + } + os.WriteFile(filepath.Join(wt, "a.txt"), []byte("feat\n"), 0o644) + git(t, wt, "commit", "-qam", "feat edits a") + os.WriteFile(filepath.Join(repo, "a.txt"), []byte("main\n"), 0o644) + git(t, repo, "commit", "-qam", "main edits a") + cmd := exec.Command("git", "-C", wt, "rebase", "main") + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err == nil { + t.Fatalf("expected a conflict:\n%s", out) + } + var pane proto.PaneInfo + if err := call(t, c, proto.MethodPaneCreate, proto.PaneCreateParams{Command: []string{"/bin/sh", "-c", "sleep 30"}, Cwd: wt}, &pane); err != nil { + t.Fatal(err) + } + + // Mid-rebase git names no branch; the ask is by the branch all the same. + ask := proto.BranchResolvingParams{ProjectID: proj.ID, Branch: "feat", PaneID: pane.ID} + if err := call(t, c, proto.MethodBranchResolving, ask, nil); err != nil { + t.Fatal(err) + } + got := waitProject(t, c, func(p proto.ProjectInfo) bool { return p.ID == proj.ID && resolveOf(p, wt) != nil }) + r := resolveOf(got, wt) + if r.Pane != pane.ID || r.By != "" || r.At.IsZero() || !slices.Equal(r.Files, []string{"a.txt"}) { + t.Errorf("ask: %+v", r) + } + + // Taken back by the person: no longer said. + if err := call(t, c, proto.MethodBranchResolving, proto.BranchResolvingParams{ProjectID: proj.ID, Branch: "feat"}, nil); err != nil { + t.Fatal(err) + } + waitProject(t, c, func(p proto.ProjectInfo) bool { return p.ID == proj.ID && resolveOf(p, wt) == nil }) + + // Asked again, then resolved: gone with the conflict. + if err := call(t, c, proto.MethodBranchResolving, ask, nil); err != nil { + t.Fatal(err) + } + waitProject(t, c, func(p proto.ProjectInfo) bool { return p.ID == proj.ID && resolveOf(p, wt) != nil }) + os.WriteFile(filepath.Join(wt, "a.txt"), []byte("main\nfeat\n"), 0o644) + git(t, wt, "add", "a.txt") + cmd = exec.Command("git", "-C", wt, "rebase", "--continue") + cmd.Env = append(os.Environ(), "GIT_EDITOR=true", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("continue: %v\n%s", err, out) + } + waitProject(t, c, func(p proto.ProjectInfo) bool { + for _, w := range p.Worktrees { + if w.Path == wt { + return w.Branch == "feat" && w.Resolve == nil + } + } + return false + }) + + wantErr(t, call(t, c, proto.MethodBranchResolving, proto.BranchResolvingParams{ProjectID: proj.ID, Branch: "feat", PaneID: "nope"}, nil), "no pane") + wantErr(t, call(t, c, proto.MethodBranchResolving, proto.BranchResolvingParams{ProjectID: proj.ID, Branch: "nope", PaneID: pane.ID}, nil), "not checked out") + wantErr(t, call(t, c, proto.MethodBranchResolving, proto.BranchResolvingParams{ProjectID: proj.ID, PaneID: pane.ID}, nil), "") + wantErr(t, call(t, c, proto.MethodBranchResolving, proto.BranchResolvingParams{ProjectID: "nope", Branch: "feat"}, nil), "") +} diff --git a/internal/server/scope.go b/internal/server/scope.go index 867127fa..02d910f5 100644 --- a/internal/server/scope.go +++ b/internal/server/scope.go @@ -123,6 +123,8 @@ var scoped = map[string]scopeKind{ proto.MethodWorktreeRemove: scopeProject, proto.MethodWorktreeCleanup: scopeProject, proto.MethodBranchPrune: scopeProject, proto.MethodBranchCommit: scopeProject, proto.MethodBranchStage: scopeProject, proto.MethodBranchReview: scopeProject, proto.MethodBranchPush: scopeProject, proto.MethodBranchPR: scopeProject, proto.MethodBranchMerge: scopeProject, proto.MethodBranchPRMerge: scopeProject, proto.MethodBranchDiscard: scopeProject, proto.MethodBranchGit: scopeProject, + // Running CI again spends the project's Actions minutes. + proto.MethodCIRerun: scopeProject, proto.MethodBranchRebaseUndo: scopeProject, proto.MethodBranchResolving: scopeProject, proto.MethodServerStop: scopeServer, proto.MethodServerReload: scopeServer, // The cloud agent decides what every agent's environment is given. @@ -428,12 +430,15 @@ var verbs = map[string]string{ proto.MethodWorktreeCleanup: "clean up worktrees", proto.MethodBranchPrune: "delete old branches of", proto.MethodBranchCommit: "commit", proto.MethodBranchStage: "stage changes on", proto.MethodBranchReview: "review the pull request of", proto.MethodBranchPush: "push", proto.MethodBranchPR: "open a pull request", proto.MethodBranchMerge: "merge", proto.MethodBranchPRMerge: "merge a pull request", proto.MethodBranchDiscard: "discard a branch", - proto.MethodBranchGit: "run git", - proto.MethodTicketUpdate: "change a ticket", - proto.MethodAgentSkill: "install or remove the agents' conch skill", - proto.MethodProjectFiles: "change which local files a project copies into its worktrees", - proto.MethodProjectSetup: "change the command a project runs in its new worktrees", - proto.MethodScheduleAdd: "schedule a message or a task", proto.MethodScheduleRemove: "remove something scheduled", + proto.MethodBranchGit: "run git", + proto.MethodCIRerun: "re-run the CI of", + proto.MethodBranchRebaseUndo: "undo the rebase of", + proto.MethodBranchResolving: "say who resolves", + proto.MethodTicketUpdate: "change a ticket", + proto.MethodAgentSkill: "install or remove the agents' conch skill", + proto.MethodProjectFiles: "change which local files a project copies into its worktrees", + proto.MethodProjectSetup: "change the command a project runs in its new worktrees", + proto.MethodScheduleAdd: "schedule a message or a task", proto.MethodScheduleRemove: "remove something scheduled", proto.MethodGroupSave: "change a project group", proto.MethodGroupRemove: "remove a project group", proto.MethodGroupTaskRemove: "remove a task across a group", proto.MethodGroupTaskMerge: "merge a task's pull requests", proto.MethodAgentLibrary: "change the library of MCP servers and skills", proto.MethodLibraryApply: "apply the library to the agents", proto.MethodLibraryFetch: "download a skill into the library", diff --git a/internal/server/server.go b/internal/server/server.go index df745a6c..57ade2bd 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -455,7 +455,7 @@ var slowMethods = map[string]bool{ proto.MethodProjectFiles: true, proto.MethodProjectSetup: true, proto.MethodSessionList: true, proto.MethodSessionResume: true, proto.MethodSessionDelete: true, proto.MethodSessionSearch: true, proto.MethodSessionShare: true, proto.MethodSessionExport: true, proto.MethodFSUpload: true, proto.MethodBranchCommit: true, proto.MethodBranchStage: true, proto.MethodBranchPush: true, proto.MethodBranchPR: true, - proto.MethodBranchMerge: true, proto.MethodBranchPRMerge: true, proto.MethodBranchDiscard: true, proto.MethodBranchGit: true, proto.MethodBranchCILog: true, proto.MethodAgentReply: true, proto.MethodAgentChat: true, proto.MethodAgentBackgroundStop: true, proto.MethodScheduleAdd: true, proto.MethodProjectIssues: true, proto.MethodReviewSend: true, proto.MethodAgentInterrupt: true, proto.MethodAgentAttach: true, + proto.MethodBranchMerge: true, proto.MethodBranchPRMerge: true, proto.MethodBranchDiscard: true, proto.MethodBranchGit: true, proto.MethodBranchCILog: true, proto.MethodCIStats: true, proto.MethodCIRerun: true, proto.MethodBranchRebased: true, proto.MethodBranchRebaseUndo: true, proto.MethodBranchResolving: true, proto.MethodAgentReply: true, proto.MethodAgentChat: true, proto.MethodAgentBackgroundStop: true, proto.MethodScheduleAdd: true, proto.MethodProjectIssues: true, proto.MethodReviewSend: true, proto.MethodAgentInterrupt: true, proto.MethodAgentAttach: true, proto.MethodProjectTickets: true, proto.MethodTicketGet: true, proto.MethodTicketUpdate: true, proto.MethodTicketCheck: true, proto.MethodTicketOverview: true, proto.MethodWorktreeStale: true, proto.MethodWorktreeCleanup: true, proto.MethodBranchStale: true, proto.MethodBranchPrune: true, proto.MethodProjectResolve: true, proto.MethodProjectGitInit: true, proto.MethodWorktreeDescribe: true, proto.MethodWorktreeHave: true, proto.MethodWorktreePack: true, @@ -1038,6 +1038,48 @@ func (s *Server) dispatch(c *client, msg proto.Message) (any, *proto.Error) { } return s.projects.changes(cp) + case proto.MethodAutopilotActivity: + ap, perr := decode[proto.AutopilotActivityParams](msg) + if perr != nil { + return nil, perr + } + return s.autopilotActivity(ap), nil + + case proto.MethodCIStats: + sp, perr := decode[proto.CIStatsParams](msg) + if perr != nil { + return nil, perr + } + return s.projects.ciStats(sp) + + case proto.MethodCIRerun: + rp, perr := decode[proto.CIRerunParams](msg) + if perr != nil { + return nil, perr + } + return s.projects.ciRerun(rp) + + case proto.MethodBranchRebased: + rp, perr := decode[proto.BranchRebasedParams](msg) + if perr != nil { + return nil, perr + } + return s.projects.branchRebased(rp) + + case proto.MethodBranchRebaseUndo: + up, perr := decode[proto.BranchRebaseUndoParams](msg) + if perr != nil { + return nil, perr + } + return s.projects.undoRebase(up) + + case proto.MethodBranchResolving: + rp, perr := decode[proto.BranchResolvingParams](msg) + if perr != nil { + return nil, perr + } + return s.branchResolving(rp) + case proto.MethodProjectLog: lp, perr := decode[proto.LogParams](msg) if perr != nil { diff --git a/internal/server/triage.go b/internal/server/triage.go index 5d9ec3c5..23f93d6b 100644 --- a/internal/server/triage.go +++ b/internal/server/triage.go @@ -274,6 +274,8 @@ func (s *Server) triageStart(ctx context.Context, p *project, rec triageRecord, rec.Pane = pi.ID b.put(rec) log.Printf("triage: %s reads #%d %q of %s", agent, rec.Issue, rec.Title, info.Name) + s.autopilotNote(proto.AutopilotNote{ProjectID: rec.Project, Kind: proto.ActivityTriage, + Text: fmt.Sprintf("%s is reading #%d %s for triage", agent, rec.Issue, rec.Title)}) } // triageVerdict is what the agent writes. @@ -324,8 +326,12 @@ func (s *Server) triageFinish(p *project, rec triageRecord, label string, pol pr b.put(rec) if rec.Failed != "" { log.Printf("triage: #%d: %s; the issue is left as it was", rec.Issue, rec.Failed) + s.autopilotNote(proto.AutopilotNote{ProjectID: rec.Project, Kind: proto.ActivityTriage, Error: true, + Text: fmt.Sprintf("triage of #%d gave no verdict: %s; the issue is left as it was", rec.Issue, rec.Failed)}) } else { log.Printf("triage: #%d is %s", rec.Issue, rec.Verdict) + s.autopilotNote(proto.AutopilotNote{ProjectID: rec.Project, Kind: proto.ActivityTriage, + Text: fmt.Sprintf("triaged #%d %s: %s", rec.Issue, rec.Title, rec.Verdict)}) } } diff --git a/macos/Sources/ConchApp/AutopilotPanel.swift b/macos/Sources/ConchApp/AutopilotPanel.swift new file mode 100644 index 00000000..152f539c --- /dev/null +++ b/macos/Sources/ConchApp/AutopilotPanel.swift @@ -0,0 +1,142 @@ +import ConchKit +import SwiftUI + +// The commit graph's Autopilot panel: what the server's autopilot does on +// its own in this project (its rules), what it is minding now, and what +// it did β€” kept by the server (autopilot.activity), so it says what +// happened while nobody was looking, and read again as it happens. + +struct AutopilotPanel: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + @ObservedObject var store: Store + + var body: some View { + let _ = look + let on = model.autopilot?.policy.anyOn == true + let minding = (model.autopilot?.branches ?? []).filter { $0.projectID == model.project } + VStack(spacing: 0) { + HStack(spacing: 8) { + Text("Autopilot").font(.ui(size: 13.5, weight: .semibold)) + Text(on ? "On" : "Off").font(.ui(size: 10.5, weight: .semibold)) + .foregroundStyle(on ? Theme.ok : Theme.muted) + .padding(.horizontal, 7).padding(.vertical, 2) + .background(Capsule().fill((on ? Theme.ok : Theme.muted).opacity(0.15))) + Spacer(minLength: 4) + Button("Settings…") { store.openSettings("git") } + .controlSize(.small) + .help("Checks & autopilot: what it does on its own, for every project") + } + .padding(.horizontal, 14).frame(height: 52) + Rectangle().fill(Theme.line).frame(height: 1) + ScrollView { + VStack(alignment: .leading, spacing: 16) { + if let p = model.autopilot?.policy { + VStack(alignment: .leading, spacing: 5) { + ForEach(Array(autopilotRules(p, project: model.project).enumerated()), id: \.offset) { _, r in + HStack(alignment: .firstTextBaseline, spacing: 7) { + Text(r.on ? "βœ“" : "–").font(.ui(size: 11, weight: .bold)) + .foregroundStyle(r.on ? Theme.ok : Theme.muted).frame(width: 10) + Text(r.text).font(.ui(size: 12)).foregroundStyle(r.on ? Theme.text : Theme.muted) + .fixedSize(horizontal: false, vertical: true) + } + .accessibilityElement(children: .combine) + } + } + } + if !minding.isEmpty { + VStack(alignment: .leading, spacing: 6) { + Text("MINDING NOW").font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(Theme.muted) + ForEach(minding, id: \.branch) { b in + Button { model.focus(branch: b.branch) } label: { + HStack(spacing: 8) { + Text(b.branch).font(.ui(size: 12, weight: .medium)).lineLimit(1).truncationMode(.middle) + Spacer(minLength: 6) + Text(b.status).font(.ui(size: 11)).foregroundStyle(b.conflicting == true || b.checkFailed == true ? Theme.warn : Theme.text2) + .lineLimit(1).truncationMode(.tail) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain).help("Show \(b.branch) in the graph") + } + } + } + Feed(model: model) + } + .padding(14) + } + } + .background(Theme.side) + .onChange(of: store.autopilotTick[model.machine] ?? 0) { _, _ in model.loadAutopilot() } + } +} + +/// What it did, a day at a time, newest first. +private struct Feed: View { + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + + var body: some View { + let _ = look + VStack(alignment: .leading, spacing: 10) { + Text("WHAT IT DID").font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(Theme.muted) + if !model.activityError.isEmpty { + Text(model.activityError).font(.ui(size: 12)).foregroundStyle(Theme.err) + .fixedSize(horizontal: false, vertical: true) + } else if model.activity.isEmpty { + Text("Nothing yet. What the autopilot does on its own in this project β€” a failed check sent to an agent, a pull request opened or merged, a conflict handed back β€” shows here, and stays after a restart.") + .font(.ui(size: 12)).foregroundStyle(Theme.muted).fixedSize(horizontal: false, vertical: true) + } + ForEach(activityDays(model.activity), id: \.title) { day in + VStack(alignment: .leading, spacing: 2) { + Text(day.title).font(.ui(size: 11.5, weight: .semibold)).foregroundStyle(Theme.text2).padding(.bottom, 4) + ForEach(Array(day.notes.enumerated()), id: \.offset) { _, n in Entry(model: model, note: n) } + } + } + } + } +} + +private struct Entry: View { + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let note: AutopilotNote + + var body: some View { + let _ = look + let tone: Color = switch note.tone { + case .done: Theme.ok + case .failed: Theme.err + case .handed: Theme.work + case .info: Theme.muted + } + HStack(alignment: .top, spacing: 9) { + Text(note.at.map { Self.time.string(from: $0) } ?? "").font(.ui(size: 10.5)).monospacedDigit() + .foregroundStyle(Theme.muted).frame(width: 36, alignment: .leading).padding(.top, 1) + Circle().fill(tone).frame(width: 7, height: 7).padding(.top, 4) + VStack(alignment: .leading, spacing: 3) { + Text(note.text).font(.ui(size: 12)).foregroundStyle(Theme.text).fixedSize(horizontal: false, vertical: true) + HStack(spacing: 6) { + if !note.kindLabel.isEmpty { + Text(note.kindLabel).font(.ui(size: 10, weight: .semibold)).foregroundStyle(tone) + .padding(.horizontal, 5).padding(.vertical, 1) + .background(RoundedRectangle(cornerRadius: 3).fill(tone.opacity(0.14))) + } + if let b = note.branch, !b.isEmpty { + Button(b) { model.focus(branch: b) } + .buttonStyle(.link).font(.ui(size: 11)).lineLimit(1) + .help("Show \(b) in the graph") + } + } + } + } + .padding(.vertical, 5) + } + + static let time: DateFormatter = { + let f = DateFormatter() + f.dateFormat = "HH:mm" + return f + }() +} diff --git a/macos/Sources/ConchApp/CIPanel.swift b/macos/Sources/ConchApp/CIPanel.swift new file mode 100644 index 00000000..6f22bd43 --- /dev/null +++ b/macos/Sources/ConchApp/CIPanel.swift @@ -0,0 +1,292 @@ +import AppKit +import ConchKit +import SwiftUI + +// The commit graph's CI panel: the project's GitHub Actions over the last +// week, two or a month β€” how often it passes, how long it takes and waits, +// how long a branch stays red, runs per day, each job's time, the jobs +// that fail and pass with nothing changed, and the failures that can be +// run again. All of it read through gh on the project's machine (ci.stats). + +struct CIPanel: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + + var body: some View { + let _ = look + VStack(spacing: 0) { + HStack(spacing: 8) { + VStack(alignment: .leading, spacing: 1) { + Text("CI pipeline").font(.ui(size: 13.5, weight: .semibold)) + Text("GitHub Actions Β· last \(model.ciDays) days Β· read with gh") + .font(.ui(size: 11)).foregroundStyle(Theme.muted).lineLimit(1) + } + Spacer(minLength: 4) + if model.ciLoading { ProgressView().controlSize(.small) } + Picker("Range", selection: $model.ciDays) { + Text("7d").tag(7) + Text("14d").tag(14) + Text("30d").tag(30) + } + .pickerStyle(.segmented).labelsHidden().fixedSize().controlSize(.small) + .onChange(of: model.ciDays) { _, _ in model.loadCI() } + } + .padding(.horizontal, 14).frame(height: 52) + Rectangle().fill(Theme.line).frame(height: 1) + ScrollView { + VStack(alignment: .leading, spacing: 16) { + if !model.ciError.isEmpty { + Text(model.ciError).font(.ui(size: 12)).foregroundStyle(Theme.err) + .fixedSize(horizontal: false, vertical: true) + } + if let s = model.ci { + Tiles(s: s) + if s.runs == 0 { + Text("No finished runs in the last \(s.days) days.").font(.ui(size: 12)).foregroundStyle(Theme.muted) + } else { + RunsPerDay(s: s) + } + if !(s.failing ?? []).isEmpty { Failing(model: model, runs: s.failing ?? []) } + if !(s.jobs ?? []).isEmpty || s.jobsPending > 0 { JobTimes(s: s) } + if !(s.flaky ?? []).isEmpty { Flaky(items: s.flaky ?? []) } + } else if model.ciError.isEmpty { + ProgressView().controlSize(.small).frame(maxWidth: .infinity) + } + } + .padding(14) + } + } + .background(Theme.side) + } +} + +/// A heading and a line saying how to read what follows. +private struct CISection: View { + let title: String + var note = "" + @ViewBuilder let content: Content + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(alignment: .firstTextBaseline) { + Text(title).font(.ui(size: 12.5, weight: .semibold)) + Spacer(minLength: 6) + if !note.isEmpty { Text(note).font(.ui(size: 10.5)).foregroundStyle(Theme.muted).lineLimit(1) } + } + content + } + } +} + +private struct Tiles: View { + @Environment(\.conchTheme) private var look + let s: CIStats + + var body: some View { + let _ = look + LazyVGrid(columns: [GridItem(.flexible(), spacing: 8), GridItem(.flexible(), spacing: 8)], spacing: 8) { + tile("PASS RATE", s.passRate.map { "\($0)%" } ?? "β€”", + s.passRateChange.map { $0 == 0 ? "same as before" : "\($0 > 0 ? "β–²" : "β–Ό") \(abs($0)) pts vs before" } ?? "\(s.runs) runs", + (s.passRateChange ?? 0) > 0 ? Theme.ok : (s.passRateChange ?? 0) < 0 ? Theme.err : Theme.muted) + tile("MEDIAN RUN", s.medianSeconds > 0 ? ciDuration(s.medianSeconds) : "β€”", + s.medianChange.map { $0 == 0 ? "same as before" : "\($0 < 0 ? "β–Ό" : "β–²") \(ciDuration(abs($0))) \($0 < 0 ? "faster" : "slower")" } ?? "start to finish", + (s.medianChange ?? 0) < 0 ? Theme.ok : (s.medianChange ?? 0) > 0 ? Theme.warn : Theme.muted) + tile("RED β†’ GREEN", s.redToGreenCount > 0 ? ciDuration(s.redToGreenSeconds) : "β€”", + s.redToGreenCount > 0 ? "median of \(s.redToGreenCount)" : "nothing went red", Theme.muted) + tile("IN QUEUE", s.runs > 0 ? ciDuration(s.queueSeconds) : "β€”", "median wait to start", Theme.muted) + } + } + + func tile(_ k: String, _ v: String, _ d: String, _ tone: Color) -> some View { + VStack(alignment: .leading, spacing: 2) { + Text(k).font(.ui(size: 10, weight: .semibold)).foregroundStyle(Theme.muted) + Text(v).font(.ui(size: 19, weight: .semibold)).monospacedDigit().lineLimit(1).minimumScaleFactor(0.7) + Text(d).font(.ui(size: 10.5)).foregroundStyle(tone).lineLimit(1).minimumScaleFactor(0.8) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(10) + .background(RoundedRectangle(cornerRadius: 8).fill(Theme.window)) + .overlay(RoundedRectangle(cornerRadius: 8).stroke(Theme.line)) + .accessibilityElement(children: .combine) + } +} + +/// Passed runs as green bars with failures stacked on top, one a day; +/// the top gridline is labelled with the count it stands for. +private struct RunsPerDay: View { + @Environment(\.conchTheme) private var look + let s: CIStats + static let height: Double = 96 + + var body: some View { + let _ = look + let bars = ciBars(s.daily, height: Self.height) + let top = ciAxisTop(s.daily.map { $0.passed + $0.failed }.max() ?? 0) + CISection(title: "Runs per day") { + HStack(spacing: 10) { + legend(Theme.ok, "βœ“ passed") + legend(Theme.err, "βœ• failed") + } + HStack(alignment: .bottom, spacing: 6) { + VStack(alignment: .trailing) { + Text("\(top)") + Spacer() + Text("0") + } + .font(.ui(size: 9.5)).foregroundStyle(Theme.muted).frame(height: Self.height) + ZStack(alignment: .bottom) { + VStack { + Rectangle().fill(Theme.line.opacity(0.5)).frame(height: 1) + Spacer() + Rectangle().fill(Theme.line).frame(height: 1) + } + HStack(alignment: .bottom, spacing: s.daily.count > 20 ? 2 : 4) { + ForEach(Array(s.daily.enumerated()), id: \.offset) { i, d in + VStack(spacing: 2) { + if d.failed > 0 { + UnevenRoundedRectangle(topLeadingRadius: 3, topTrailingRadius: 3).fill(Theme.err) + .frame(height: max(bars[i].failed - 1, 1)) + } + if d.passed > 0 { + UnevenRoundedRectangle(topLeadingRadius: d.failed > 0 ? 0 : 3, topTrailingRadius: d.failed > 0 ? 0 : 3) + .fill(Theme.ok).frame(height: max(bars[i].passed - 1, 1)) + } + } + .frame(maxWidth: .infinity, maxHeight: Self.height, alignment: .bottom) + .contentShape(Rectangle()) + .help("\(d.date): \(d.passed) passed, \(d.failed) failed") + } + } + } + .frame(height: Self.height) + } + HStack { + Text(s.daily.first.map { shortDate($0.date) } ?? "") + Spacer() + Text("today") + } + .font(.ui(size: 9.5)).foregroundStyle(Theme.muted).padding(.leading, 18) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel("Runs per day: \(s.passed) passed and \(s.failed) failed over \(s.days) days") + } + + func legend(_ c: Color, _ t: String) -> some View { + HStack(spacing: 4) { + RoundedRectangle(cornerRadius: 2).fill(c).frame(width: 9, height: 9) + Text(t).font(.ui(size: 10.5)).foregroundStyle(Theme.text2) + } + } + + func shortDate(_ iso: String) -> String { + let f = DateFormatter() + f.dateFormat = "yyyy-MM-dd" + guard let d = f.date(from: iso) else { return iso } + f.dateFormat = "MMM d" + return f.string(from: d) + } +} + +/// Each job's median time as a bar and its slowest tenth as a tick. +private struct JobTimes: View { + @Environment(\.conchTheme) private var look + let s: CIStats + + var body: some View { + let _ = look + let jobs = s.jobs ?? [] + let longest = Double(max(jobs.map(\.p90Seconds).max() ?? 1, 1)) + CISection(title: "Time per job", note: "bar median Β· tick slowest 10%") { + ForEach(jobs.prefix(10), id: \.name) { j in + HStack(spacing: 8) { + Text(j.name).font(.ui(size: 11.5)).foregroundStyle(Theme.text2).lineLimit(1).truncationMode(.middle) + .frame(width: 92, alignment: .leading) + GeometryReader { g in + ZStack(alignment: .leading) { + UnevenRoundedRectangle(bottomTrailingRadius: 3, topTrailingRadius: 3).fill(Theme.accent) + .frame(width: max(g.size.width * Double(j.medianSeconds) / longest, 2), height: 9) + RoundedRectangle(cornerRadius: 1).fill(Theme.muted) + .frame(width: 2, height: 15) + .offset(x: min(g.size.width * Double(j.p90Seconds) / longest, g.size.width - 2)) + } + .frame(height: g.size.height) + } + .frame(height: 16) + Text(ciDuration(j.medianSeconds)).font(.ui(size: 11)).monospacedDigit().frame(width: 50, alignment: .trailing) + if j.failed > 0 { + Text("βœ•\(j.failed)").font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(Theme.err).frame(width: 26, alignment: .trailing) + } else { + Color.clear.frame(width: 26) + } + } + .help("\(j.name): median \(ciDuration(j.medianSeconds)), slowest 10% \(ciDuration(j.p90Seconds)), failed \(j.failed) of \(j.runs)") + .accessibilityElement(children: .ignore) + .accessibilityLabel("\(j.name): median \(ciDuration(j.medianSeconds)), slowest tenth \(ciDuration(j.p90Seconds)), failed \(j.failed) of \(j.runs)") + } + if s.jobsPending > 0 { + Text("Reading the jobs of \(s.jobsPending) more run\(s.jobsPending == 1 ? "" : "s")…") + .font(.ui(size: 11)).foregroundStyle(Theme.muted) + } + } + } +} + +private struct Flaky: View { + @Environment(\.conchTheme) private var look + let items: [CIFlaky] + + var body: some View { + let _ = look + CISection(title: "Flaky", note: "failed, then passed with nothing changed") { + ForEach(items.prefix(6), id: \.name) { f in + VStack(alignment: .leading, spacing: 1) { + HStack { + Text(f.name).font(.ui(size: 11.5, design: .monospaced)).lineLimit(1).truncationMode(.middle) + Spacer(minLength: 6) + Text("\(f.times)Γ—").font(.ui(size: 11, weight: .semibold)).foregroundStyle(Theme.warn) + } + Text([f.how ?? "", f.last.map { agoText($0) } ?? ""].filter { !$0.isEmpty }.joined(separator: " Β· ")) + .font(.ui(size: 10.5)).foregroundStyle(Theme.muted).lineLimit(1) + } + .accessibilityElement(children: .combine) + } + } + } +} + +/// The failures that can be run again: each workflow's newest run on a +/// branch, where it failed. +private struct Failing: View { + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let runs: [CIRun] + + var body: some View { + let _ = look + CISection(title: "Failing now", note: "the newest run of each workflow, per branch") { + ForEach(runs.prefix(8)) { r in + HStack(spacing: 8) { + Circle().fill(Theme.err).frame(width: 7, height: 7) + VStack(alignment: .leading, spacing: 1) { + Text("\(r.workflow) Β· \(r.branch ?? "")").font(.ui(size: 12, weight: .medium)).lineLimit(1).truncationMode(.middle) + Text([r.conclusion == "timed_out" ? "timed out" : "failed", (r.attempt ?? 1) > 1 ? "attempt \(r.attempt ?? 1)" : "", + r.at.map { agoText($0) } ?? ""].filter { !$0.isEmpty }.joined(separator: " Β· ")) + .font(.ui(size: 10.5)).foregroundStyle(Theme.muted) + } + Spacer(minLength: 4) + if let u = r.url, let url = URL(string: u) { + Button { NSWorkspace.shared.open(url) } label: { LucideIcon("globe", color: Theme.muted, size: 11).padding(3).contentShape(Rectangle()) } + .buttonStyle(.plain).help("Open the run on GitHub").accessibilityLabel("Open the run on GitHub") + } + if model.canRerun { + let busy = model.rerunning[r.id] == (r.attempt ?? 1) + Button(busy ? "Re-running…" : "Re-run failed jobs") { model.rerun(run: r.id, attempt: r.attempt ?? 1) } + .controlSize(.small).disabled(busy) + .help("Runs this run's failed jobs again on GitHub, as a new attempt") + } + } + } + } + } +} diff --git a/macos/Sources/ConchApp/CommitsView.swift b/macos/Sources/ConchApp/CommitsView.swift index 1292dd35..1e67b610 100644 --- a/macos/Sources/ConchApp/CommitsView.swift +++ b/macos/Sources/ConchApp/CommitsView.swift @@ -38,6 +38,37 @@ final class CommitsModel: ObservableObject { /// The repository's remotes, as the server names them (nil: an older /// server, and origin and upstream are taken). @Published var remotes: Set? + /// How the repository stores itself (nil from an older server). + @Published var format: RepoFormat? + /// Which agent branch each commit is on, by hash. + @Published var owners: [String: String] = [:] + /// A branch picked in the side's list: the rest of the graph dims. + @Published var focusOn: String? + /// The CI panel or the autopilot's in place of the commit's β€” one at a + /// time β€” and what each shows. + @Published var showCI = false { didSet { if showCI { showAutopilot = false } } } + @Published var showAutopilot = false { didSet { if showAutopilot { showCI = false } } } + var sidePanel: Bool { showCI || showAutopilot } + @Published var activity: [AutopilotNote] = [] + @Published var autopilot: AutopilotState? + @Published var activityError = "" + private var activityReads = Latest() + @Published var ci: CIStats? + @Published var ciDays = 14 + @Published var ciError = "" + @Published var ciLoading = false + /// Runs asked to start again, by run id, with the attempt that failed: + /// the button says so until a later attempt shows up. + @Published var rerunning: [Int64: Int] = [:] + private var ciReads = Latest() + /// Branches rebased and not pushed (branch.rebased), by name. + @Published var rebases: [String: BranchRebase] = [:] + /// The rebase being reviewed in a sheet, with git range-diff's account. + @Published var reviewing: BranchRebase? + @Published var reviewError = "" + /// Branches whose rewrite is going up, or being undone. + @Published var pushing: Set = [] + private var rebaseReads = Latest() /// The graph's search: commits that do not match are dimmed, never /// taken out, so the lanes stay whole. @Published var query = "" @@ -62,6 +93,7 @@ final class CommitsModel: ObservableObject { (machine, project) = parseCommitsKey(key) ?? ("local", "") load() store.refreshProject(machine: machine, project: project) + loadAutopilot() } /// ↻: the history again, and the server asked to look at GitHub now. @@ -72,6 +104,239 @@ final class CommitsModel: ObservableObject { var count: Int { rows.count } + var projectInfo: ProjectInfo? { store.snapshots[machine]?.project(project) } + + /// The agents' branches, most urgent first. + var branches: [GraphBranch] { + guard let p = projectInfo else { return [] } + return graphBranches(p, panes: store.snapshots[machine]?.panes ?? [], rebased: rebases) + } + + /// The branch a commit is on and its entry in the side's list, if it + /// is one of the agents'. + func branch(of hash: String) -> GraphBranch? { + guard let name = owners[hash] else { return nil } + return branches.first { $0.name == name } + } + + /// Asks an agent to resolve a branch's conflict: its own, or a new one + /// of the agent named. + func askToResolve(_ b: GraphBranch, start: String? = nil) { + store.askToResolve(machine: machine, project: project, branch: b, start: start) + } + + /// Brings the agent resolving b's conflict forward. + func showResolver(_ b: GraphBranch) { + guard let p = b.resolver, p.running else { return } + store.open(ConchKit.key(machine, p.id)) + } + + var canAutopilot: Bool { store.connection(machine)?.hello?.capabilities?.contains("autopilot.v1") == true } + var canActivity: Bool { store.connection(machine)?.hello?.capabilities?.contains("autopilot.activity.v1") == true } + + /// The autopilot's policy and the branches it minds, and what it did + /// in this project, newest first. + func loadAutopilot() { + struct NoParams: Encodable {} + guard let c = store.connection(machine), canAutopilot else { return } + let n = activityReads.next() + Task { + if let st = try? await c.call("autopilot.get", NoParams(), as: AutopilotState.self), activityReads.isLatest(n) { + autopilot = st + } + guard canActivity else { + activityError = "conch on \(store.label(machine)) keeps no record of what the autopilot did: reload its server." + return + } + struct P: Encodable { var project_id: String; var limit: Int } + do { + let a = try await c.call("autopilot.activity", P(project_id: project, limit: 200), as: AutopilotActivity.self) + guard activityReads.isLatest(n) else { return } + activity = a.notes + activityError = "" + } catch { + guard activityReads.isLatest(n) else { return } + activityError = "\(error)" + } + } + } + + /// Brings a branch into view: its commits stand out, its newest picked. + func focus(branch: String) { + focusOn = branch + if let tip = branchTips(rows.map(\.commit), remotes: remotes ?? ["origin", "upstream"])[branch] { + pick(tip, shift: false) + reveal += 1 + } + } + + var canCI: Bool { store.connection(machine)?.hello?.capabilities?.contains("ci.stats.v1") == true } + var canRerun: Bool { store.connection(machine)?.hello?.capabilities?.contains("ci.rerun.v1") == true } + + /// The project's CI over ciDays. A busy repository's job times arrive + /// a few dozen runs at a time, so while the server says some are still + /// to read it is asked again, a few times. + func loadCI(again: Int = 0) { + guard let c = store.connection(machine) else { return } + guard canCI else { + ciError = "conch on \(store.label(machine)) is older than this app and can't add up CI: reload its server." + return + } + struct P: Encodable { var project_id: String; var days: Int } + ciLoading = true + let n = ciReads.next() + let days = ciDays + Task { + do { + let s = try await c.call("ci.stats", P(project_id: project, days: days), as: CIStats.self) + guard ciReads.isLatest(n) else { return } + ci = s + ciError = "" + ciLoading = false + if s.jobsPending > 0 && again < 4 { + try? await Task.sleep(for: .milliseconds(500)) + if ciReads.isLatest(n) && showCI { loadCI(again: again + 1) } + } + } catch { + guard ciReads.isLatest(n) else { return } + ciLoading = false + ciError = "\(error)" + } + } + } + + /// Runs a failed run's failed jobs again β€” the run named, or a branch's + /// newest failed one β€” and reads CI again once GitHub has it. + func rerun(run: Int64? = nil, attempt: Int = 1, branch: String? = nil) { + guard let c = store.connection(machine) else { return } + guard canRerun else { + store.error = "conch on \(store.label(machine)) is too old to re-run CI: reload its server" + return + } + struct P: Encodable { var project_id: String; var run_id: Int64?; var branch: String? } + struct R: Decodable { var run_id: Int64 } + if let run { rerunning[run] = attempt } + Task { + do { + let r = try await c.call("ci.rerun", P(project_id: project, run_id: run, branch: branch), as: R.self) + if run == nil { rerunning[r.run_id] = attempt } + store.say("Running the failed jobs again" + (branch.map { " on \($0)" } ?? "")) + store.refreshProject(machine: machine, project: project) + try? await Task.sleep(for: .seconds(4)) + if showCI { loadCI() } + } catch { + if let run { rerunning[run] = nil } + store.error = "Could not re-run CI: \(error)" + } + } + } + + var canRebased: Bool { store.connection(machine)?.hello?.capabilities?.contains("branch.rebased.v1") == true } + + /// The agents' branches rebased and not pushed. An older server has no + /// such list, and the graph goes on without it. + func loadRebases() { + guard let c = store.connection(machine), canRebased else { return } + struct P: Encodable { var project_id: String } + let n = rebaseReads.next() + Task { + guard let r = try? await c.call("branch.rebased", P(project_id: project), as: BranchRebased.self), + rebaseReads.isLatest(n) else { return } + rebases = Dictionary((r.rebases ?? []).map { ($0.branch, $0) }, uniquingKeysWith: { a, _ in a }) + // A sheet open on a rebase that was pushed or undone elsewhere. + if let open = reviewing, rebases[open.branch]?.after != open.after { reviewing = nil } + } + } + + /// Opens the review of a branch's rebase: what resolving changed. + func review(_ r: BranchRebase) { + guard let c = store.connection(machine) else { return } + struct P: Encodable { var project_id: String; var branch: String; var diff: Bool } + reviewing = r + reviewError = "" + Task { + do { + let got = try await c.call("branch.rebased", P(project_id: project, branch: r.branch, diff: true), as: BranchRebased.self) + guard reviewing?.branch == r.branch else { return } + if let fresh = got.rebases?.first { + reviewing = fresh + } else { + reviewError = "\(r.branch) is no longer a rebase waiting to be pushed: it was pushed, undone or committed to since." + } + } catch { + guard reviewing?.branch == r.branch else { return } + reviewError = "Could not read the rebase: \(error)" + } + } + } + + /// Pushes a rebased branch: over the old one the remote still has, and + /// only that, or a first push. + func pushRebase(_ r: BranchRebase) { + guard let c = store.connection(machine) else { return } + struct P: Encodable { var project_id: String; var branch: String; var over: String? } + var over: String? + switch r.push { + case .fresh: over = nil + case .over(let h): over = h + case .moved(let h): + store.error = "Somebody pushed \(String(h.prefix(8))) to \(r.branch) since it was rebased; pushing would throw that away. Bring it in first." + return + } + pushing.insert(r.branch) + Task { + defer { pushing.remove(r.branch) } + do { + try await c.call("branch.push", P(project_id: project, branch: r.branch, over: over)) + store.say("Pushed \(r.branch), rebased onto \(projectInfo?.base ?? "the base")") + if reviewing?.branch == r.branch { reviewing = nil } + rebases[r.branch] = nil + store.refreshProject(machine: machine, project: project) + loadRebases() + } catch { + store.error = "Could not push \(r.branch): \(error)" + loadRebases() + } + } + } + + /// Puts a rebased branch back where it was, after asking: the rewrite + /// stays in git's reflog, but the agent's resolution leaves the branch. + func undoRebase(_ r: BranchRebase) { + guard let c = store.connection(machine) else { return } + let a = NSAlert() + a.messageText = "Undo the rebase of \(r.branch)?" + let base = projectInfo?.base ?? "the base" + a.informativeText = "The branch goes back to \(String(r.before.prefix(8))), where it was before" + + (r.changed > 0 ? ", and its conflict with \(base) is back. " : ", behind \(base) again. ") + + "The rebased commits stay in git's reflog (\(String(r.after.prefix(8)))). A worktree with uncommitted changes is not touched." + a.addButton(withTitle: "Undo the Rebase") + a.addButton(withTitle: "Cancel") + guard a.runModal() == .alertFirstButtonReturn else { return } + struct P: Encodable { var project_id: String; var branch: String; var before: String; var after: String } + pushing.insert(r.branch) + Task { + defer { pushing.remove(r.branch) } + do { + try await c.call("branch.rebase_undo", P(project_id: project, branch: r.branch, before: r.before, after: r.after)) + store.say("Put \(r.branch) back where it was before its rebase", .info) + if reviewing?.branch == r.branch { reviewing = nil } + rebases[r.branch] = nil + store.refreshProject(machine: machine, project: project) + // The commit picked was the rewrite, gone from the graph now: + // the branch's own tip, where it is back to, instead. + focusBranch = r.branch + load() + } catch { + store.error = "Could not undo the rebase: \(error)" + } + } + } + + func handToAgent(_ c: LogCommit) { + store.handCommit(machine: machine, project: project, hash: c.hash, subject: c.subject) + } + /// Lanes the graph column is wide, the same for every row so hashes /// and subjects line up; a history wider than 16 lanes is clipped /// rather than pushing the text off the row. @@ -88,6 +353,7 @@ final class CommitsModel: ObservableObject { } struct Params: Encodable { var project_id: String; var limit: Int } loading = true + loadRebases() let n = reads.next() Task { do { @@ -97,13 +363,16 @@ final class CommitsModel: ObservableObject { rows = commitGraph(r.commits ?? []) more = r.more ?? false remotes = r.remotes.map(Set.init) + format = r.format + owners = commitOwners(r.commits ?? [], base: projectInfo?.base ?? "", remotes: remotes ?? ["origin", "upstream"]) error = "" // The branch asked for, picked and brought into view if it is // among those read; either way, asked once. if let b = focusBranch { focusBranch = nil if let hit = rows.first(where: { CommitRef.parse($0.commit.refs, remotes: remotes ?? ["origin", "upstream"]).contains { $0.name == b } }) { - selected = hit.commit.hash + // Picked as a click would, so its panel reads it too. + pick(hit.commit.hash, shift: false) reveal += 1 } } @@ -199,24 +468,42 @@ struct CommitsView: View { @ObservedObject var store: Store /// Inside a branch's git tab: no frame of its own, which the tab has. var embedded = false + /// The agents' branches beside the graph, which a narrow window can do without. + @AppStorage("commits.branches") private var showBranches = true var body: some View { HStack(spacing: 0) { - graph - if model.selected != nil { + // The CI panel takes the room the branch list had. + if showBranches && !model.sidePanel { + BranchSide(model: model, store: store).frame(minWidth: 180, idealWidth: 228, maxWidth: 228) Rectangle().fill(Theme.line).frame(width: 1) - CommitDetailPanel(model: model, store: store).frame(width: 340) + } + graph.frame(minWidth: 320) + if model.showCI { + Rectangle().fill(Theme.line).frame(width: 1) + CIPanel(model: model).frame(minWidth: 300, idealWidth: 380, maxWidth: 380) + } else if model.showAutopilot { + Rectangle().fill(Theme.line).frame(width: 1) + AutopilotPanel(model: model, store: store).frame(minWidth: 300, idealWidth: 380, maxWidth: 380) + } else if model.selected != nil { + Rectangle().fill(Theme.line).frame(width: 1) + CommitDetailPanel(model: model, store: store).frame(minWidth: 260, idealWidth: 340, maxWidth: 340) } } .background(Theme.window) .clipShape(RoundedRectangle(cornerRadius: embedded ? 0 : 9)) .overlay(RoundedRectangle(cornerRadius: 9).stroke(embedded ? .clear : Theme.line)) + .sheet(isPresented: Binding(get: { model.reviewing != nil }, set: { if !$0 { model.reviewing = nil } })) { + RebaseReviewSheet(model: model) + } } var graph: some View { VStack(spacing: 0) { header Rectangle().fill(Theme.line).frame(height: 1) + ConflictBanner(model: model) + RebasedBanner(model: model) if model.range != nil { HStack(spacing: 8) { Circle().fill(Theme.merged).frame(width: 7, height: 7) @@ -235,8 +522,10 @@ struct CommitsView: View { ScrollViewReader { reader in ScrollView { LazyVStack(spacing: 0) { + let byName = Dictionary(model.branches.map { ($0.name, $0) }, uniquingKeysWith: { a, _ in a }) ForEach(model.rows, id: \.commit.hash) { r in - CommitRow(model: model, store: store, row: r).id(r.commit.hash) + CommitRow(model: model, store: store, row: r, owner: model.owners[r.commit.hash].flatMap { byName[$0] }) + .id(r.commit.hash) } if model.canReadMore { Button("Show older commits") { model.loadMore() } @@ -259,21 +548,78 @@ struct CommitsView: View { var header: some View { let name = store.snapshots[model.machine]?.project(model.project)?.name ?? model.project return HStack(spacing: 10) { + if !model.sidePanel { + Button { showBranches.toggle() } label: { + LucideIcon("panel-left", color: showBranches ? Theme.accent : Theme.muted, size: 13).padding(3).contentShape(Rectangle()) + } + .buttonStyle(.plain).help(showBranches ? "Hide the agents' branches" : "Show the agents' branches") + .accessibilityLabel(showBranches ? "Hide the agents' branches" : "Show the agents' branches") + } LucideIcon("git-commit-horizontal", color: Theme.accent, size: 14) - Text("Commits").font(.ui(size: 13, weight: .semibold)) - Text(name).font(.ui(size: 12)).foregroundStyle(Theme.text2) - Text(model.more ? "newest \(model.count)" : "\(model.count)").font(.ui(size: 11)).foregroundStyle(Theme.muted) + Text("Commits").font(.ui(size: 13, weight: .semibold)).fixedSize() + Text(name).font(.ui(size: 12)).foregroundStyle(Theme.text2).lineLimit(1).layoutPriority(-1) + Text(model.more ? "newest \(model.count)" : "\(model.count)").font(.ui(size: 11)).foregroundStyle(Theme.muted).fixedSize() + // Left out while a panel takes the right side: the graph is + // narrow then, and the search, panels and refresh need the room. + if let f = model.format, !f.label.isEmpty, model.selected == nil, !model.sidePanel { + Text(f.git3 ? "Git 3 Β· \(f.label)" : f.label) + .font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(f.git3 ? Theme.accent : Theme.muted) + .padding(.horizontal, 7).padding(.vertical, 2) + .background(Capsule().fill((f.git3 ? Theme.accent : Theme.muted).opacity(0.14))) + .lineLimit(1) + .help(f.git3 ? "This repository is stored the way git 3 makes new ones: SHA-256 object names and reftable refs" : "Object names and refs storage") + } if model.loading { ProgressView().controlSize(.small) } - Spacer() + Spacer(minLength: 8) HStack(spacing: 6) { LucideIcon("search", color: Theme.muted, size: 11) - TextField("Search commits, hashes, authors", text: $model.query).textFieldStyle(.plain).font(.ui(size: 12)).frame(width: 220) + TextField("Search commits, hashes, authors", text: $model.query).textFieldStyle(.plain).font(.ui(size: 12)) + .frame(minWidth: 60, maxWidth: 220) } .padding(.horizontal, 8).frame(height: 24) .background(RoundedRectangle(cornerRadius: 6).fill(Theme.window)) .overlay(RoundedRectangle(cornerRadius: 6).stroke(Theme.line)) - Text("shift-click to compare").font(.ui(size: 11)).foregroundStyle(Theme.muted) - Button { model.refresh() } label: { LucideIcon("refresh-cw", size: 12).padding(4).contentShape(Rectangle()) }.buttonStyle(.plain).help("Read the history again, and its pull requests from GitHub") + // Said until a commit is picked: with its panel open the graph + // is narrow, and the search and refresh need the room. + if model.selected == nil && !model.sidePanel { + Text("shift-click to compare").font(.ui(size: 11)).foregroundStyle(Theme.muted).lineLimit(1).layoutPriority(-2) + } + if model.canAutopilot { + let on = model.autopilot?.policy.anyOn == true + Button { model.showAutopilot.toggle(); if model.showAutopilot { model.loadAutopilot() } } label: { + HStack(spacing: 5) { + Circle().fill(on ? Theme.ok : Theme.muted).frame(width: 6, height: 6) + Text("Autopilot").font(.ui(size: 11.5, weight: .semibold)) + .foregroundStyle(model.showAutopilot ? Theme.accent : Theme.text2) + } + .padding(.horizontal, 7).frame(height: 22) + .background(RoundedRectangle(cornerRadius: 6).fill(model.showAutopilot ? Theme.accent.opacity(0.16) : .clear)) + .overlay(RoundedRectangle(cornerRadius: 6).stroke(model.showAutopilot ? Theme.accent.opacity(0.5) : Theme.line)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain).fixedSize() + .help(model.showAutopilot ? "Back to the commit" : "What the autopilot does on its own here, and what it did") + .accessibilityLabel(model.showAutopilot ? "Hide the autopilot" : "Show the autopilot, \(on ? "on" : "off")") + } + if model.canCI { + Button { + model.showCI.toggle() + if model.showCI { model.loadCI() } + } label: { + HStack(spacing: 4) { + LucideIcon("zap", color: model.showCI ? Theme.accent : Theme.muted, size: 11) + Text("CI").font(.ui(size: 11.5, weight: .semibold)).foregroundStyle(model.showCI ? Theme.accent : Theme.text2) + } + .padding(.horizontal, 7).frame(height: 22) + .background(RoundedRectangle(cornerRadius: 6).fill(model.showCI ? Theme.accent.opacity(0.16) : .clear)) + .overlay(RoundedRectangle(cornerRadius: 6).stroke(model.showCI ? Theme.accent.opacity(0.5) : Theme.line)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain).fixedSize() + .help(model.showCI ? "Back to the commit" : "The project's CI: pass rate, run times, slow and flaky jobs, failures to run again") + .accessibilityLabel(model.showCI ? "Hide CI" : "Show CI") + } + Button { model.refresh() } label: { LucideIcon("refresh-cw", size: 12).padding(4).contentShape(Rectangle()) }.buttonStyle(.plain).fixedSize().help("Read the history again, and its pull requests from GitHub") } .padding(.horizontal, 12).frame(height: 40) .background(Theme.paneHeader) @@ -293,6 +639,8 @@ struct CommitRow: View { @ObservedObject var model: CommitsModel @ObservedObject var store: Store let row: GraphRow + /// The agent branch the commit is on, if any. + let owner: GraphBranch? @State private var hovering = false static let height: CGFloat = 26 @@ -303,17 +651,27 @@ struct CommitRow: View { let refs = CommitRef.parse(c.refs, remotes: model.remotes ?? ["origin", "upstream"]) let on = model.selected == c.hash let cmp = model.compareWith == c.hash + let tip = owner != nil && refs.contains { $0.name == owner?.name } let dim = !commitMatches(c, model.query) || (model.inRange.map { !$0.contains(c.hash) } ?? false) + || (model.focusOn != nil && model.owners[c.hash] != model.focusOn) HStack(spacing: 8) { GraphCell(row: row).frame(width: CGFloat(model.lanes) * Self.laneWidth + 6, height: Self.height).clipped() - Text(c.short).font(.ui(size: 11.5, design: .monospaced)).foregroundStyle(Theme.muted) + Text(c.short).font(.ui(size: 11.5, design: .monospaced)).foregroundStyle(Theme.muted).fixedSize() + // Chips and the subject share what is left, clipped rather than + // pushing the hash and the agent out of the row. + HStack(spacing: 8) { ForEach(Array(refs.enumerated()), id: \.offset) { _, r in RefChip(ref: r) } // The commit a pull request's checks run on: its CI, here too. - if let pr = model.pullRequests[c.hash] { CIChip(pr: pr, number: true) } + if let pr = model.pullRequests[c.hash] { + CIChip(pr: pr, number: true) + CIMarks(marks: ciMarks(pr)) + } + if tip, let o = owner { StateTag(state: o.state) } Text(c.subject).font(.ui(size: 12.5)).foregroundStyle(Theme.text).lineLimit(1).truncationMode(.tail) .layoutPriority(-1) - Spacer(minLength: 8) - Text(c.author ?? "").font(.ui(size: 11.5)).foregroundStyle(Theme.muted).lineLimit(1) + } + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading).clipped() + AgentCell(agent: owner?.agent, author: c.author ?? "").frame(width: 96, alignment: .leading) Text(agoText(c.time)).font(.ui(size: 11.5)).foregroundStyle(Theme.muted).frame(minWidth: 52, alignment: .trailing) } .padding(.horizontal, 10).frame(height: Self.height) @@ -322,10 +680,20 @@ struct CommitRow: View { .contentShape(Rectangle()) .onHover { hovering = $0 } .onTapGesture { model.pick(c.hash, shift: NSEvent.modifierFlags.contains(.shift)) } + .accessibilityElement(children: .combine) + .accessibilityAddTraits(.isButton) + .accessibilityAction { model.pick(c.hash, shift: false) } .help(c.hash) .contextMenu { Button("Copy Hash") { copy(c.hash) } Button("Copy Subject") { copy(c.subject) } + Button("Hand to an Agent…") { model.handToAgent(c) } + if let o = owner, o.state == .ciFailing, tip, model.canRerun { + Button("Re-run Failed Jobs") { model.rerun(branch: o.name) } + } + if let o = owner, o.state.conflicts { + Button("Ask \(o.agent?.displayName ?? "an Agent") to Resolve") { model.askToResolve(o) } + } let branches = refs.filter { $0.kind == .head || $0.kind == .branch }.map(\.name).filter { $0 != "HEAD" } if !branches.isEmpty { Divider() } ForEach(branches, id: \.self) { b in @@ -473,6 +841,17 @@ struct CommitDetailPanel: View { } } } + if model.range == nil { + if let b = model.branch(of: d.hash), b.state.conflicts { ConflictCard(model: model, branch: b) } + if let b = model.branch(of: d.hash), let r = b.rebase { RebasedCard(model: model, branch: b, rebase: r) } + HStack(spacing: 8) { + if let c = model.rows.first(where: { $0.commit.hash == d.hash })?.commit { + Button("Hand to an Agent…") { model.handToAgent(c) } + .controlSize(.small) + .help("A new branch starting at this commit, with an agent of your choice on it") + } + } + } Rectangle().fill(Theme.line).frame(height: 1) Text("FILES Β· \(d.files?.count ?? 0)").font(.ui(size: 11, weight: .semibold)).foregroundStyle(Theme.muted) ForEach(d.files ?? []) { f in @@ -524,3 +903,374 @@ func fileCodeColor(_ code: String) -> Color { default: return Theme.warn } } + +/// Who made a commit: the agent of the branch it is on, with its mark's +/// colour, or the author git has for it. +struct AgentCell: View { + @Environment(\.conchTheme) private var look + let agent: PaneInfo? + let author: String + + var body: some View { + let _ = look + HStack(spacing: 5) { + if let a = agent { + Circle().fill(agentColor(a.agent?.name).map(Theme.color) ?? Theme.muted).frame(width: 7, height: 7) + Text(a.agent?.name.capitalized ?? a.displayName).font(.ui(size: 11.5)).foregroundStyle(Theme.text2).lineLimit(1) + } else { + Text(author).font(.ui(size: 11.5)).foregroundStyle(Theme.muted).lineLimit(1) + } + } + .help(agent.map { "\($0.displayName) β€” \(author)" } ?? author) + } +} + +/// A pull request's checks as small squares on its commit: green passed, +/// red failed, an outline still running. +struct CIMarks: View { + @Environment(\.conchTheme) private var look + let marks: [CIMark] + + var body: some View { + let _ = look + HStack(spacing: 2) { + ForEach(Array(marks.enumerated()), id: \.offset) { _, m in + let tone = m.state == "pass" ? Theme.ok : m.state == "fail" ? Theme.err : Theme.warn + RoundedRectangle(cornerRadius: 2) + .fill(m.state == "pending" ? .clear : tone) + .overlay(RoundedRectangle(cornerRadius: 2).stroke(tone, lineWidth: 1.2)) + .frame(width: 8, height: 8) + .help("\(m.name): \(m.state == "pass" ? "passed" : m.state == "fail" ? "failed" : "running")") + } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(marks.map { "\($0.name) \($0.state)" }.joined(separator: ", ")) + } +} + +/// What an agent branch needs, on its newest commit. +struct StateTag: View { + @Environment(\.conchTheme) private var look + let state: GraphBranchState + + var body: some View { + let _ = look + if let (text, tone) = words { + Text(text).font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(tone).lineLimit(1) + .padding(.horizontal, 6).padding(.vertical, 1.5) + .background(Capsule().fill(tone.opacity(0.16))) + .fixedSize() + } + } + + var words: (String, Color)? { + switch state { + case .conflicted(let n): ("βœ• conflict Β· \(n) file\(n == 1 ? "" : "s")", Theme.err) + case .willConflict: ("⚠ will conflict", Theme.warn) + case .ciFailing: ("βœ• CI failed", Theme.err) + case .waiting: ("waiting for you", Theme.warn) + case .rebased: ("βœ“ rebased", Theme.ok) + case .resolving: ("resolving", Theme.work) + case .resolveWaiting: ("resolving Β· needs you", Theme.warn) + case .resolveStopped: ("βœ• resolve stopped", Theme.err) + default: nil + } + } +} + +/// The agents' branches beside the graph: each with its agent, what it +/// needs, and how far it is from the base. Picking one dims the rest of +/// the graph; picking it again brings it all back. +struct BranchSide: View { + @ObservedObject var model: CommitsModel + @ObservedObject var store: Store + + var body: some View { + let bs = model.branches + VStack(alignment: .leading, spacing: 2) { + HStack { + Text("AGENTS ON BRANCHES").font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(Theme.muted) + Spacer() + Text("\(bs.count)").font(.ui(size: 10.5)).foregroundStyle(Theme.muted) + } + .padding(.horizontal, 10).padding(.top, 12).padding(.bottom, 6) + if bs.isEmpty { + Text("No agent is working on a branch of this project. Start a task and its branch shows here.") + .font(.ui(size: 11.5)).foregroundStyle(Theme.muted).padding(.horizontal, 10) + .fixedSize(horizontal: false, vertical: true) + } + ScrollView { + VStack(spacing: 2) { + ForEach(bs, id: \.name) { b in BranchSideRow(model: model, branch: b) } + } + .padding(.horizontal, 6) + } + Spacer(minLength: 0) + if let base = model.projectInfo?.base { + HStack(spacing: 6) { + Capsule().fill(laneColor(0)).frame(width: 3, height: 12) + Text(base).font(.ui(size: 12)) + Spacer() + Text("base").font(.ui(size: 10.5)).foregroundStyle(Theme.muted) + } + .padding(.horizontal, 12).padding(.vertical, 10) + } + } + .background(Theme.side) + } +} + +struct BranchSideRow: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let branch: GraphBranch + @State private var hovering = false + + var body: some View { + let _ = look + let on = model.focusOn == branch.name + let (state, tone) = describe(branch) + HStack(spacing: 8) { + Circle().fill(agentColor(branch.agent?.agent?.name).map(Theme.color) ?? Theme.muted).frame(width: 8, height: 8) + VStack(alignment: .leading, spacing: 1) { + Text(branch.name).font(.ui(size: 12, weight: .medium)).lineLimit(1).truncationMode(.middle) + HStack(spacing: 4) { + Text(branch.agent.map { $0.agent?.name.capitalized ?? $0.displayName } ?? "no agent").foregroundStyle(Theme.muted) + Text("Β·").foregroundStyle(Theme.muted) + Text(state).foregroundStyle(tone) + } + .font(.ui(size: 10.5)).lineLimit(1) + } + Spacer(minLength: 4) + Text("↑\(branch.ahead) ↓\(branch.behind)").font(.ui(size: 10.5, design: .monospaced)) + .foregroundStyle(branch.behind > 0 && branch.state.conflicts ? tone : Theme.muted) + } + .padding(.horizontal, 8).padding(.vertical, 6) + .background(RoundedRectangle(cornerRadius: 6).fill(on ? Theme.accentDeep.opacity(0.3) : hovering ? Theme.raise : .clear)) + .contentShape(Rectangle()) + .onHover { hovering = $0 } + .onTapGesture { toggle(on) } + .accessibilityElement(children: .combine) + .accessibilityAddTraits(.isButton) + .accessibilityAction { toggle(on) } + .contextMenu { + if branch.state == .resolving || branch.state == .resolveWaiting, let r = branch.resolver { + Button("Show \(resolverName(branch) ?? r.displayName)") { model.showResolver(branch) } + } else if branch.state.conflicts { + let again = { if case .resolveStopped = branch.state { return " Again" } else { return "" } }() + Button("Ask \(branch.agent?.displayName ?? "an Agent") to Resolve" + again) { model.askToResolve(branch) } + } + if let r = branch.rebase { + Button("Review the Resolution…") { model.review(r) } + Button(r.push == .fresh ? "Push" : "Push (with Lease)") { model.pushRebase(r) } + .disabled(model.pushing.contains(r.branch) || { if case .moved = r.push { return true } else { return false } }()) + Button("Undo the Rebase…") { model.undoRebase(r) } + } + if branch.state == .ciFailing, model.canRerun { + Button("Re-run Failed Jobs") { model.rerun(branch: branch.name) } + } + Button("View Changes") { model.store.openChanges(project: key(model.machine, model.project), branch: branch.name) } + } + } + + /// Focuses the branch, or lets go of it. + func toggle(_ on: Bool) { + model.focusOn = on ? nil : branch.name + // The branch's newest commit, picked and brought into view. + if !on, let tip = branchTips(model.rows.map(\.commit), remotes: model.remotes ?? ["origin", "upstream"])[branch.name] { + model.pick(tip, shift: false) + model.reveal += 1 + } + } + + func describe(_ b: GraphBranch) -> (String, Color) { + switch b.state { + case .conflicted(let n): ("conflict Β· \(n) file\(n == 1 ? "" : "s")", Theme.err) + case .rebased: ("rebased", Theme.ok) + case .waiting: ("waiting for you", Theme.warn) + case .ciFailing: ("CI failed", Theme.err) + case .willConflict: ("will conflict", Theme.warn) + case .resolving: ("resolving", Theme.work) + case .resolveWaiting: ("needs you", Theme.warn) + case .resolveStopped: ("stopped", Theme.err) + case .working: ("working", Theme.work) + case .done: ("done", Theme.ok) + case .idle: ("idle", Theme.muted) + } + } +} + +/// Above the graph when a branch's rebase or merge stopped on conflicts: +/// what stopped, and the agent to ask β€” the branch's own, or another one +/// started in its worktree. Once one is asked, how that is going: at it, +/// waiting on the person, or stopped with the conflict still there. +struct ConflictBanner: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + + var body: some View { + let _ = look + if let b = conflictBannerBranch(model.branches) { + let base = model.projectInfo?.base ?? "the base" + let tone = resolveTone(b.state) + HStack(spacing: 10) { + if b.state == .resolving { + ProgressView().controlSize(.small).frame(width: 16) + } else { + Image(systemName: b.state == .resolveWaiting ? "hand.raised.fill" : "exclamationmark.triangle.fill").foregroundStyle(tone) + } + VStack(alignment: .leading, spacing: 1) { + Text(b.state.resolution ? resolveHeadline(b, base: base) : "\(b.name) stopped on a conflict with \(base)") + .font(.ui(size: 12.5, weight: .semibold)).lineLimit(2) + Text(b.state.resolution ? resolveDetail(b) + "." : stoppedDetail(b)) + .font(.ui(size: 11.5)).foregroundStyle(Theme.text2).lineLimit(2) + } + Spacer(minLength: 8) + switch b.state { + case .resolving, .resolveWaiting: + if let r = b.resolver, r.running { + Button(b.state == .resolveWaiting ? "Answer \(resolverName(b) ?? r.displayName)…" : "Show \(resolverName(b) ?? r.displayName)") { + model.showResolver(b) + } + .controlSize(.small).tint(Theme.accentDeep) + .help("Opens the agent's pane") + } + AnotherAgentButton(model: model, branch: b) + default: + ResolveButton(model: model, branch: b) + } + Button("View Changes") { model.store.openChanges(project: key(model.machine, model.project), branch: b.name) } + .controlSize(.small) + } + .padding(.horizontal, 12).padding(.vertical, 8) + .background(tone.opacity(0.12)) + .overlay(alignment: .bottom) { Rectangle().fill(tone.opacity(0.35)).frame(height: 1) } + .accessibilityElement(children: .contain) + // Nothing else changes when an agent just asked has not started + // in time (resolveStartGrace), or as "asked 4m ago" ages: look + // again every few seconds while an agent has it. + .task(id: b.state.resolution ? b.name : "") { + guard b.state.resolution else { return } + while !Task.isCancelled { + try? await Task.sleep(for: .seconds(5)) + model.objectWillChange.send() + } + } + } + } + + func stoppedDetail(_ b: GraphBranch) -> String { + let n = b.stoppedFiles + return "\(n) file\(n == 1 ? "" : "s") to resolve in its worktree. Nothing has been pushed." + } +} + +/// The colour of a conflict in each state: an agent at it is work in +/// hand, one asking is the person's, stuck is an error. +@MainActor func resolveTone(_ s: GraphBranchState) -> Color { + switch s { + case .resolving: Theme.work + case .resolveWaiting, .willConflict: Theme.warn + default: Theme.err + } +} + +/// Ask the branch's agent to resolve its conflict, or pick another agent +/// to start in its worktree with the same request. +struct ResolveButton: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let branch: GraphBranch + + var body: some View { + let _ = look + let startable = model.store.startable(on: model.machine) + let who = branch.agent?.agent?.name.capitalized ?? branch.agent?.displayName + Menu { + if let who { Button("Ask \(who) (on this branch)") { model.askToResolve(branch) } } + Section("Start a new agent in its worktree") { + ForEach(startable, id: \.name) { a in Button(a.title) { model.askToResolve(branch, start: a.name) } } + } + } label: { + let again = { if case .resolveStopped = branch.state { return " again" } else { return "" } }() + Text((who.map { "Ask \($0) to resolve" } ?? "Ask an agent to resolve") + again) + } primaryAction: { + if branch.agent != nil { + model.askToResolve(branch) + } else if let a = startable.first { + model.askToResolve(branch, start: a.name) + } + } + .menuStyle(.borderedButton).fixedSize().controlSize(.small).tint(Theme.accentDeep) + .help("Sends the agent the conflicting files and asks it to resolve them and run the tests. Nothing is pushed.") + } +} + +/// While one agent is resolving a conflict: hand it to another, started +/// in the branch's worktree with the same request. The first keeps +/// running β€” two agents in one checkout should not both be editing, so +/// the menu says so. +struct AnotherAgentButton: View { + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let branch: GraphBranch + + var body: some View { + let _ = look + let startable = model.store.startable(on: model.machine) + let who = resolverName(branch) ?? "the agent at it" + Menu("Another agent") { + Section("Start one in its worktree; \(who) keeps running") { + ForEach(startable, id: \.name) { a in Button(a.title) { model.askToResolve(branch, start: a.name) } } + } + } + .menuStyle(.borderedButton).fixedSize().controlSize(.small) + .disabled(startable.isEmpty) + .help("Asks a new agent, in the branch's worktree, to resolve the conflict instead. Stop \(who) first if it is still changing files.") + } +} + +/// The side panel's word on a branch that conflicts with the base: the +/// files, and an agent to ask. +struct ConflictCard: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let branch: GraphBranch + + var body: some View { + let _ = look + let stopped = branch.stopped + let resolution = branch.state.resolution + let tone = resolution ? resolveTone(branch.state) : stopped ? Theme.err : Theme.warn + let base = model.projectInfo?.base ?? "the base" + VStack(alignment: .leading, spacing: 6) { + Text(resolution ? resolveHeadline(branch, base: base) : stopped ? "Stopped on a conflict with \(base)" : "Will conflict with \(base)") + .font(.ui(size: 12.5, weight: .semibold)).foregroundStyle(tone).fixedSize(horizontal: false, vertical: true) + Text(resolution ? resolveDetail(branch) + "." + : stopped ? "The rebase or merge in \(branch.name)'s worktree is waiting for these files to be resolved." + : "\(base) changed the same lines as \(branch.name). Nothing has moved yet: git merge-tree tried it.") + .font(.ui(size: 11.5)).foregroundStyle(Theme.text2).fixedSize(horizontal: false, vertical: true) + ForEach(branch.conflicts.prefix(6), id: \.self) { f in + Text(f).font(.ui(size: 11.5, design: .monospaced)).lineLimit(1).truncationMode(.head) + } + if branch.conflicts.count > 6 { + Text("and \(branch.conflicts.count - 6) more").font(.ui(size: 11)).foregroundStyle(Theme.muted) + } + if (branch.state == .resolving || branch.state == .resolveWaiting), let r = branch.resolver, r.running { + HStack(spacing: 6) { + Button("Show \(resolverName(branch) ?? r.displayName)") { model.showResolver(branch) }.controlSize(.small) + AnotherAgentButton(model: model, branch: branch) + } + } else { + ResolveButton(model: model, branch: branch) + } + } + .padding(10) + .background(RoundedRectangle(cornerRadius: 8).fill(tone.opacity(0.10))) + .overlay(RoundedRectangle(cornerRadius: 8).stroke(tone.opacity(0.35))) + } +} diff --git a/macos/Sources/ConchApp/RebasedViews.swift b/macos/Sources/ConchApp/RebasedViews.swift new file mode 100644 index 00000000..cb899365 --- /dev/null +++ b/macos/Sources/ConchApp/RebasedViews.swift @@ -0,0 +1,238 @@ +import ConchKit +import SwiftUI + +// A branch rebased onto the base β€” an agent asked to resolve its conflict +// does this β€” and not pushed yet: said above the graph, shown beside the +// branch's commit with each commit before and after, and reviewed in a +// sheet with git range-diff's account of what resolving changed, before +// it is pushed over the old branch or put back. + +/// Says the push a rebase needs, for its button. +func pushTitle(_ r: BranchRebase) -> String { + switch r.push { + case .fresh: "Push" + case .over: "Push (with lease)" + case .moved: "Push" + } +} + +func pushHelp(_ r: BranchRebase, base: String) -> String { + switch r.push { + case .fresh: "Pushes \(r.branch) for the first time" + case .over(let h): "Replaces \(String(h.prefix(8))) on the remote with the rebased branch, and only that: anything pushed since is kept and the push refused" + case .moved(let h): "Somebody pushed \(String(h.prefix(8))) to \(r.branch) since the rebase; pushing would throw it away. Bring it in first." + } +} + +func pushBlocked(_ r: BranchRebase) -> Bool { + if case .moved = r.push { return true } + return false +} + +/// Above the graph when a branch is rebased and waiting to go up, and no +/// conflict has stopped anything (that banner comes first). +struct RebasedBanner: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + + var body: some View { + let _ = look + let bs = model.branches + if conflictBannerBranch(bs) == nil, let b = bs.first(where: { $0.rebase != nil }), let r = b.rebase { + let base = model.projectInfo?.base ?? "the base" + HStack(spacing: 10) { + Image(systemName: "checkmark.circle.fill").foregroundStyle(Theme.ok) + VStack(alignment: .leading, spacing: 1) { + Text("\(b.name) is rebased onto \(base)").font(.ui(size: 12.5, weight: .semibold)).lineLimit(1) + Text(r.summary + ". Not pushed yet.").font(.ui(size: 11.5)).foregroundStyle(Theme.text2).lineLimit(1) + } + Spacer(minLength: 8) + Button("Review…") { model.review(r) } + .controlSize(.small).buttonStyle(.borderedProminent).tint(Theme.accentDeep) + Button(pushTitle(r)) { model.pushRebase(r) } + .controlSize(.small) + .disabled(model.pushing.contains(r.branch) || pushBlocked(r)) + .help(pushHelp(r, base: base)) + } + .padding(.horizontal, 12).padding(.vertical, 8) + .background(Theme.ok.opacity(0.10)) + .overlay(alignment: .bottom) { Rectangle().fill(Theme.ok.opacity(0.35)).frame(height: 1) } + } + } +} + +/// Beside a rebased branch's commit: when and onto what, each commit +/// before and after, and what to do with it. +struct RebasedCard: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + let branch: GraphBranch + let rebase: BranchRebase + + var body: some View { + let _ = look + let base = model.projectInfo?.base ?? "the base" + let busy = model.pushing.contains(rebase.branch) + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 6) { + Text("REBASED ONTO \(base.uppercased())").font(.ui(size: 10.5, weight: .bold)).foregroundStyle(Theme.ok) + if let at = rebase.at { Text("Β· \(agoText(at))").font(.ui(size: 10.5)).foregroundStyle(Theme.muted) } + } + Text("\(rebase.branch) is on \(base) again").font(.ui(size: 13.5, weight: .semibold)) + .fixedSize(horizontal: false, vertical: true) + Text(rebase.summary + (branch.agent.map { " Β· \($0.agent?.name.capitalized ?? $0.displayName) is on this branch" } ?? "")) + .font(.ui(size: 11.5)).foregroundStyle(Theme.text2).fixedSize(horizontal: false, vertical: true) + if let cs = rebase.commits, !cs.isEmpty { + VStack(alignment: .leading, spacing: 3) { + Text("REWRITTEN COMMITS").font(.ui(size: 10.5, weight: .semibold)).foregroundStyle(Theme.muted) + ForEach(Array(cs.prefix(12).enumerated()), id: \.offset) { _, c in RewrittenRow(commit: c) } + if cs.count > 12 { + Text("and \(cs.count - 12) more").font(.ui(size: 11)).foregroundStyle(Theme.muted) + } + } + } + if case .moved(let h) = rebase.push { + Text("Somebody pushed \(String(h.prefix(8))) to \(rebase.branch) since: pushing would throw it away. Bring it in first.") + .font(.ui(size: 11.5)).foregroundStyle(Theme.warn).fixedSize(horizontal: false, vertical: true) + } + Button { model.review(rebase) } label: { + Text("Review the resolution").frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent).tint(Theme.accentDeep).controlSize(.regular) + .help("What resolving the conflict changed in each commit (git range-diff)") + HStack(spacing: 6) { + Button { model.pushRebase(rebase) } label: { Text(pushTitle(rebase)).frame(maxWidth: .infinity) } + .disabled(busy || pushBlocked(rebase)) + .help(pushHelp(rebase, base: base)) + Button { model.undoRebase(rebase) } label: { Text("Undo the rebase").frame(maxWidth: .infinity) } + .disabled(busy) + .help("Puts \(rebase.branch) back at \(String(rebase.before.prefix(8))), where it was before") + } + .controlSize(.small) + } + .padding(10) + .background(RoundedRectangle(cornerRadius: 8).fill(Theme.ok.opacity(0.08))) + .overlay(RoundedRectangle(cornerRadius: 8).stroke(Theme.ok.opacity(0.30))) + } +} + +/// One commit before β†’ after, and whether its change is what it was. +struct RewrittenRow: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + let commit: RebasedCommit + + var body: some View { + let _ = look + HStack(spacing: 6) { + Text(commit.old.map { String($0.prefix(7)) } ?? "β€”").strikethrough(commit.old != nil) + .foregroundStyle(Theme.muted) + Text("β†’").foregroundStyle(Theme.muted) + Text(commit.new.map { String($0.prefix(7)) } ?? "β€”").foregroundStyle(Theme.work) + Text(commit.subject).font(.ui(size: 11.5)).foregroundStyle(Theme.text2).lineLimit(1).truncationMode(.tail) + Spacer(minLength: 2) + if let (word, tone) = mark { + Text(word).font(.ui(size: 9.5, weight: .semibold)).foregroundStyle(tone) + .padding(.horizontal, 4).padding(.vertical, 1) + .background(RoundedRectangle(cornerRadius: 3).fill(tone.opacity(0.14))) + .fixedSize() + } + } + .font(.ui(size: 11, design: .monospaced)) + .accessibilityElement(children: .combine) + } + + var mark: (String, Color)? { + switch commit.change { + case "changed": ("resolved", Theme.warn) + case "dropped": ("dropped", Theme.muted) + case "added": ("new", Theme.work) + default: nil + } + } +} + +/// The review: git range-diff's account of the rebase, the resolution's +/// own lines marked, with the push and the undo at hand. +struct RebaseReviewSheet: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + @ObservedObject var model: CommitsModel + + var body: some View { + let _ = look + let base = model.projectInfo?.base ?? "the base" + VStack(alignment: .leading, spacing: 0) { + if let r = model.reviewing { + VStack(alignment: .leading, spacing: 4) { + Text("Review the resolution").font(.ui(size: 15, weight: .semibold)) + Text("\(r.branch) onto \(base) Β· \(r.summary)").font(.ui(size: 12)).foregroundStyle(Theme.text2) + Text("Lines marked + or βˆ’ are what the rebase changed in a commit's own diff: resolving the conflict, mostly. A commit that came across as it was shows as one line.") + .font(.ui(size: 11.5)).foregroundStyle(Theme.muted).fixedSize(horizontal: false, vertical: true) + } + .padding(16) + Rectangle().fill(Theme.line).frame(height: 1) + // Scrolling both ways centres what is smaller than the view; + // the diff starts at the top left, as text does. + GeometryReader { geo in + ScrollView([.vertical, .horizontal]) { + LazyVStack(alignment: .leading, spacing: 0) { + if !model.reviewError.isEmpty { + Text(model.reviewError).font(.ui(size: 12)).foregroundStyle(Theme.err).padding(12) + } else if let d = r.diff { + ForEach(rangeDiffLines(d)) { l in DiffOfDiffLine(line: l) } + } else { + ProgressView().controlSize(.small).padding(16) + } + } + .padding(.vertical, 8) + .frame(minWidth: geo.size.width, minHeight: geo.size.height, alignment: .topLeading) + } + } + .background(Theme.side) + Rectangle().fill(Theme.line).frame(height: 1) + HStack(spacing: 8) { + Button("Undo the Rebase…") { model.undoRebase(r) } + .disabled(model.pushing.contains(r.branch)) + Spacer() + Button("Close") { model.reviewing = nil }.keyboardShortcut(.cancelAction) + Button(pushTitle(r)) { model.pushRebase(r) } + .keyboardShortcut(.defaultAction) + .disabled(model.pushing.contains(r.branch) || pushBlocked(r) || !model.reviewError.isEmpty) + .help(pushHelp(r, base: base)) + } + .padding(12) + } + } + .frame(minWidth: 640, idealWidth: 760, minHeight: 420, idealHeight: 560) + .background(Theme.window) + } +} + +struct DiffOfDiffLine: View { + /// Read so this is drawn again when the theme changes (ThemeLook). + @Environment(\.conchTheme) private var look + let line: RangeDiffLine + + var body: some View { + let _ = look + let (fg, bg): (Color, Color) = switch line.kind { + case .commit: (Theme.text, Theme.raise) + case .hunk: (Theme.work, .clear) + case .added: (Theme.ok, Theme.ok.opacity(0.10)) + case .removed: (Theme.err, Theme.err.opacity(0.10)) + case .context: (Theme.text2, .clear) + } + Text(line.text.isEmpty ? " " : line.text) + .font(.ui(size: 11.5, weight: line.kind == .commit ? .semibold : .regular, design: .monospaced)) + .foregroundStyle(fg) + .lineLimit(1).fixedSize(horizontal: true, vertical: false) + .padding(.horizontal, 12).padding(.vertical, line.kind == .commit ? 4 : 0) + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) + .background(bg) + .padding(.top, line.kind == .commit && line.id > 0 ? 6 : 0) + .textSelection(.enabled) + } +} diff --git a/macos/Sources/ConchApp/Store.swift b/macos/Sources/ConchApp/Store.swift index c54e3607..0f44aff2 100644 --- a/macos/Sources/ConchApp/Store.swift +++ b/macos/Sources/ConchApp/Store.swift @@ -58,6 +58,9 @@ final class Store: ObservableObject { @Published var installingAgents: Set = [] /// The task being written, while its sheet is up. @Published var taskDraft: TaskDraft? + /// Counts the autopilot's notes from each machine, so a feed showing + /// that machine's reads its list again when one arrives. + @Published var autopilotTick: [String: Int] = [:] /// The machines whose TUI tabs this launch has taken in. private var viewAdopted: Set = [] /// Files the palette's search found, for the query they were found for. @@ -1776,6 +1779,8 @@ final class Store: ObservableObject { terminals.removeValue(forKey: k)?.stop() defer { updateBadge() } questions.removeValue(forKey: k) + case "autopilot.note": + autopilotTick[machine, default: 0] += 1 case "project.updated": if let p = try? dec.decode(ProjectInfo.self, from: data) { // A project added since the connection was counted, or one @@ -3191,10 +3196,12 @@ final class Store: ObservableObject { /// Starts an agent (or, without one, a terminal) and shows it in a tab /// of its own, as the TUI's c and n do. - func newPane(machine: String, cwd: String?, inProject: Bool, agent: String?) { + func newPane(machine: String, cwd: String?, inProject: Bool, agent: String?, prompt: String? = nil, + started: ((PaneInfo) -> Void)? = nil) { guard let c = conns[machine] else { return } struct Create: Encodable { var agent: String? + var prompt: String? var cwd: String? var no_project: Bool? var cols: Int? @@ -3204,12 +3211,13 @@ final class Store: ObservableObject { Task { if let agent, !(await readyAgent(agent, on: machine)) { return } do { - let p = try await c.call("pane.create", Create(agent: agent, cwd: cwd, no_project: inProject ? nil : true, + let p = try await c.call("pane.create", Create(agent: agent, prompt: prompt, cwd: cwd, no_project: inProject ? nil : true, cols: size?.cols, rows: size?.rows), as: PaneInfo.self) snapshots[machine, default: Snapshot()].upsert(p) joinWorkspace(machine: machine, pane: p) layout.open(key(machine, p.id)) focusTerminal() + started?(p) } catch { self.error = "Could not start \(agent ?? "a terminal"): \(error)" } @@ -3398,6 +3406,7 @@ final class Store: ObservableObject { var prompt: String var agent: String? var branch: String? + var base: String? } let branch = d.branch.trimmingCharacters(in: .whitespaces) taskDraft = nil @@ -3405,7 +3414,8 @@ final class Store: ObservableObject { if !d.agent.isEmpty, !(await readyAgent(d.agent, on: m)) { return } do { let p = try await c.call("task.create", Params(project_id: pr, prompt: d.prompt, agent: d.agent, - branch: branch.isEmpty ? nil : branch), as: PaneInfo.self) + branch: branch.isEmpty ? nil : branch, + base: d.base.isEmpty ? nil : d.base), as: PaneInfo.self) snapshots[m, default: Snapshot()].upsert(p) joinWorkspace(machine: m, pane: p) layout.open(key(m, p.id)) @@ -3437,6 +3447,60 @@ final class Store: ObservableObject { } } + /// Asks an agent to resolve a branch's conflict with the base: the + /// branch's own agent when it has one running (prompted as if typed), + /// else a new one of `start` in the branch's worktree, given the same + /// words as its first message. + func askToResolve(machine: String, project: String, branch: GraphBranch, start: String? = nil) { + guard let c = conns[machine], let pr = snapshots[machine]?.project(project) else { return } + let text = resolvePrompt(branch: branch.name, base: pr.base ?? "the base", files: branch.conflicts, stopped: branch.stopped) + if start == nil, let a = branch.agent { + guard c.hello?.capabilities?.contains("agent.prompt.v1") == true else { + error = "The server on \(label(machine)) predates prompting an agent; reload it" + return + } + struct Params: Encodable { var id: String; var text: String } + Task { + do { + try await c.call("agent.prompt", Params(id: a.id, text: text)) + self.say("Asked \(a.displayName) to resolve \(branch.name)") + self.noteResolving(machine: machine, project: project, branch: branch.name, pane: a.id) + } catch { self.error = "\(error)" } + } + return + } + guard let path = branchWorktree(pr, branch.name)?.path else { + error = "\(branch.name) has no worktree to start an agent in" + return + } + newPane(machine: machine, cwd: path, inProject: true, agent: start ?? startable(on: machine).first?.name, prompt: text) { p in + self.noteResolving(machine: machine, project: project, branch: branch.name, pane: p.id) + } + } + + /// Tells the server which agent is resolving branch's conflict, so the + /// graph says it is at it β€” in every client, and after the autopilot + /// looks. An older server keeps no asks: the graph then goes by an + /// agent working in the stopped worktree. + func noteResolving(machine: String, project: String, branch: String, pane: String) { + guard let c = conns[machine], c.hello?.capabilities?.contains("branch.resolving.v1") == true else { return } + struct P: Encodable { var project_id: String; var branch: String; var pane_id: String } + Task { + do { try await c.call("branch.resolving", P(project_id: project, branch: branch, pane_id: pane)) } catch { + NSLog("conch: saying %@ resolves %@: %@", pane, branch, "\(error)") + } + } + } + + /// Opens the task sheet to hand a commit to an agent: a new branch + /// starting at that commit. + func handCommit(machine: String, project: String, hash: String, subject: String) { + var d = TaskDraft(project: key(machine, project), agent: startable(on: machine).first?.name ?? "claude") + d.base = hash + d.baseLabel = "\(hash.prefix(8)) Β· \(subject)" + taskDraft = d + } + /// Sends an agent a message, as the TUI's Prompt… does: the server /// types it in and submits it. func promptAgent(_ k: String) { @@ -3645,6 +3709,11 @@ struct TaskDraft: Identifiable { var ticket = "" /// When it starts: "" now, else as `conch task -at` and the rest take it. var when = "" + /// What its branch starts from: "" for the project's base, else a + /// commit or branch β€” a commit handed to an agent from the graph β€” + /// and how to name it in the sheet. + var base = "" + var baseLabel = "" /// The team it joins: a name, "-" for none, "" for its rules'. var team = "" } diff --git a/macos/Sources/ConchApp/Views.swift b/macos/Sources/ConchApp/Views.swift index 84f56150..e3676fb5 100644 --- a/macos/Sources/ConchApp/Views.swift +++ b/macos/Sources/ConchApp/Views.swift @@ -1553,6 +1553,10 @@ struct TaskSheet: View { Text([project?.name ?? "", m == "local" ? "" : store.label(m)].filter { !$0.isEmpty }.joined(separator: " Β· ") + (project?.git == false ? " β€” not a git repository yet: Start asks whether to make it one" : " β€” on a branch and worktree of its own")) .font(.ui(size: 12)).foregroundStyle(.secondary) + if !draft.base.isEmpty { + Text("Starts from \(draft.baseLabel.isEmpty ? String(draft.base.prefix(8)) : draft.baseLabel)") + .font(.ui(size: 12)).foregroundStyle(.secondary).lineLimit(1) + } TextEditor(text: $draft.prompt) .font(.ui(size: 13)).frame(minHeight: 120) .scrollContentBackground(.hidden).padding(6) diff --git a/macos/Sources/ConchKit/AutopilotFeed.swift b/macos/Sources/ConchKit/AutopilotFeed.swift new file mode 100644 index 00000000..43d246b1 --- /dev/null +++ b/macos/Sources/ConchKit/AutopilotFeed.swift @@ -0,0 +1,184 @@ +import Foundation + +// What the server's autopilot did and is set to do, for the commit +// graph's Autopilot panel: its notes (autopilot.activity) and its policy +// (autopilot.get). + +public struct AutopilotNote: Decodable, Equatable, Sendable { + public var projectID: String + public var branch: String? + public var text: String + public var error: Bool? + public var merged: Bool? + /// ci, check, ship, merge, resolve, intake or triage; nil from an + /// older server. + public var kind: String? + public var at: Date? + + enum CodingKeys: String, CodingKey { + case branch, text, error, merged, kind, at + case projectID = "project_id" + } + + public enum Tone: Equatable, Sendable { case done, failed, handed, info } + + /// How the feed marks it: a merge done, something that failed or was + /// refused, a failure handed to an agent to fix, anything else. + public var tone: Tone { + if merged == true { return .done } + if error == true { return .failed } + if (kind == "ci" || kind == "check" || kind == "resolve") && text.contains("sent it to") { return .handed } + if kind == "resolve" && text.contains(" to resolve") { return .handed } + return .info + } + + public var kindLabel: String { + switch kind { + case "ci": "CI" + case "check": "Check" + case "ship": "Push" + case "merge": "Merge" + case "resolve": "Conflict" + case "intake": "Intake" + case "triage": "Triage" + default: "" + } + } +} + +public struct AutopilotActivity: Decodable, Sendable { + public var notes: [AutopilotNote] +} + +/// One day of the feed, newest first. +public struct ActivityDay: Equatable, Sendable { + public var title: String + public var notes: [AutopilotNote] +} + +/// The notes grouped by the day they were made, in the person's calendar: +/// Today, Yesterday, then "Nov 10" β€” and notes an older server made +/// without a time, last, under Earlier. +public func activityDays(_ notes: [AutopilotNote], now: Date = Date(), calendar: Calendar = .current) -> [ActivityDay] { + var days: [ActivityDay] = [] + var undated: [AutopilotNote] = [] + let f = DateFormatter() + f.calendar = calendar + f.timeZone = calendar.timeZone + f.locale = Locale(identifier: "en_US_POSIX") + f.dateFormat = "MMM d" + for n in notes { + guard let at = n.at else { undated.append(n); continue } + let title: String + if calendar.isDate(at, inSameDayAs: now) { + title = "Today" + } else if let y = calendar.date(byAdding: .day, value: -1, to: now), calendar.isDate(at, inSameDayAs: y) { + title = "Yesterday" + } else { + title = f.string(from: at) + } + if days.last?.title == title { days[days.count - 1].notes.append(n) } else { days.append(ActivityDay(title: title, notes: [n])) } + } + if !undated.isEmpty { days.append(ActivityDay(title: "Earlier", notes: undated)) } + return days +} + +/// The server's autopilot settings (proto.AutopilotPolicy), as much of +/// them as the panel says. +public struct AutopilotPolicy: Decodable, Equatable, Sendable { + public var autoFix: Int? + public var autoMerge: Bool? + public var autoPR: Bool? + public var autoResolve: Int? + public var requireTests: Bool? + public var maxDiff: Int? + public var checks: [String: String]? + public var intake: [String: String]? + public var triage: [String: String]? + + enum CodingKeys: String, CodingKey { + case checks, intake, triage + case autoFix = "auto_fix", autoMerge = "auto_merge", autoPR = "auto_pr", autoResolve = "auto_resolve" + case requireTests = "require_tests", maxDiff = "max_diff" + } + + /// Whether it does anything on its own at all. + public var anyOn: Bool { + (autoFix ?? 0) > 0 || autoMerge == true || autoPR == true || (autoResolve ?? 0) > 0 + || !(checks ?? [:]).isEmpty || !(intake ?? [:]).isEmpty || !(triage ?? [:]).isEmpty + } +} + +/// A branch the autopilot is minding (proto.AutopilotBranch). +public struct AutopilotBranch: Decodable, Equatable, Sendable { + public var projectID: String + public var branch: String + public var fixes: Int? + public var waiting: Bool? + public var held: String? + public var checkFailed: Bool? + public var checking: String? + public var unshipped: String? + public var conflicting: Bool? + public var resolves: Int? + + enum CodingKeys: String, CodingKey { + case branch, fixes, waiting, held, checking, unshipped, conflicting, resolves + case projectID = "project_id", checkFailed = "check_failed" + } + + /// What it is waiting on, in a few words. + public var status: String { + if conflicting == true { return "conflicts with its base" + ((resolves ?? 0) > 0 ? " Β· asked \(resolves ?? 0)Γ—" : "") } + if checking != nil { return "running the check" } + if checkFailed == true { return "check failed" } + if waiting == true { return held.map { "green, held: \($0)" } ?? "green, merging" } + if let u = unshipped { return "not pushed: \(u)" } + if (fixes ?? 0) > 0 { return "sent \(fixes ?? 0) failure\(fixes == 1 ? "" : "s") to fix" } + return "watching" + } +} + +public struct AutopilotState: Decodable, Sendable { + public var policy: AutopilotPolicy + public var branches: [AutopilotBranch]? +} + +/// One of the autopilot's rules as the panel says it. +public struct AutopilotRule: Equatable, Sendable { + public var on: Bool + public var text: String +} + +/// The policy said rule by rule, for a project: what goes back to the +/// agents, what is pushed and merged, and this project's check, intake +/// label and triage label. +public func autopilotRules(_ p: AutopilotPolicy, project: String) -> [AutopilotRule] { + let fix = p.autoFix ?? 0, resolve = p.autoResolve ?? 0 + var out = [ + AutopilotRule(on: fix > 0, text: fix > 0 ? "Failed CI and checks go back to the agent, \(fix) times at most" : "Failed CI and checks stay with you"), + AutopilotRule(on: resolve > 0, text: resolve > 0 ? "Conflicts with the base go to the agent, \(resolve) times at most" : "Conflicts with the base stay with you"), + AutopilotRule(on: p.autoPR == true, text: "Push finished branches and open their pull requests"), + AutopilotRule(on: p.autoMerge == true, text: "Merge pull requests when green"), + ] + if p.requireTests == true || (p.maxDiff ?? 0) > 0 { + var why: [String] = [] + if p.requireTests == true { why.append("without a test") } + if let m = p.maxDiff, m > 0 { why.append("over \(m) lines") } + out.append(AutopilotRule(on: true, text: "Pull requests " + why.joined(separator: " or ") + " stay drafts")) + } + if let c = p.checks?[project], !c.isEmpty { + out.append(AutopilotRule(on: true, text: "Check: \(c)")) + } else { + out.append(AutopilotRule(on: false, text: "No check for this project")) + } + if let l = p.intake?[project], !l.isEmpty { + out.append(AutopilotRule(on: true, text: "Issues with the label \(l) become queued tasks")) + } + if let l = p.triage?[project], !l.isEmpty { + out.append(AutopilotRule(on: true, text: "Triage issues labelled \(l)")) + } else { + out.append(AutopilotRule(on: false, text: "Triage: off for this project")) + } + return out +} diff --git a/macos/Sources/ConchKit/BranchGraph.swift b/macos/Sources/ConchKit/BranchGraph.swift new file mode 100644 index 00000000..eca5de2b --- /dev/null +++ b/macos/Sources/ConchKit/BranchGraph.swift @@ -0,0 +1,332 @@ +import Foundation + +// What the commit graph says about the agents' branches: which commits are +// whose, what each branch needs from the person, and what an agent is +// asked when its branch conflicts with the base. + +/// The local branches pointing at commits of a history, each at its newest: +/// "HEAD -> main" is main; a remote's branch and a tag are not branches. +public func branchTips(_ commits: [LogCommit], remotes: Set = ["origin", "upstream"]) -> [String: String] { + var tips: [String: String] = [:] + for c in commits { + for r in CommitRef.parse(c.refs, remotes: remotes) where (r.kind == .head || r.kind == .branch) && r.name != "HEAD" { + if tips[r.name] == nil { tips[r.name] = c.hash } + } + } + return tips +} + +/// Which branch each commit is on, for the graph's agent column: a +/// branch's commits are those its first parents reach before reaching the +/// base. The base's own history, and what was merged into it, is nobody's +/// branch. A branch stacked on another keeps only its own commits, since +/// the branch nearer the top claims first. +public func commitOwners(_ commits: [LogCommit], base: String, remotes: Set = ["origin", "upstream"]) -> [String: String] { + let byHash = Dictionary(commits.map { ($0.hash, $0) }, uniquingKeysWith: { a, _ in a }) + let tips = branchTips(commits, remotes: remotes) + // Everything the base reaches, by any parent. + var onBase = Set() + if let t = tips[base] { + var stack = [t] + while let h = stack.popLast() { + guard onBase.insert(h).inserted, let c = byHash[h] else { continue } + stack.append(contentsOf: c.parents ?? []) + } + } + // Newest tip first, so a stacked branch claims its commits before the + // one beneath it walks through them. + let order = Dictionary(commits.enumerated().map { ($1.hash, $0) }, uniquingKeysWith: { a, _ in a }) + var owners: [String: String] = [:] + let tipHashes = Set(tips.filter { $0.key != base }.values) + for (name, tip) in tips.sorted(by: { (order[$0.value] ?? 0, $0.key) < (order[$1.value] ?? 0, $1.key) }) where name != base { + var h: String? = tip + // Another branch's tip is where this one was stacked on it. + while let cur = h, !onBase.contains(cur), owners[cur] == nil, cur == tip || !tipHashes.contains(cur), let c = byHash[cur] { + owners[cur] = name + h = c.parents?.first + } + } + return owners +} + +/// What an agent's branch needs, most urgent first. +public enum GraphBranchState: Equatable, Sendable { + /// Its worktree stopped mid-rebase or merge with files to resolve. + case conflicted(Int) + /// The agent asked to resolve its conflict stopped, the conflict still + /// there β€” or ended, its pane gone. + case resolveStopped(ended: Bool) + /// The agent asked to resolve its conflict is waiting for the person. + case resolveWaiting + /// Rebased onto the base β€” a conflict resolved β€” and not pushed: the + /// remote still has the old commits. + case rebased + /// Its agent is waiting for the person. + case waiting + /// Its pull request's checks failed. + case ciFailing + /// Merging it into the base would conflict (git merge-tree), though + /// nothing has moved yet. + case willConflict + /// An agent is resolving its conflict with the base. + case resolving + case working + case done + case idle + + /// Sorts the side's list: lower comes first. + public var urgency: Int { + switch self { + case .conflicted: 0 + case .resolveStopped: 1 + case .resolveWaiting: 2 + case .rebased: 3 + case .waiting: 4 + case .ciFailing: 5 + case .willConflict: 6 + case .resolving: 7 + case .working: 8 + case .done: 9 + case .idle: 10 + } + } + + /// Whether the branch conflicts with the base: stuck, coming, or in + /// an agent's hands. + public var conflicts: Bool { + switch self { + case .conflicted, .willConflict, .resolving, .resolveWaiting, .resolveStopped: true + default: false + } + } + + /// Whether an agent is, or was, asked to resolve it: the banner and + /// card say how that is going rather than offer to ask. + public var resolution: Bool { + switch self { + case .resolving, .resolveWaiting, .resolveStopped: true + default: false + } + } +} + +/// An agent's branch as the graph's side lists it. +public struct GraphBranch: Equatable, Sendable { + public var name: String + /// The agent working on it, if one is running. + public var agent: PaneInfo? + public var state: GraphBranchState + /// Commits ahead of and behind the base. + public var ahead: Int + public var behind: Int + /// The files merging it into the base would conflict in. + public var conflicts: [String] + public var pr: PRInfo? + /// Its rebase not yet pushed (branch.rebased). + public var rebase: BranchRebase? + /// The files its worktree, stopped mid-rebase or merge, still has to + /// resolve. + public var stoppedFiles: Int = 0 + /// A rebase is unfinished in its worktree. + public var midRebase: Bool = false + /// Who was asked to resolve its conflict (branch.resolving), and that + /// agent's pane while it is there β€” or, from a server that keeps no + /// asks, the agent working in a worktree stopped mid-rebase. + public var ask: ResolveAsk? + public var resolver: PaneInfo? + + /// Whether its worktree stopped mid-rebase or merge on a conflict. + public var stopped: Bool { stoppedFiles > 0 || midRebase } +} + +/// How long an agent just asked has to start before not working means it +/// stopped. +public let resolveStartGrace: TimeInterval = 30 + +/// The project's agent branches β€” every branch checked out in a worktree +/// of its own, never the base or the main checkout β€” with the state each +/// is in, most urgent first and otherwise as the worktrees are listed. +/// Rebased is the server's list of branches rebased and not pushed, by +/// name. +public func graphBranches(_ project: ProjectInfo, panes: [PaneInfo], rebased: [String: BranchRebase] = [:], now: Date = Date()) -> [GraphBranch] { + let base = project.base ?? "" + let mainBranches = Set((project.worktrees ?? []).filter { $0.main == true }.compactMap(\.branch)) + let info = Dictionary((project.branches ?? []).map { ($0.name, $0) }, uniquingKeysWith: { a, _ in a }) + var out: [GraphBranch] = [] + for w in project.worktrees ?? [] where w.main != true { + // Mid-rebase git names no branch; the server says which it rewrites. + guard let name = w.branch ?? w.rebasing, !name.isEmpty, name != base, !mainBranches.contains(name), + !out.contains(where: { $0.name == name }) else { continue } + let b = info[name] + // An agent whose branch is blank (its HEAD detached mid-rebase) is + // found by the folder it works in. + let inFolder = panes.filter { p in + p.agent != nil && p.running && p.projectID == project.id && (p.branch ?? "").isEmpty + && (p.cwd == w.path || (p.cwd ?? "").hasPrefix(w.path + "/")) + } + let agent = branchAgent(branchAgents(panes, project: project.id, branch: name) + inFolder, handedTo: nil) + let pr = b?.pr.flatMap { ($0.state ?? "OPEN") == "OPEN" ? $0 : nil } + let stoppedFiles = max(w.status?.conflicts ?? 0, 0) + // An older server leaves branch nil mid-rebase; a newer one names + // it as branch too, and says operation. + let midRebase = (w.rebasing != nil && (w.branch == nil || w.branch == w.rebasing)) || w.operation == "rebase" + let stopped = stoppedFiles > 0 || midRebase + let conflicting = stopped || !(w.conflicts ?? []).isEmpty + // The agent at its conflict: the one asked, while its pane is + // there; else, from a server keeping no asks, one busy in a + // worktree stopped mid-rebase β€” nothing else is done there. + var resolver: PaneInfo? + var resolve: GraphBranchState? + if let ask = w.resolve, conflicting { + let p = panes.first { $0.id == ask.pane } + resolver = p + if let p, p.running, p.agent?.state == .working { + resolve = .resolving + } else if let p, p.running, p.agent?.state == .blocked { + resolve = .resolveWaiting + } else if let p, p.running, let at = ask.at, now.timeIntervalSince(at) < resolveStartGrace { + resolve = .resolving + } else { + resolve = .resolveStopped(ended: !(p?.running ?? false)) + } + } else if w.resolve == nil, stopped, let a = agent, a.agent?.state == .working || a.agent?.state == .blocked { + resolver = a + resolve = a.agent?.state == .working ? .resolving : .resolveWaiting + } + let state: GraphBranchState + if let resolve { + state = resolve + } else if stoppedFiles > 0 { + state = .conflicted(stoppedFiles) + } else if rebased[name] != nil { + state = .rebased + } else if agent?.agent?.state == .blocked { + state = .waiting + } else if pr?.checks == "fail" { + state = .ciFailing + } else if !(w.conflicts ?? []).isEmpty { + state = .willConflict + } else if agent?.agent?.state == .working { + state = .working + } else if agent?.agent?.state == .done { + state = .done + } else { + state = .idle + } + out.append(GraphBranch(name: name, agent: agent, state: state, ahead: b?.baseAhead ?? 0, behind: b?.baseBehind ?? 0, + conflicts: w.conflicts ?? [], pr: pr, rebase: rebased[name], stoppedFiles: stoppedFiles, + midRebase: midRebase, ask: conflicting ? w.resolve : nil, resolver: resolver)) + } + return out.enumerated().sorted { ($0.element.state.urgency, $0.offset) < ($1.element.state.urgency, $1.offset) }.map(\.element) +} + +/// What an agent is asked when its branch conflicts with the base: finish +/// the rebase that stopped, or bring the branch up to date before the +/// conflict reaches a pull request. Tests are run; pushing is left to the +/// person or the autopilot. +public func resolvePrompt(branch: String, base: String, files: [String], stopped: Bool) -> String { + let shown = files.prefix(8).joined(separator: ", ") + let rest = files.count > 8 ? " and \(files.count - 8) more" : "" + let which = files.isEmpty ? "the conflicting files (git status lists them)" : shown + rest + if stopped { + return "The rebase of \(branch) onto \(base) stopped on conflicts in \(which). Resolve each one, keeping what both sides meant, " + + "run the tests that cover those files, then git add them and git rebase --continue. Say what you kept from each side." + } + return "Rebase \(branch) onto \(base): it will conflict in \(which). Resolve each conflict, keeping what both sides meant, " + + "run the tests that cover those files, and say what you kept from each side." +} + +/// One of a pull request's checks, as a mark on the commit it ran on. +public struct CIMark: Equatable, Sendable { + public var name: String + /// pass, fail or pending. + public var state: String + public var url: String? +} + +/// A pull request's checks as marks: failures first, then those still +/// running, then passes, a handful at most so a row stays a row. +public func ciMarks(_ pr: PRInfo, limit: Int = 8) -> [CIMark] { + let rank = ["fail": 0, "pending": 1, "pass": 2] + let runs = (pr.runs ?? []).enumerated().sorted { + (rank[$0.element.state] ?? 3, $0.offset) < (rank[$1.element.state] ?? 3, $1.offset) + } + return runs.prefix(limit).map { CIMark(name: $0.element.name, state: $0.element.state, url: $0.element.url) } +} + +/// How a repository stores itself (project.log's format): git 3 makes new +/// ones SHA-256 with reftable refs. +public struct RepoFormat: Decodable, Equatable, Sendable { + public var objects: String? + public var refs: String? + + public init(objects: String?, refs: String?) { + self.objects = objects + self.refs = refs + } + + public var git3: Bool { objects == "sha256" } + + /// "SHA-256 Β· reftable", or "" when the server did not say. + public var label: String { + guard let o = objects, !o.isEmpty else { return "" } + let hash = o == "sha256" ? "SHA-256" : o == "sha1" ? "SHA-1" : o + return refs.map { "\(hash) Β· \($0)" } ?? hash + } +} + +/// The agent resolving a branch's conflict, by name: "Claude". +public func resolverName(_ b: GraphBranch) -> String? { + guard let p = b.resolver else { return nil } + return p.agent?.name.capitalized ?? p.displayName +} + +/// The banner's line on a branch whose conflict is in an agent's hands. +public func resolveHeadline(_ b: GraphBranch, base: String) -> String { + let who = resolverName(b) ?? "The agent" + switch b.state { + case .resolving: return "\(who) is resolving the conflict with \(base)" + case .resolveWaiting: return "\(who) is waiting on you while resolving \(b.name)" + case .resolveStopped(ended: true): return "The agent resolving \(b.name) ended; it still conflicts with \(base)" + case .resolveStopped(ended: false): return "\(who) stopped; \(b.name) still conflicts with \(base)" + default: return "\(b.name) conflicts with \(base)" + } +} + +/// How far it is and who asked when: "2 of 3 files left Β· you asked 4m +/// ago". +public func resolveDetail(_ b: GraphBranch, now: Date = Date()) -> String { + var parts: [String] = [] + let asked = b.ask?.files?.count ?? 0 + if b.stoppedFiles > 0 { + let n = b.stoppedFiles + parts.append(asked > n ? "\(n) of \(asked) files left" : "\(n) file\(n == 1 ? "" : "s") left") + } else if b.midRebase { + parts.append("files resolved, the rebase not finished") + } else { + parts.append("not rebased yet") + } + if let ask = b.ask, let at = ask.at { + let who = ask.by == "autopilot" ? "the autopilot" : "you" + let ago = agoText(at, now: now) + parts.append("\(who) asked \(ago == "now" ? "just now" : ago)") + } + return parts.joined(separator: " Β· ") +} + + +/// The branch the conflict banner is about: one stopped on a conflict, or +/// whose conflict is in an agent's hands β€” the most urgent, as the list is +/// sorted. nil when there is none, and the rebased banner may show. +public func conflictBannerBranch(_ bs: [GraphBranch]) -> GraphBranch? { + bs.first { b in + if case .conflicted = b.state { return true } + return b.state.resolution + } +} + +/// Where branch is checked out β€” mid-rebase too, when git names no +/// branch and the server says which one the rebase rewrites. +public func branchWorktree(_ project: ProjectInfo, _ branch: String) -> WorktreeInfo? { + (project.worktrees ?? []).first { $0.branch == branch } ?? (project.worktrees ?? []).first { $0.branch == nil && $0.rebasing == branch } +} diff --git a/macos/Sources/ConchKit/CIStats.swift b/macos/Sources/ConchKit/CIStats.swift new file mode 100644 index 00000000..7c002d3c --- /dev/null +++ b/macos/Sources/ConchKit/CIStats.swift @@ -0,0 +1,142 @@ +import Foundation + +// A project's GitHub Actions over a period of days, as ci.stats gives it, +// and what the CI panel works out from it. + +public struct CIStats: Decodable, Equatable, Sendable { + public var days: Int + public var runs: Int + public var passed: Int + public var failed: Int + public var prevRuns: Int + public var prevPassed: Int + public var medianSeconds: Int + public var prevMedianSeconds: Int + public var queueSeconds: Int + public var redToGreenSeconds: Int + public var redToGreenCount: Int + public var daily: [CIDay] + public var jobs: [CIJob]? + public var flaky: [CIFlaky]? + public var failing: [CIRun]? + public var jobsPending: Int + + enum CodingKeys: String, CodingKey { + case days, runs, passed, failed, daily, jobs, flaky, failing + case prevRuns = "prev_runs", prevPassed = "prev_passed" + case medianSeconds = "median_seconds", prevMedianSeconds = "prev_median_seconds", queueSeconds = "queue_seconds" + case redToGreenSeconds = "red_to_green_seconds", redToGreenCount = "red_to_green_count" + case jobsPending = "jobs_pending" + } + + public init(from d: Decoder) throws { + let c = try d.container(keyedBy: CodingKeys.self) + days = try c.decode(Int.self, forKey: .days) + runs = try c.decodeIfPresent(Int.self, forKey: .runs) ?? 0 + passed = try c.decodeIfPresent(Int.self, forKey: .passed) ?? 0 + failed = try c.decodeIfPresent(Int.self, forKey: .failed) ?? 0 + prevRuns = try c.decodeIfPresent(Int.self, forKey: .prevRuns) ?? 0 + prevPassed = try c.decodeIfPresent(Int.self, forKey: .prevPassed) ?? 0 + medianSeconds = try c.decodeIfPresent(Int.self, forKey: .medianSeconds) ?? 0 + prevMedianSeconds = try c.decodeIfPresent(Int.self, forKey: .prevMedianSeconds) ?? 0 + queueSeconds = try c.decodeIfPresent(Int.self, forKey: .queueSeconds) ?? 0 + redToGreenSeconds = try c.decodeIfPresent(Int.self, forKey: .redToGreenSeconds) ?? 0 + redToGreenCount = try c.decodeIfPresent(Int.self, forKey: .redToGreenCount) ?? 0 + daily = try c.decodeIfPresent([CIDay].self, forKey: .daily) ?? [] + jobs = try c.decodeIfPresent([CIJob].self, forKey: .jobs) + flaky = try c.decodeIfPresent([CIFlaky].self, forKey: .flaky) + failing = try c.decodeIfPresent([CIRun].self, forKey: .failing) + jobsPending = try c.decodeIfPresent(Int.self, forKey: .jobsPending) ?? 0 + } + + /// The share of finished runs that passed, in whole percent; nil + /// without any. + public var passRate: Int? { runs > 0 ? Int((Double(passed) * 100 / Double(runs)).rounded()) : nil } + + /// How many points the pass rate moved from the period before; nil when + /// either has no runs. + public var passRateChange: Int? { + guard let now = passRate, prevRuns > 0 else { return nil } + return now - Int((Double(prevPassed) * 100 / Double(prevRuns)).rounded()) + } + + /// How many seconds the median run moved from the period before. + public var medianChange: Int? { + guard prevRuns > 0, prevMedianSeconds > 0, medianSeconds > 0 else { return nil } + return medianSeconds - prevMedianSeconds + } +} + +public struct CIDay: Decodable, Equatable, Sendable { + public var date: String + public var passed: Int + public var failed: Int + + public init(date: String, passed: Int, failed: Int) { + self.date = date + self.passed = passed + self.failed = failed + } +} + +public struct CIJob: Decodable, Equatable, Sendable { + public var name: String + public var runs: Int + public var failed: Int + public var medianSeconds: Int + public var p90Seconds: Int + + enum CodingKeys: String, CodingKey { + case name, runs, failed + case medianSeconds = "median_seconds", p90Seconds = "p90_seconds" + } +} + +public struct CIFlaky: Decodable, Equatable, Sendable { + public var name: String + public var times: Int + public var how: String? + public var last: Date? +} + +public struct CIRun: Decodable, Equatable, Sendable, Identifiable { + public var id: Int64 + public var workflow: String + public var branch: String? + public var sha: String? + public var conclusion: String? + public var attempt: Int? + public var url: String? + public var at: Date? +} + +/// A duration as the panel says it: "45s", "6m 42s", "1h 02m". +public func ciDuration(_ seconds: Int) -> String { + let s = max(seconds, 0) + if s < 60 { return "\(s)s" } + if s < 3600 { return s % 60 == 0 ? "\(s / 60)m" : "\(s / 60)m \(s % 60)s" } + let m = (s % 3600) / 60 + return m == 0 ? "\(s / 3600)h" : "\(s / 3600)h " + String(format: "%02dm", m) +} + +/// The top of the runs-per-day chart: the busiest day rounded up to the +/// nearest number worth labelling β€” 1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6 or 8 +/// times a power of ten, whole β€” at least 1, so the tallest bar fills +/// most of the chart. +public func ciAxisTop(_ busiest: Int) -> Int { + guard busiest > 1 else { return 1 } + var scale = 1 + while busiest > scale * 10 { scale *= 10 } + for step in [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10] { + let v = step * Double(scale) + if v == v.rounded(), Int(v) >= busiest { return Int(v) } + } + return 10 * scale +} + +/// Each day's bar, passed and failed, in points of a chart height high +/// whose top is ciAxisTop of the busiest day. +public func ciBars(_ days: [CIDay], height: Double) -> [(passed: Double, failed: Double)] { + let top = Double(ciAxisTop(days.map { $0.passed + $0.failed }.max() ?? 0)) + return days.map { (Double($0.passed) * height / top, Double($0.failed) * height / top) } +} diff --git a/macos/Sources/ConchKit/CommitGraph.swift b/macos/Sources/ConchKit/CommitGraph.swift index 608ccceb..30a04943 100644 --- a/macos/Sources/ConchKit/CommitGraph.swift +++ b/macos/Sources/ConchKit/CommitGraph.swift @@ -27,6 +27,8 @@ public struct LogResult: Decodable, Sendable { public var more: Bool? /// The repository's remotes; nil from an older server. public var remotes: [String]? + /// How the repository stores itself; nil from an older server. + public var format: RepoFormat? } /// A project's commit graph tab's key in the layout: diff --git a/macos/Sources/ConchKit/LucideIcons.swift b/macos/Sources/ConchKit/LucideIcons.swift index 92d36b09..624a02a8 100644 --- a/macos/Sources/ConchKit/LucideIcons.swift +++ b/macos/Sources/ConchKit/LucideIcons.swift @@ -72,6 +72,7 @@ public enum LucideIcons { "pencil": ["M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z", "m15 5 4 4"], "trash-2": ["M3 6h18", "M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6", "M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2", "M10 11v6", "M14 11v6"], "git-commit-horizontal": [svgCircle(12, 12, 3), svgLine(3, 12, 9, 12), svgLine(15, 12, 21, 12)], + "panel-left": [svgRect(3, 3, 18, 18, 2), svgLine(9, 3, 9, 21)], "tag": ["M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z", svgCircle(7.5, 7.5, 0.5)], "moon": ["M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"], "sun": [svgCircle(12, 12, 4), "M12 2v2", "M12 20v2", "m4.93 4.93 1.41 1.41", "m17.66 17.66 1.41 1.41", "M2 12h2", "M20 12h2", "m6.34 17.66-1.41 1.41", "m19.07 4.93-1.41 1.41"], diff --git a/macos/Sources/ConchKit/Protocol.swift b/macos/Sources/ConchKit/Protocol.swift index f0263baa..f1f0e83c 100644 --- a/macos/Sources/ConchKit/Protocol.swift +++ b/macos/Sources/ConchKit/Protocol.swift @@ -204,6 +204,13 @@ public struct WorktreeInfo: Decodable, Equatable, Sendable { /// "revert" or "am". Mid-rebase, branch is the branch being rebased, /// though git has detached HEAD (worktree.operation.v1). public var operation: String? + /// The branch a rebase left unfinished here is rewriting: git detaches + /// HEAD meanwhile. A server with worktree.operation.v1 names it as + /// branch too; an older one leaves branch nil. nil from older still. + public var rebasing: String? + /// The agent asked to resolve the branch's conflict, while it is + /// there (branch.resolving.v1). nil from an older server. + public var resolve: ResolveAsk? public init(path: String, branch: String?, main: Bool? = nil, port: Int? = nil) { self.path = path @@ -213,6 +220,22 @@ public struct WorktreeInfo: Decodable, Equatable, Sendable { } } +/// An agent asked to resolve a branch's conflict: its pane, who asked +/// ("autopilot", or nil for the person), when, and the files then. +public struct ResolveAsk: Decodable, Equatable, Sendable { + public var pane: String + public var by: String? + public var at: Date? + public var files: [String]? + + public init(pane: String, by: String? = nil, at: Date? = nil, files: [String]? = nil) { + self.pane = pane + self.by = by + self.at = at + self.files = files + } +} + /// One check of a pull request: state is pass, fail or pending. /// Not Identifiable by name: a name can repeat across workflows. public struct PRCheck: Decodable, Equatable, Sendable { diff --git a/macos/Sources/ConchKit/Rebased.swift b/macos/Sources/ConchKit/Rebased.swift new file mode 100644 index 00000000..7d42b2d0 --- /dev/null +++ b/macos/Sources/ConchKit/Rebased.swift @@ -0,0 +1,108 @@ +import Foundation + +// A branch rebased and not pushed yet (branch.rebased): an agent asked to +// resolve a conflict with the base leaves one. The remote still has the +// old commits, so before it goes up the person can see what resolving +// the conflict changed, push it over the old with a lease, or undo it. + +public struct BranchRebased: Decodable, Sendable { + public var rebases: [BranchRebase]? +} + +public struct BranchRebase: Decodable, Equatable, Sendable { + public var branch: String + public var before: String + public var after: String + public var onto: String + public var at: Date? + public var commits: [RebasedCommit]? + /// What the remote has for the branch, as the checkout last saw it. + public var remote: String? + /// git range-diff's account, when asked for. + public var diff: String? + + /// How a push of the rewrite would go. + public enum Push: Equatable, Sendable { + /// Never pushed: a plain push. + case fresh + /// Over the old branch the remote still has, and only that. + case over(String) + /// The remote has something else: somebody pushed since. + case moved(String) + } + + public var push: Push { + guard let r = remote, !r.isEmpty else { return .fresh } + return r == before ? .over(r) : .moved(r) + } + + public var changed: Int { (commits ?? []).filter { $0.change == "changed" }.count } + public var dropped: Int { (commits ?? []).filter { $0.change == "dropped" }.count } + + /// "3 commits rewritten Β· 1 changed resolving the conflict Β· 1 dropped". + public var summary: String { + let cs = commits ?? [] + guard !cs.isEmpty else { return "Nothing to compare" } + let n = cs.filter { $0.change != "added" }.count + var parts = ["\(n) commit\(n == 1 ? "" : "s") rewritten"] + if changed > 0 { parts.append("\(changed) changed resolving the conflict") } + if dropped > 0 { parts.append("\(dropped) dropped") } + let added = cs.count - n + if added > 0 { parts.append("\(added) added") } + return parts.joined(separator: " Β· ") + } +} + +public struct RebasedCommit: Decodable, Equatable, Sendable { + public var old: String? + public var new: String? + public var subject: String + /// same, changed, dropped or added. + public var change: String +} + +/// A line of git range-diff's account. +public struct RangeDiffLine: Equatable, Sendable, Identifiable { + public enum Kind: Equatable, Sendable { + /// "1: abc ! 1: def subject": a commit before and after. + case commit + /// A section of the diff of diffs. + case hunk + /// What the rewrite added to the commit's change, or took from it. + case added, removed + case context + } + + public var id: Int + public var kind: Kind + public var text: String +} + +/// Reads git range-diff: a commit pair's line stands alone; beneath a +/// changed one, each line is indented four, its first character saying +/// whether the rewrite added it to the commit's diff or took it away. +public func rangeDiffLines(_ text: String) -> [RangeDiffLine] { + var out: [RangeDiffLine] = [] + for raw in text.split(separator: "\n", omittingEmptySubsequences: false) { + let line = String(raw) + if line.isEmpty && out.isEmpty { continue } + let kind: RangeDiffLine.Kind + var body = line + if line.hasPrefix(" ") { + body = String(line.dropFirst(4)) + switch body.first { + case "+": kind = .added + case "-": kind = .removed + case "@": kind = .hunk + default: kind = .context + } + } else if line.isEmpty { + kind = .context + } else { + kind = .commit + } + out.append(RangeDiffLine(id: out.count, kind: kind, text: body)) + } + while out.last?.text.isEmpty == true { out.removeLast() } + return out +} diff --git a/macos/Tests/ConchKitTests/AutopilotFeedTests.swift b/macos/Tests/ConchKitTests/AutopilotFeedTests.swift new file mode 100644 index 00000000..ecabd133 --- /dev/null +++ b/macos/Tests/ConchKitTests/AutopilotFeedTests.swift @@ -0,0 +1,73 @@ +import Foundation +import Testing +@testable import ConchKit + +let activityJSON = #""" +{"notes":[ + {"project_id":"r1","branch":"conch/git3","text":"CI failed on conch/git3: sent it to claude-git3 to fix","kind":"ci","at":"2026-11-14T12:01:00Z"}, + {"project_id":"r1","branch":"conch/phone","text":"merged #234 on GitHub (squash), green","kind":"merge","merged":true,"at":"2026-11-14T11:55:00Z"}, + {"project_id":"r1","branch":"conch/graph","text":"#9 is green but GitHub would not merge it: conflict","kind":"merge","error":true,"at":"2026-11-13T18:00:00Z"}, + {"project_id":"r1","branch":"","text":"took #241 Fix the login as a queued task (label conch)","kind":"intake","at":"2026-11-10T09:12:00Z"}, + {"project_id":"r1","branch":"old","text":"from an older server"} +]} +"""# + +// The server's notes, newest first; one from an older server has no kind +// or time and still reads. +@Test func activityDecodes() throws { + let a = try conchDecoder().decode(AutopilotActivity.self, from: Data(activityJSON.utf8)) + #expect(a.notes.count == 5) + #expect(a.notes[1].merged == true && a.notes[1].kind == "merge") + #expect(a.notes[2].error == true) + #expect(a.notes[4].kind == nil && a.notes[4].at == nil) +} + +// How each note is marked: a merge done, a failure, something handed to +// an agent, the rest. +@Test func activityTones() throws { + let a = try conchDecoder().decode(AutopilotActivity.self, from: Data(activityJSON.utf8)) + #expect(a.notes[0].tone == .handed) + #expect(a.notes[1].tone == .done) + #expect(a.notes[2].tone == .failed) + #expect(a.notes[3].tone == .info) + #expect(a.notes[0].kindLabel == "CI") + #expect(a.notes[3].kindLabel == "Intake") + #expect(a.notes[4].kindLabel == "") +} + +// Grouped by day as the person's calendar has it: Today, Yesterday, then +// the date; a note without a time goes last, under Earlier. +@Test func activityByDay() throws { + let a = try conchDecoder().decode(AutopilotActivity.self, from: Data(activityJSON.utf8)) + var cal = Calendar(identifier: .gregorian) + cal.timeZone = TimeZone(identifier: "UTC")! + let now = ISO8601DateFormatter().date(from: "2026-11-14T15:00:00Z")! + let days = activityDays(a.notes, now: now, calendar: cal) + #expect(days.map(\.title) == ["Today", "Yesterday", "Nov 10", "Earlier"]) + #expect(days[0].notes.count == 2 && days[1].notes.count == 1) + #expect(activityDays([], now: now, calendar: cal).isEmpty) +} + +// The rules said in words, for the panel's top: what is on, and for this +// project its check, intake and triage labels. +@Test func autopilotRules() throws { + let p = try conchDecoder().decode(AutopilotPolicy.self, from: Data(#""" + {"auto_fix":3,"auto_merge":true,"auto_pr":false,"auto_resolve":2,"require_tests":true, + "checks":{"r1":"go test ./..."},"intake":{"r1":"conch"},"triage":{"r2":"triage"}} + """#.utf8)) + let lines = autopilotRules(p, project: "r1") + #expect(lines.first { $0.text.contains("Failed CI") }?.on == true) + #expect(lines.first { $0.text.contains("3 times") } != nil) + #expect(lines.first { $0.text.contains("Merge") }?.on == true) + #expect(lines.first { $0.text.contains("Push finished") }?.on == false) + #expect(lines.first { $0.text.contains("go test ./...") }?.on == true) + #expect(lines.first { $0.text.contains("label conch") }?.on == true) + #expect(lines.first { $0.text.contains("Triage") }?.on == false) + #expect(p.anyOn) + let off = try conchDecoder().decode(AutopilotPolicy.self, from: Data("{}".utf8)) + #expect(!off.anyOn) + #expect(autopilotRules(off, project: "r1").allSatisfy { !$0.on }) + // Another project's check and labels are not this one's. + #expect(autopilotRules(p, project: "r2").first { $0.text.hasPrefix("No check") }?.on == false) + #expect(autopilotRules(p, project: "r2").first { $0.text.contains("Triage") }?.on == true) +} diff --git a/macos/Tests/ConchKitTests/BranchGraphTests.swift b/macos/Tests/ConchKitTests/BranchGraphTests.swift new file mode 100644 index 00000000..fefd0bb6 --- /dev/null +++ b/macos/Tests/ConchKitTests/BranchGraphTests.swift @@ -0,0 +1,173 @@ +import Foundation +import Testing +@testable import ConchKit + +// The commit graph's history as conch has it: master with a merged pull +// request, and two agents' branches off it β€” one two commits long, one +// that started before the merge. +// +// u1 (conch/graph) codex +// r2 (HEAD -> conch/git3) claude +// m5 (master) merge of a2 +// r1 claude +// u0 codex +// a2 (origin/feature) +// m4 +func history() -> [LogCommit] { + [ + LogCommit(hash: "u1", parents: ["u0"], subject: "lanes", refs: ["conch/graph"]), + LogCommit(hash: "r2", parents: ["r1"], subject: "bundle", refs: ["HEAD -> conch/git3"]), + LogCommit(hash: "m5", parents: ["m4", "a2"], subject: "merge", refs: ["master", "origin/master"]), + LogCommit(hash: "r1", parents: ["m4"], subject: "stamp"), + LogCommit(hash: "u0", parents: ["m4"], subject: "model"), + LogCommit(hash: "a2", parents: ["m4"], subject: "feature", refs: ["origin/feature"]), + LogCommit(hash: "m4", parents: [], subject: "root"), + ] +} + +// Each branch's commits are what its first parents reach before the base +// does: the merged feature is master's, and so is everything below. +@Test func ownersFollowFirstParentsToTheBase() { + let owners = commitOwners(history(), base: "master") + #expect(owners["u1"] == "conch/graph") + #expect(owners["u0"] == "conch/graph") + #expect(owners["r2"] == "conch/git3") + #expect(owners["r1"] == "conch/git3") + #expect(owners["m5"] == nil && owners["a2"] == nil && owners["m4"] == nil) + #expect(branchTips(history())["conch/git3"] == "r2") + #expect(branchTips(history())["master"] == "m5") + // A remote's branch is not a tip of a local one. + #expect(branchTips(history())["origin/feature"] == nil) +} + +// A branch stacked on another keeps only its own commits; the one below +// it keeps the rest. A base that is not in the history (a log cut short, +// a base never fetched) leaves each branch everything its first parents +// reach, and an empty history owns nothing. +@Test func ownersOfStackedAndOddHistories() { + let stacked = [ + LogCommit(hash: "c3", parents: ["c2"], subject: "top", refs: ["top"]), + LogCommit(hash: "c2", parents: ["c1"], subject: "mid", refs: ["mid"]), + LogCommit(hash: "c1", parents: ["c0"], subject: "low"), + LogCommit(hash: "c0", parents: [], subject: "base", refs: ["main"]), + ] + let o = commitOwners(stacked, base: "main") + #expect(o["c3"] == "top") + #expect(o["c2"] == "mid" && o["c1"] == "mid") + #expect(o["c0"] == nil) + let noBase = commitOwners(stacked, base: "trunk") + #expect(noBase["c0"] != nil) + #expect(commitOwners([], base: "main").isEmpty) + // A parent outside the history ends the walk without a crash. + #expect(commitOwners([LogCommit(hash: "x", parents: ["gone"], subject: "", refs: ["b"])], base: "main") == ["x": "b"]) +} + +// The side's list: one entry per agent's worktree branch, never the base +// or the main checkout, each in the state that needs the person most. +@Test func graphBranchStates() throws { + let json = #""" + {"id":"r1","name":"conch","path":"/p","base":"master", + "worktrees":[{"path":"/p","branch":"master","main":true}, + {"path":"/w/a","rebasing":"stopped","status":{"files":2,"conflicts":2}}, + {"path":"/w/b","branch":"red"}, + {"path":"/w/c","branch":"forecast","conflicts":["a.go","b.go"]}, + {"path":"/w/d","branch":"asking"}, + {"path":"/w/e","branch":"busy"}, + {"path":"/w/f","branch":"quiet"}], + "branches":[{"name":"master"}, + {"name":"red","base_ahead":2,"base_behind":1,"pr":{"number":7,"state":"OPEN","checks":"fail"}}, + {"name":"forecast","base_ahead":1}]} + """# + let project = try conchDecoder().decode(ProjectInfo.self, from: Data(json.utf8)) + let panes = try conchDecoder().decode([PaneInfo].self, from: Data(#""" + [{"id":"p1","name":"a","state":"running","project_id":"r1","cwd":"/w/a/sub","agent":{"name":"codex","state":"working"}}, + {"id":"p2","name":"d","state":"running","project_id":"r1","branch":"asking","agent":{"name":"claude","state":"blocked"}}, + {"id":"p3","name":"e","state":"running","project_id":"r1","branch":"busy","agent":{"name":"gemini","state":"working"}}, + {"id":"p4","name":"other","state":"running","project_id":"r2","branch":"quiet","agent":{"name":"claude","state":"working"}}] + """#.utf8)) + let bs = graphBranches(project, panes: panes) + // stopped's agent is at its conflict, so it waits behind the rest. + #expect(bs.map(\.name) == ["asking", "red", "forecast", "stopped", "busy", "quiet"]) + let by = Dictionary(uniqueKeysWithValues: bs.map { ($0.name, $0) }) + // Mid-rebase git names no branch: the worktree says which it is + // rewriting, and its agent is found by the folder it works in. + // Its agent working there: resolving it. + #expect(by["stopped"]?.state == .resolving) + #expect(by["stopped"]?.agent?.id == "p1") + #expect(by["stopped"]?.stopped == true && by["red"]?.stopped == false) + #expect(by["red"]?.state == .ciFailing && by["red"]?.ahead == 2 && by["red"]?.behind == 1) + #expect(by["forecast"]?.state == .willConflict && by["forecast"]?.conflicts == ["a.go", "b.go"]) + #expect(by["asking"]?.state == .waiting) + #expect(by["busy"]?.state == .working) + // Another project's agent on a branch of the same name is not this one's. + #expect(by["quiet"]?.state == .idle && by["quiet"]?.agent == nil) + #expect(graphBranches(ProjectInfo(id: "x", name: "x", path: "/x"), panes: []).isEmpty) +} + +// A conflict stopped mid-rebase is the most urgent, then an agent asking, +// then red CI, then one coming: the order the side's list sorts by. +@Test func graphBranchStateOrder() { + let order: [GraphBranchState] = [.conflicted(1), .waiting, .ciFailing, .willConflict, .working, .done, .idle] + #expect(order.map(\.urgency) == order.map(\.urgency).sorted()) + #expect(Set(order.map(\.urgency)).count == order.count) +} + +// What an agent is asked: the branch, the base, the files, and to finish +// what was started β€” continue a rebase that stopped, or bring the branch +// up to date when nothing has moved yet. It never asks it to push. +@Test func resolvePromptSaysWhatToDo() { + let stopped = resolvePrompt(branch: "conch/graph", base: "master", files: ["a.go", "b.go"], stopped: true) + #expect(stopped.contains("conch/graph") && stopped.contains("master")) + #expect(stopped.contains("a.go") && stopped.contains("b.go")) + #expect(stopped.contains("--continue")) + #expect(!stopped.contains("push")) + let ahead = resolvePrompt(branch: "conch/graph", base: "master", files: ["a.go"], stopped: false) + #expect(ahead.contains("Rebase conch/graph onto master")) + #expect(!ahead.contains("--continue")) + // Many files are named a few at a time, with a count of the rest. + let many = resolvePrompt(branch: "b", base: "main", files: (1...12).map { "f\($0).go" }, stopped: true) + #expect(many.contains("f1.go") && !many.contains("f12.go") && many.contains("and 4 more")) + // No files known (an older server): it still says where to look. + #expect(resolvePrompt(branch: "b", base: "main", files: [], stopped: true).contains("git status")) +} + +// The checks of a pull request as marks on its commit, failures first, a +// few at most; none for a pull request without checks. +@Test func ciMarksFromChecks() { + var pr = PRInfo(number: 1, state: "OPEN", checks: "fail") + pr.runs = [PRCheck(name: "build", state: "pass"), PRCheck(name: "test macos", state: "fail"), + PRCheck(name: "swift", state: "pending")] + #expect(ciMarks(pr).map(\.name) == ["test macos", "swift", "build"]) + pr.runs = (1...20).map { PRCheck(name: "c\($0)", state: "pass") } + #expect(ciMarks(pr).count == 8) + #expect(ciMarks(PRInfo(number: 2)).isEmpty) +} + +// The repository's format in a word or two, git 3's shown as such. +@Test func repoFormatLabel() { + #expect(RepoFormat(objects: "sha256", refs: "reftable").label == "SHA-256 Β· reftable") + #expect(RepoFormat(objects: "sha256", refs: "reftable").git3) + #expect(!RepoFormat(objects: "sha1", refs: "files").git3) + #expect(RepoFormat(objects: "sha1", refs: "files").label == "SHA-1 Β· files") + #expect(RepoFormat(objects: nil, refs: nil).label == "") +} + +// A server with worktree.operation.v1 names the branch being rebased as +// the worktree's branch too, and its panes are on it: still stopped, even +// with no file left in conflict (an exec or a break stopped it). +@Test func graphBranchMidRebaseFromANewerServer() throws { + let project = try conchDecoder().decode(ProjectInfo.self, from: Data(#""" + {"id":"r1","name":"conch","path":"/p","base":"master", + "worktrees":[{"path":"/p","branch":"master","main":true}, + {"path":"/w/a","branch":"stopped","rebasing":"stopped","operation":"rebase","detached":true,"status":{"files":0}}, + {"path":"/w/b","branch":"merging","operation":"merge"}]} + """#.utf8)) + let panes = try conchDecoder().decode([PaneInfo].self, from: Data(#""" + [{"id":"p1","name":"a","state":"running","project_id":"r1","branch":"stopped","cwd":"/w/a","agent":{"name":"codex","state":"working"}}] + """#.utf8)) + let by = Dictionary(uniqueKeysWithValues: graphBranches(project, panes: panes).map { ($0.name, $0) }) + #expect(by["stopped"]?.stopped == true) + #expect(by["stopped"]?.agent?.id == "p1") + #expect(by["merging"]?.stopped == false) + #expect(branchWorktree(project, "stopped")?.path == "/w/a") +} diff --git a/macos/Tests/ConchKitTests/CIStatsTests.swift b/macos/Tests/ConchKitTests/CIStatsTests.swift new file mode 100644 index 00000000..d8fe4cdf --- /dev/null +++ b/macos/Tests/ConchKitTests/CIStatsTests.swift @@ -0,0 +1,71 @@ +import Foundation +import Testing +@testable import ConchKit + +let ciJSON = #""" +{"days":7,"runs":20,"passed":17,"failed":3,"prev_runs":10,"prev_passed":8, + "median_seconds":402,"prev_median_seconds":440,"queue_seconds":24, + "red_to_green_seconds":660,"red_to_green_count":3, + "daily":[{"date":"2026-11-08","passed":2,"failed":0},{"date":"2026-11-09","passed":5,"failed":1}, + {"date":"2026-11-10","passed":0,"failed":0},{"date":"2026-11-11","passed":3,"failed":2}, + {"date":"2026-11-12","passed":4,"failed":0},{"date":"2026-11-13","passed":1,"failed":0}, + {"date":"2026-11-14","passed":2,"failed":0}], + "jobs":[{"name":"test macos","runs":20,"failed":2,"median_seconds":390,"p90_seconds":610}, + {"name":"lint","runs":20,"failed":0,"median_seconds":48,"p90_seconds":61}], + "flaky":[{"name":"test macos","times":2,"how":"failed and passed on the same commit","last":"2026-11-13T10:00:00Z"}], + "failing":[{"id":42,"workflow":"ci","branch":"conch/git3","sha":"abc","conclusion":"failure","attempt":1,"url":"https://x/42","at":"2026-11-14T11:00:00Z"}], + "jobs_pending":5} +"""# + +// The server's numbers, as the panel reads them; an older server's answer +// without the optional lists still decodes. +@Test func ciStatsDecode() throws { + let s = try conchDecoder().decode(CIStats.self, from: Data(ciJSON.utf8)) + #expect(s.days == 7 && s.runs == 20 && s.passed == 17 && s.medianSeconds == 402) + #expect(s.daily.count == 7 && s.daily[3].failed == 2) + #expect(s.jobs?.first?.p90Seconds == 610) + #expect(s.failing?.first?.id == 42 && s.failing?.first?.branch == "conch/git3") + #expect(s.jobsPending == 5) + let bare = try conchDecoder().decode(CIStats.self, from: Data(#"{"days":14,"runs":0,"passed":0,"failed":0,"daily":[]}"#.utf8)) + #expect(bare.jobs == nil && bare.prevRuns == 0 && bare.jobsPending == 0) +} + +// Pass rate and its change in whole points; none without runs to compare. +@Test func ciRates() throws { + let s = try conchDecoder().decode(CIStats.self, from: Data(ciJSON.utf8)) + #expect(s.passRate == 85) + #expect(s.passRateChange == 5) // 85 now, 80 before + #expect(s.medianChange == -38) + var none = s + none.prevRuns = 0 + #expect(none.passRateChange == nil && none.medianChange == nil) + none.runs = 0 + #expect(none.passRate == nil) +} + +@Test func ciDurations() { + #expect(ciDuration(0) == "0s") + #expect(ciDuration(45) == "45s") + #expect(ciDuration(60) == "1m") + #expect(ciDuration(402) == "6m 42s") + #expect(ciDuration(3600) == "1h") + #expect(ciDuration(3725) == "1h 02m") + #expect(ciDuration(-5) == "0s") +} + +// The chart's top is a round number at or above the busiest day, so its +// gridline label means something; bars are scaled to it. +@Test func ciChartScale() { + #expect(ciAxisTop(0) == 1) + #expect(ciAxisTop(1) == 1) + #expect(ciAxisTop(6) == 6) + #expect(ciAxisTop(7) == 8) + #expect(ciAxisTop(11) == 12) + #expect(ciAxisTop(23) == 25) + #expect(ciAxisTop(130) == 150) + let days = [CIDay(date: "a", passed: 4, failed: 2), CIDay(date: "b", passed: 0, failed: 0)] + let bars = ciBars(days, height: 100) + #expect(bars[0].passed == 400.0 / 6 && bars[0].failed == 200.0 / 6) + #expect(bars[1].passed == 0 && bars[1].failed == 0) + #expect(ciBars([], height: 100).isEmpty) +} diff --git a/macos/Tests/ConchKitTests/RebasedTests.swift b/macos/Tests/ConchKitTests/RebasedTests.swift new file mode 100644 index 00000000..7b166d7c --- /dev/null +++ b/macos/Tests/ConchKitTests/RebasedTests.swift @@ -0,0 +1,83 @@ +import Foundation +import Testing +@testable import ConchKit + +let rebasedJSON = #""" +{"rebases":[ + {"branch":"conch/git-graph","before":"aaaa1111","after":"bbbb2222","onto":"cccc3333","at":"2026-11-14T12:00:00Z", + "remote":"aaaa1111", + "commits":[{"old":"a1","new":"b1","subject":"Draw merge curves","change":"changed"}, + {"old":"a2","new":"b2","subject":"Lane colours","change":"same"}, + {"old":"a3","subject":"Already on master","change":"dropped"}]}, + {"branch":"fresh","before":"d1","after":"d2","onto":"c"}, + {"branch":"raced","before":"e1","after":"e2","onto":"c","remote":"e9"} +]} +"""# + +// The server's rebases, and what pushing each means: over the old branch +// with a lease, a first push, or one somebody else pushed since. +@Test func rebasedDecodesAndPushes() throws { + let r = try conchDecoder().decode(BranchRebased.self, from: Data(rebasedJSON.utf8)) + let rs = r.rebases ?? [] + #expect(rs.count == 3) + #expect(rs[0].changed == 1 && rs[0].dropped == 1 && rs[0].at != nil) + #expect(rs[0].push == .over("aaaa1111")) + #expect(rs[1].push == .fresh && rs[1].commits == nil) + #expect(rs[2].push == .moved("e9")) + #expect(rs[0].summary == "3 commits rewritten Β· 1 changed resolving the conflict Β· 1 dropped") + #expect(rs[1].summary == "Nothing to compare") + let empty = try conchDecoder().decode(BranchRebased.self, from: Data("{}".utf8)) + #expect(empty.rebases == nil) +} + +// A rebased branch that has not gone up needs the person: after a +// conflict stopped somewhere, before anything else. +@Test func rebasedBranchState() throws { + let project = try conchDecoder().decode(ProjectInfo.self, from: Data(#""" + {"id":"r1","name":"conch","path":"/p","base":"master", + "worktrees":[{"path":"/p","branch":"master","main":true}, + {"path":"/w/a","branch":"asking"}, + {"path":"/w/b","branch":"conch/git-graph","conflicts":["a.go"]}, + {"path":"/w/c","rebasing":"stopped","status":{"files":1,"conflicts":1}}], + "branches":[{"name":"conch/git-graph","pr":{"number":3,"state":"OPEN","checks":"fail"}}]} + """#.utf8)) + let panes = try conchDecoder().decode([PaneInfo].self, from: Data(#""" + [{"id":"p2","name":"d","state":"running","project_id":"r1","branch":"asking","agent":{"name":"claude","state":"blocked"}}] + """#.utf8)) + let rs = try conchDecoder().decode(BranchRebased.self, from: Data(rebasedJSON.utf8)).rebases ?? [] + let bs = graphBranches(project, panes: panes, rebased: Dictionary(uniqueKeysWithValues: rs.map { ($0.branch, $0) })) + #expect(bs.map(\.name) == ["stopped", "conch/git-graph", "asking"]) + #expect(bs[1].state == .rebased && bs[1].rebase?.after == "bbbb2222") + #expect(!bs[1].state.conflicts) + // Without the server's word, as before. + #expect(graphBranches(project, panes: panes)[2].state == .ciFailing) + let order: [GraphBranchState] = [.conflicted(1), .rebased, .waiting] + #expect(order.map(\.urgency) == order.map(\.urgency).sorted()) +} + +// git range-diff's account, line by line: a pair of commits, the +// resolution's own additions and removals, the rest as context. +@Test func rangeDiffReads() { + let text = """ + 1: c92020d ! 1: 6e6da5d feat one + @@ Commit message + + ## f ## + @@ + - a + --b + + A + +-b2 + +B + c + 2: 860eca6 = 2: eadbc9d feat two + """ + let ls = rangeDiffLines(text) + #expect(ls.first?.kind == .commit && ls.first?.text == "1: c92020d ! 1: 6e6da5d feat one") + #expect(ls[1].kind == .hunk && ls[1].text == "@@ Commit message") + #expect(ls.filter { $0.kind == .removed }.map(\.text) == ["- a", "--b"]) + #expect(ls.filter { $0.kind == .added }.map(\.text) == ["+ A", "+-b2"]) + #expect(ls.last?.kind == .commit) + #expect(ls.contains { $0.kind == .context && $0.text == " +B" }) + #expect(rangeDiffLines("").isEmpty) +} diff --git a/macos/Tests/ConchKitTests/ResolvingTests.swift b/macos/Tests/ConchKitTests/ResolvingTests.swift new file mode 100644 index 00000000..093646a3 --- /dev/null +++ b/macos/Tests/ConchKitTests/ResolvingTests.swift @@ -0,0 +1,132 @@ +import Foundation +import Testing +@testable import ConchKit + +/// A project whose one agent branch, feat, is in the worktree given, with +/// the panes given (JSON). +private func resolving(_ worktree: String, panes: String, branches: String = #"[{"name":"main"}]"#) throws -> [GraphBranch] { + try resolving(worktree, panes: panes, branches: branches, now: Date(timeIntervalSince1970: 1_800_000_100)) +} + +private func resolving(_ worktree: String, panes: String, branches: String = #"[{"name":"main"}]"#, now: Date, + rebased: [String: BranchRebase] = [:]) throws -> [GraphBranch] { + let project = try conchDecoder().decode(ProjectInfo.self, from: Data(#""" + {"id":"r1","name":"api","path":"/p","base":"main", + "worktrees":[{"path":"/p","branch":"main","main":true},\#(worktree)], + "branches":\#(branches)} + """#.utf8)) + let ps = try conchDecoder().decode([PaneInfo].self, from: Data(panes.utf8)) + return graphBranches(project, panes: ps, rebased: rebased, now: now) +} + +// 2027-01-15T08:00:00Z is 1_800_000_000: asked 100s before now. +private let stopped = #"{"path":"/w/feat","rebasing":"feat","status":{"files":2,"conflicts":2},"conflicts":["a.go","b.go"],"resolve":{"pane":"p9","at":"2027-01-15T08:00:00Z","files":["a.go","b.go","c.go"]}}"# +private func pane(_ id: String, _ state: String, running: Bool = true) -> String { + #"{"id":"\#(id)","name":"x","state":"\#(running ? "running" : "exited")","project_id":"r1","cwd":"/w/feat","agent":{"name":"claude","state":"\#(state)"}}"# +} + +// The agent asked is at it, asks the person something, or stopped with +// the conflict still there β€” and the branch says which. +@Test func resolvingStates() throws { + let working = try resolving(stopped, panes: "[\(pane("p9", "working"))]")[0] + #expect(working.state == .resolving) + #expect(working.resolver?.id == "p9" && working.ask?.files?.count == 3) + #expect(working.stopped && working.stoppedFiles == 2 && working.state.conflicts) + + #expect(try resolving(stopped, panes: "[\(pane("p9", "blocked"))]")[0].state == .resolveWaiting) + #expect(try resolving(stopped, panes: "[\(pane("p9", "done"))]")[0].state == .resolveStopped(ended: false)) + // Its pane gone, or its program ended. + #expect(try resolving(stopped, panes: "[]")[0].state == .resolveStopped(ended: true)) + #expect(try resolving(stopped, panes: "[\(pane("p9", "idle", running: false))]")[0].state == .resolveStopped(ended: true)) + // Just asked: it has not started working yet, which is not stopping. + let soon = Date(timeIntervalSince1970: 1_800_000_010) + #expect(try resolving(stopped, panes: "[\(pane("p9", "idle"))]", now: soon)[0].state == .resolving) +} + +// Asked before anything moved β€” the branch will conflict β€” and working. +@Test func resolvingBeforeTheRebase() throws { + let coming = #"{"path":"/w/feat","branch":"feat","conflicts":["a.go"],"resolve":{"pane":"p9","by":"autopilot","at":"2027-01-15T08:00:00Z"}}"# + let b = try resolving(coming, panes: "[\(pane("p9", "working"))]")[0] + #expect(b.state == .resolving && !b.stopped && b.ask?.by == "autopilot") + // Idle long after: it stopped, the conflict still coming. + #expect(try resolving(coming, panes: "[\(pane("p9", "idle"))]")[0].state == .resolveStopped(ended: false)) +} + +// An ask whose conflict is gone is no longer news: the branch is rebased, +// or whatever else it is. +@Test func resolvedAskGivesWay() throws { + let done = #"{"path":"/w/feat","branch":"feat","resolve":{"pane":"p9","at":"2027-01-15T08:00:00Z"}}"# + let r = try conchDecoder().decode(BranchRebase.self, from: Data(#"{"branch":"feat","before":"a","after":"b","onto":"c"}"#.utf8)) + #expect(try resolving(done, panes: "[\(pane("p9", "done"))]", now: Date(), rebased: ["feat": r])[0].state == .rebased) + #expect(try resolving(done, panes: "[\(pane("p9", "working"))]")[0].state == .working) +} + +// From a server that keeps no asks: an agent working in a worktree +// stopped mid-rebase is resolving it; one doing nothing leaves it stuck. +@Test func resolvingWithoutAnAsk() throws { + let old = #"{"path":"/w/feat","rebasing":"feat","status":{"files":1,"conflicts":1}}"# + #expect(try resolving(old, panes: "[\(pane("p1", "working"))]")[0].state == .resolving) + #expect(try resolving(old, panes: "[\(pane("p1", "blocked"))]")[0].state == .resolveWaiting) + #expect(try resolving(old, panes: "[\(pane("p1", "idle"))]")[0].state == .conflicted(1)) + #expect(try resolving(old, panes: "[]")[0].state == .conflicted(1)) + // Will conflict, an agent working: it is doing its own work, not resolving. + let coming = #"{"path":"/w/feat","branch":"feat","conflicts":["a.go"]}"# + #expect(try resolving(coming, panes: "[\(pane("p1", "working"))]")[0].state == .willConflict) +} + +// Stuck needs the person most, then an agent asking, and an agent at it +// needs nobody yet. +@Test func resolvingUrgency() { + let order: [GraphBranchState] = [.conflicted(1), .resolveStopped(ended: false), .resolveWaiting, .rebased, .waiting, + .ciFailing, .willConflict, .resolving, .working, .done, .idle] + #expect(order.map(\.urgency) == order.map(\.urgency).sorted()) + #expect(Set(order.map(\.urgency)).count == order.count) + #expect(GraphBranchState.resolveStopped(ended: true).urgency == GraphBranchState.resolveStopped(ended: false).urgency) +} + +// What the banner and the card say of it. +@Test func resolvingWords() throws { + let b = try resolving(stopped, panes: "[\(pane("p9", "working"))]")[0] + #expect(resolveHeadline(b, base: "main") == "Claude is resolving the conflict with main") + #expect(resolveDetail(b, now: Date(timeIntervalSince1970: 1_800_000_100)) == "2 of 3 files left Β· you asked 1m ago") + let w = try resolving(stopped, panes: "[\(pane("p9", "blocked"))]")[0] + #expect(resolveHeadline(w, base: "main") == "Claude is waiting on you while resolving feat") + let s = try resolving(stopped, panes: "[\(pane("p9", "done"))]")[0] + #expect(resolveHeadline(s, base: "main") == "Claude stopped; feat still conflicts with main") + let e = try resolving(stopped, panes: "[]")[0] + #expect(resolveHeadline(e, base: "main") == "The agent resolving feat ended; it still conflicts with main") + let coming = #"{"path":"/w/feat","branch":"feat","conflicts":["a.go"],"resolve":{"pane":"p9","by":"autopilot","at":"2027-01-15T07:00:00Z"}}"# + let a = try resolving(coming, panes: "[\(pane("p9", "working"))]")[0] + #expect(resolveDetail(a, now: Date(timeIntervalSince1970: 1_800_000_100)) == "not rebased yet Β· the autopilot asked 1h ago") +} + +// The banner is about the branch most in need: stuck before one in hand, +// and none for a conflict merely coming. +@Test func conflictBannerPicks() throws { + let working = try resolving(stopped, panes: "[\(pane("p9", "working"))]") + #expect(conflictBannerBranch(working)?.name == "feat") + let coming = try resolving(#"{"path":"/w/feat","branch":"feat","conflicts":["a.go"]}"#, panes: "[]") + #expect(conflictBannerBranch(coming) == nil) + let stuck = try resolving(#"{"path":"/w/feat","rebasing":"feat","status":{"files":1,"conflicts":1}}"#, panes: "[]") + #expect(conflictBannerBranch(stuck)?.state == .conflicted(1)) + #expect(conflictBannerBranch([]) == nil) +} + +// A new agent is started where the branch is checked out, which is a +// worktree naming no branch while its rebase is stopped. +@Test func branchWorktreeMidRebase() throws { + let p = try conchDecoder().decode(ProjectInfo.self, from: Data(#""" + {"id":"r1","name":"api","path":"/p","base":"main", + "worktrees":[{"path":"/p","branch":"main","main":true},{"path":"/w/feat","rebasing":"feat"},{"path":"/w/b","branch":"b"}]} + """#.utf8)) + #expect(branchWorktree(p, "feat")?.path == "/w/feat") + #expect(branchWorktree(p, "b")?.path == "/w/b") + #expect(branchWorktree(p, "nope") == nil) +} + +// One file asked, one left: not "1 of 1"; and asked a moment ago. +@Test func resolvingWordsJustAsked() throws { + let one = #"{"path":"/w/feat","rebasing":"feat","status":{"files":1,"conflicts":1},"resolve":{"pane":"p9","at":"2027-01-15T08:00:00Z","files":["a.go"]}}"# + let b = try resolving(one, panes: "[\(pane("p9", "working"))]")[0] + #expect(resolveDetail(b, now: Date(timeIntervalSince1970: 1_800_000_020)) == "1 file left Β· you asked just now") +} diff --git a/web/src/app/docs/mac-app/page.mdx b/web/src/app/docs/mac-app/page.mdx index b63a9dbc..298a46e1 100644 --- a/web/src/app/docs/mac-app/page.mdx +++ b/web/src/app/docs/mac-app/page.mdx @@ -131,7 +131,7 @@ A web page in a tab beside the agents. ## Commits -The project's history as a graph. +Agents' branches, conflicts, **CI**, **Autopilot**. **How:** **Commit Graph** on a project's or branch's menu. diff --git a/web/src/app/docs/protocol/page.mdx b/web/src/app/docs/protocol/page.mdx index b26113c1..41b80773 100644 --- a/web/src/app/docs/protocol/page.mdx +++ b/web/src/app/docs/protocol/page.mdx @@ -36,9 +36,13 @@ Over SSH the same stream runs through `conch bridge`. `hello` returns the server | Panes | `pane.list`, `pane.create`, `pane.close`, `pane.resize`, `pane.send_text`, `pane.send_keys`, `pane.send_mouse`, `pane.scroll`, `pane.read`, `pane.rename`, `pane.subscribe`, `pane.unsubscribe`, `pane.mark_seen`; `pane.search` finds text in a pane's history (capability `pane.search.v1`); `pane.monitor` watches a pane for output or silence, reported as `monitor` and `alert` in its info (capability `pane.monitor.v1`) | | Agents | `agent.report`, `agent.explain`, `agent.status`, `agent.install`, `agent.setup`, `agent.setup.sync`, `agent.limits`, `agent.broadcast`; `agent.setup.sync` with `user` gives the other agents the setup in your home rather than a checkout's, and `undo` puts it back (capability `agent.setup.sync.user.v1`); `agent.library` and `agent.library.apply` keep MCP servers and skills in conch and write them where each agent looks for them (capability `agent.library.v1`); `agent.prompt` submits one message to an agent and answers with the `turn` that will reply, refusing an agent waiting for an answer with the code `agent_blocked` β€” `turn` in an agent's status counts its starts of work (capability `agent.prompt.v1`); `agent.skill` installs or removes conch's skill for the agents (capability `agent.skill.v1`); `account.list`, `account.add`, `account.remove`, `account.pin` and `account.failover` keep an agent's other accounts, and `pane.create`, `task.create`, `group.task` and `session.resume` take `account` while panes, plan limits and sessions say theirs (capability `agent.accounts.v1`) | | Scoping | a pane's `created_by` names the pane it was started from, and a change asked from inside an agent's pane to a pane or project that isn't its own comes back with the code `out_of_scope` (capability `pane.scope.v1`); `pane.caller` says which pane a connection comes from and, for an agent, the name it goes by elsewhere, and `scope.act_for` holds a connection to what that agent started on this machine (capability `scope.remote.v1`) | -| Projects | `project.list`, `project.add`, `project.remove`, `project.refresh`, `project.changes`, `project.diff`, `project.log` (a project's commits across its branches and tags, with parents and refs, for a commit graph, and the repository's remotes by which a remote's branch is told from a local one; capability `project.log.v1`), `project.create`, `project.set_files`, `project.resolve` (which project and branch a directory is in; capability `project.resolve.v1`). A worktree's `operation` says what git left unfinished there (`rebase`, `merge`…), and mid-rebase its `branch` is the branch being rebased though `detached` is set (capability `worktree.operation.v1`) | +| Projects | `project.list`, `project.add`, `project.remove`, `project.refresh`, `project.changes`, `project.diff`, `project.log` (a project's commits across its branches and tags, with parents and refs, for a commit graph, the repository's remotes by which a remote's branch is told from a local one, and its `format` β€” `objects` sha1 or sha256 and `refs` files or reftable β€” absent from an older server; capability `project.log.v1`), `project.create`, `project.set_files`, `project.resolve` (which project and branch a directory is in; capability `project.resolve.v1`). A worktree's `operation` says what git left unfinished there (`rebase`, `merge`…), and mid-rebase its `branch` is the branch being rebased though `detached` is set (capability `worktree.operation.v1`) | | Worktrees and tasks | `worktree.add`, `worktree.remove`, `worktree.copy_files`, `task.create`; a task's `name` names its pane (capability `task.name.v1`) | | Branches | `branch.commit`, `branch.push`, `branch.pr`, `branch.merge`, `branch.discard` (capability `branch.harvest.v1`; a commit's `patch` field needs `branch.hunks.v1`, a push's `rebase` field `branch.push.rebase.v1`, and a push the remote is ahead of comes back with the code `push_rejected`, and a rebase undone by conflicts with `rebase_conflict`); `branch.git` runs the git panel's commands in the branch's worktree and reports an unfinished rebase or merge (capability `branch.git.v1`) | +| Rebased branches | `branch.rebased` lists each checked-out branch whose newest change is a finished rebase not yet pushed β€” or one `branch`'s β€” with its tip `before` and `after`, the commit it went `onto`, what the `remote` has, and each commit's fate (`same`, `changed` where a conflict was resolved, `dropped`, `added`); `diff` adds git range-diff's account. A push with `over` replaces the remote's branch only if it is still that commit, and `branch.rebase_undo` puts a branch back at `before` while it is still at `after` (capability `branch.rebased.v1`) | +| Resolving a conflict | `branch.resolving` names the agent (`pane_id`) asked to resolve a `branch`'s conflict with the base, or with no `pane_id` that nobody is; the project's worktree then carries `resolve` β€” the `pane`, `by` (`autopilot`, or empty for the person), `at` and the `files` β€” while the conflict is there. The autopilot sets it when it hands a conflict to an agent. Kept in memory, so a reload forgets it (capability `branch.resolving.v1`) | +| CI | `ci.stats` adds up a project's GitHub Actions runs over `days` (14 by default, 90 at most) and the same span before: runs, passes and failures, median run, queue and red-to-green times, runs per day, each job's median and slowest tenth, flaky jobs, and each workflow's newest failed run per branch; a few dozen runs' jobs are read per call and `jobs_pending` says how many are left (capability `ci.stats.v1`). `ci.rerun` runs a run's failed jobs again, by `run_id` or a `branch`'s newest failed run (capability `ci.rerun.v1`). Both go through `gh` on the project's machine | +| Autopilot activity | every `autopilot.note` the server sends carries its `kind` (`ci`, `check`, `ship`, `merge`, `resolve`, `intake`, `triage`) and `at`, and is kept β€” the newest 500, in `autopilot-activity.jsonl` beside the config, so a restart keeps them; `autopilot.activity` lists them newest first, for a `project_id` or every project, `limit` at most (100 by default) (capability `autopilot.activity.v1`) | | Worktree cleanup | `worktree.stale`, `worktree.cleanup` (capability `worktree.cleanup.v1`) | | Moving a worktree | `worktree.describe`, `worktree.pack`, `worktree.pack_read` on the machine it leaves; `worktree.have`, `fs.upload`, `worktree.unpack` and `project.clone` on the one it goes to (capability `worktree.move.v1`). The servers never talk to each other: the client carries the pack | | Sessions | `session.list`, `session.search`, `session.resume`, `session.share`, `session.delete`, `session.dismiss`; `session.export` and `session.share` with a `doc` hand a conversation to another machine (capability `session.handoff.v1`) |