| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "log/slog" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "strings" |
| 11 | "time" |
| 12 | |
| 13 | "the-valley/flow/internal/event" |
| 14 | "the-valley/flow/internal/git" |
| 15 | "the-valley/flow/internal/integration" |
| 16 | "the-valley/flow/internal/restack" |
| 17 | "the-valley/flow/internal/run" |
| 18 | "the-valley/flow/internal/tmux" |
| 19 | "the-valley/flow/internal/valley" |
| 20 | "github.com/spf13/cobra" |
| 21 | ) |
| 22 | |
| 23 | var restackConflictsCmd = &cobra.Command{ |
| 24 | Use: "restack-conflicts", |
| 25 | Short: "Dispatch runs to resolve the restack conflicts a valley reports on changes klaus owns", |
| 26 | Long: `Reads the restack reports of the valley repos the session's runs deliver |
| 27 | to, and launches a run to resolve each current conflict on a change klaus |
| 28 | owns. The dashboard does this after each integration check, about once a |
| 29 | minute; run it by hand where no dashboard runs. |
| 30 | |
| 31 | A valley's restacker rebases ready changes onto main after each landing, and |
| 32 | when a rebase conflicts it reports the conflict beside the change. A change |
| 33 | is klaus's when its record's owner is klaus's principal, the repo's git |
| 34 | config valley.principal; who uploaded its latest version doesn't count, |
| 35 | since the restacker uploads the versions it rebases. A report counts only |
| 36 | while the valley says it is current, and while what the listing shows of |
| 37 | the change (its record, active version, head and branch) matches the |
| 38 | report, and each other change the report rebased is listed on the branch |
| 39 | the report names for it. |
| 40 | |
| 41 | For each such conflict, unless klaus leaves it alone (below), klaus: |
| 42 | |
| 43 | 1. reads the change and origin's refs again: main, the report, and each |
| 44 | rebased change's record and the branch its record names, and skips |
| 45 | the report if any moved; |
| 46 | 2. records the attempt, and the ID of the run it is about to launch, in |
| 47 | its ledger, and does nothing if it can't; |
| 48 | 3. returns the change to draft ('valley unready'), and launches nothing |
| 49 | unless the valley then lists it as klaus's draft at the same head and |
| 50 | branch; |
| 51 | 4. launches 'klaus launch [--repo <project>] --change <change-id> |
| 52 | --run-id <id> --expect-owner <principal> --expect-branch <branch> |
| 53 | --expect-head <head> --expect-draft --reason restack-conflict <brief>' |
| 54 | from a clone of the repo. Launch checks all of it again, fetching the |
| 55 | branch and asking the valley under its continuation lock, before it |
| 56 | creates the worktree and again as the worker starts, and fails rather |
| 57 | than start a worker on a change that was readied or moved meanwhile, |
| 58 | or that it couldn't check. It keeps its own refusals too: a run |
| 59 | already working on the change or its branch, or a branch with work |
| 60 | origin lacks. |
| 61 | |
| 62 | The brief names the change, its version, head and branch, and main's tip: |
| 63 | what klaus read itself. Nothing a report says is run, and none of its text |
| 64 | is passed on; the run finds the conflicts by rebasing, and pushes the |
| 65 | rebased head with the leased push its instructions give. |
| 66 | |
| 67 | As the pipeline does for a PR's conflicts, klaus never starts a second run |
| 68 | on a change, waits 60 seconds after each dispatch, and stops after 3 runs, |
| 69 | until a report says the change restacked cleanly: one reset per clean |
| 70 | report, and only while origin still holds that report. It acts once on |
| 71 | each set of inputs, the change's head and main's tip, whatever came |
| 72 | between: an unchanged conflict is not retried, nor one that comes back to |
| 73 | inputs klaus acted on before, nor one whose unready or launch failed; it |
| 74 | shows what came of those inputs then. Once |
| 75 | no run is working on a change whose attempts are spent, klaus says it |
| 76 | stopped, even if the last run left the conflict as it was. |
| 77 | |
| 78 | An attempt is given back only when klaus knows no worker started: it |
| 79 | stopped before launching, or launch exited with status 3. Any other launch |
| 80 | failure keeps the attempt and the cooldown, and so does a pass that ends |
| 81 | mid-launch: either leaves the launch pending in the ledger, and the change |
| 82 | busy, until a run by its ID is recorded (a dispatch) or klaus proves no |
| 83 | worker of it runs: no launch holds the clone's continuation lock, no run |
| 84 | by the ID is recorded, and no live tmux pane's command names it. Time alone |
| 85 | settles nothing. |
| 86 | |
| 87 | klaus leaves a conflict alone when it is in another change below this one |
| 88 | (a change whose owner isn't klaus is never taken over), or when the change |
| 89 | sits on other changes. |
| 90 | |
| 91 | Each dispatch emits change:restack-dispatched under the new run's ID. A |
| 92 | conflict klaus stops short of resolving, or leaves alone (above), emits |
| 93 | change:restack-stalled once for each set of inputs: the change needs the |
| 94 | coordinator, as klaus will not resolve it. Its reason says why: attempts |
| 95 | spent, unready or launch failed, or "left-alone: sits on other changes" or |
| 96 | "left-alone: conflict in a change below". What klaus did is kept in the |
| 97 | session's restack-dispatches.json; klaus status and the dashboard show it, a conflict left |
| 98 | alone as needing help. |
| 99 | The ledger drops a change's entry once the change lands or is withdrawn, |
| 100 | unless a launch for it is pending, and keeps what came of a change's latest |
| 101 | 16 sets of inputs; older ones may be acted on again. |
| 102 | |
| 103 | Prints one line per conflict on a change klaus owns.`, |
| 104 | Args: cobra.NoArgs, |
| 105 | RunE: func(cmd *cobra.Command, args []string) error { |
| 106 | store, err := sessionStore() |
| 107 | if err != nil { |
| 108 | return err |
| 109 | } |
| 110 | hds, ok := store.(*run.HomeDirStore) |
| 111 | if !ok { |
| 112 | return fmt.Errorf("restack-conflicts needs a session directory") |
| 113 | } |
| 114 | views, err := restackPass(cmd.Context(), hds, nil, true) |
| 115 | if err != nil { |
| 116 | return err |
| 117 | } |
| 118 | if len(views) == 0 { |
| 119 | fmt.Println("No restack conflicts on changes klaus owns.") |
| 120 | } |
| 121 | for _, v := range views { |
| 122 | fmt.Println(v) |
| 123 | } |
| 124 | return nil |
| 125 | }, |
| 126 | } |
| 127 | |
| 128 | func init() { |
| 129 | rootCmd.AddCommand(restackConflictsCmd) |
| 130 | } |
| 131 | |
| 132 | // restackLaunchTimeout bounds one resolution run's launch. |
| 133 | const restackLaunchTimeout = 5 * time.Minute |
| 134 | |
| 135 | // restackPass runs a restack pass over the valley repos of the session's |
| 136 | // runs, reading their reports in listed, or with nil, listing each repo. |
| 137 | // With act it holds the ledger's lock, dispatches and records what it did; |
| 138 | // without, it only reports. |
| 139 | func restackPass(ctx context.Context, store *run.HomeDirStore, listed *valley.Changes, act bool) ([]restack.View, error) { |
| 140 | states, err := store.List() |
| 141 | if err != nil { |
| 142 | return nil, err |
| 143 | } |
| 144 | root, _ := git.RepoRoot() |
| 145 | repos := restack.Repos(states, root) |
| 146 | if len(repos) == 0 { |
| 147 | return nil, nil |
| 148 | } |
| 149 | if act { |
| 150 | unlock, err := restack.Lock(store.BaseDir()) |
| 151 | if err != nil { |
| 152 | return nil, err |
| 153 | } |
| 154 | defer unlock() |
| 155 | } |
| 156 | // The ledger holds the attempts and cooldowns: a pass that can't read |
| 157 | // it dispatches nothing, rather than start them over. |
| 158 | ledger, err := restack.LoadLedger(store.BaseDir()) |
| 159 | if err != nil && act { |
| 160 | return nil, fmt.Errorf("reading the restack ledger: %w", err) |
| 161 | } |
| 162 | if err != nil { |
| 163 | slog.Warn("reading the restack ledger", "err", err) |
| 164 | } |
| 165 | all, err := run.ListAllSessions() |
| 166 | if err != nil { |
| 167 | all = states |
| 168 | } |
| 169 | events := event.NewLog(store.BaseDir()) |
| 170 | emit := func(runID, typ string, data map[string]interface{}) { |
| 171 | if err := events.Emit(event.New(runID, typ, data)); err != nil { |
| 172 | slog.Warn("emitting a restack event", "type", typ, "err", err) |
| 173 | } |
| 174 | } |
| 175 | d := restack.Default(launchResolution, runRecorded, restack.RunningOn(all, run.DefaultTmuxDeps()), workerGone, emit) |
| 176 | return restack.Pass(ctx, d, ledger, repos, listed, act), nil |
| 177 | } |
| 178 | |
| 179 | // launchResolution launches a resolution run with this klaus binary, |
| 180 | // under the run ID klaus recorded, in launch's strict mode: launch checks |
| 181 | // the change is still the owner's draft at the branch and head klaus |
| 182 | // checked before it starts the worker. Launch's exit status 3 says it |
| 183 | // failed before starting one (restack.ErrNotStarted). |
| 184 | func launchResolution(ctx context.Context, l restack.Launch) error { |
| 185 | self, err := os.Executable() |
| 186 | if err != nil { |
| 187 | self = "klaus" |
| 188 | } |
| 189 | args := []string{"launch"} |
| 190 | if l.Project != "" { |
| 191 | args = append(args, "--repo", l.Project) |
| 192 | } |
| 193 | args = append(args, "--change", l.ChangeID, "--run-id", l.RunID, |
| 194 | "--expect-owner", l.Owner, "--expect-branch", l.Branch, "--expect-head", l.Head, "--expect-draft", |
| 195 | "--reason", event.DispatchRestackConflict, "--", l.Prompt) |
| 196 | return runLaunch(ctx, self, l.Dir, args) |
| 197 | } |
| 198 | |
| 199 | // runLaunch runs launch with this klaus binary, self, in dir, and says why |
| 200 | // it failed. An error wrapping restack.ErrNotStarted says launch exited |
| 201 | // with status 3, before it started a worker. |
| 202 | func runLaunch(ctx context.Context, self, dir string, args []string) error { |
| 203 | ctx, cancel := context.WithTimeout(ctx, restackLaunchTimeout) |
| 204 | defer cancel() |
| 205 | cmd := exec.CommandContext(ctx, self, args...) |
| 206 | cmd.Dir = dir |
| 207 | out, err := cmd.CombinedOutput() |
| 208 | if err == nil { |
| 209 | return nil |
| 210 | } |
| 211 | why := launchError(out) |
| 212 | var exit *exec.ExitError |
| 213 | if errors.As(err, &exit) && exit.ExitCode() == exitNoWorker { |
| 214 | return fmt.Errorf("klaus launch: %w: %s", restack.ErrNotStarted, why) |
| 215 | } |
| 216 | return fmt.Errorf("klaus launch: %w: %s", err, why) |
| 217 | } |
| 218 | |
| 219 | // launchError is what a failed launch's output says went wrong: its |
| 220 | // "Error: " line, else all of it. |
| 221 | func launchError(out []byte) string { |
| 222 | lines := strings.Split(string(out), "\n") |
| 223 | for i := len(lines) - 1; i >= 0; i-- { |
| 224 | if msg, ok := strings.CutPrefix(lines[i], "Error: "); ok { |
| 225 | return msg |
| 226 | } |
| 227 | } |
| 228 | return strings.TrimSpace(string(out)) |
| 229 | } |
| 230 | |
| 231 | // runRecorded reports whether a run by runID is recorded in any session. |
| 232 | func runRecorded(runID string) bool { |
| 233 | states, err := run.ListAllSessions() |
| 234 | return err == nil && findRun(states, runID) != nil |
| 235 | } |
| 236 | |
| 237 | // workerGone reports whether klaus can prove that no worker of run runID |
| 238 | // runs, nor is about to start, from the clone at dir: no launch holds the |
| 239 | // clone's continuation lock, under which launch checks for live holders, |
| 240 | // starts its worker and records its run (and stops a worker whose run it |
| 241 | // couldn't record); no run by the ID is recorded, in any session; and no |
| 242 | // live tmux pane runs a command that names the run, as every worker's |
| 243 | // does. A launch still on its way to the lock is no worker yet: under the |
| 244 | // lock it finds any run recorded meanwhile, and starts none beside it. Any |
| 245 | // read that fails is doubt: false. |
| 246 | func workerGone(ctx context.Context, dir, runID string) bool { |
| 247 | release, ok := tryLockContinuation(ctx, dir) |
| 248 | if !ok { |
| 249 | return false |
| 250 | } |
| 251 | defer release() |
| 252 | states, err := run.ListAllSessions() |
| 253 | if err != nil || findRun(states, runID) != nil { |
| 254 | return false |
| 255 | } |
| 256 | live, err := tmux.PaneStartedWith(ctx, runID) |
| 257 | return err == nil && !live |
| 258 | } |
| 259 | |
| 260 | // restackViews indexes views by change, as the dashboard and status look |
| 261 | // them up. |
| 262 | func restackViews(views []restack.View) map[integration.ChangeKey]restack.View { |
| 263 | out := make(map[integration.ChangeKey]restack.View, len(views)) |
| 264 | for _, v := range views { |
| 265 | out[integration.ChangeKey{Repo: v.Repo, ChangeID: v.ChangeID}] = v |
| 266 | } |
| 267 | return out |
| 268 | } |