oficina / equipo Public

Merge remote-tracking branch 'origin/main' into notify/actions

Paul Campbell pushed by claude agent, operated by paul@keymail.dev 69219bb0f527256dee811b77049985966601f014 parent 94219e9parent a2619ce
12 files changed, +1,144 −94
  • .rastrillo/budgets.txt +4 −4
  • internal/equipo/chat/change_files_exposure_test.go +1 −1
  • internal/equipo/chat/preview.go +3 −1
  • internal/equipo/chat/preview_retry.go +388 −0
  • internal/equipo/chat/publish.go +4 −2
  • internal/equipo/chat/stuck.go +59 −57
  • internal/equipo/chat/tasks.go +36 −18
  • internal/equipo/preview_pass_store.go +7 −2
  • internal/equipo/work_views.go +47 −8
  • internal/runner/thin/mcp.go +1 −1
  • internal/runner/thin/merge_identity_test.go +95 −0
  • internal/thintest/preview_retry_done_contract_test.go +499 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 7a7c6d2d..e5ae5dc7 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,7 +14,7 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 23248 - Preview grants, Retry/timeline, no-access merges, kept timed-out work, and reviewed check-db operator copy; measured 23248 source lines (2026-11-26).
+size internal/equipo 23293 - Preview grants, Retry/timeline, no-access merges, kept timed-out work, and reviewed check-db operator copy; previews run again on done tasks; measured 23293 source lines (2026-11-26).
size internal/wire 7420 - Protocol 31 display facts, path validation, task evidence, merge reasons; protocol 32 unfinished work, shell_unavailable, CI units (2026-11-26); measured 7420 source lines.
size internal/equipotest - 12017 Task 21 repairs historical migration and conversation fixtures after Plan 3, and the Rastrillo upgrade contract comparing served assets with what Assets serves; measured 0/12017 source/test lines.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 29062 23966 Protocol 31 facts, merge credential, publication guards; step limit, kept timed-out work, shell use, CI unit shares (2026-11-26); measured 29062/23966.
+size internal/runner/thin 29062 24061 Protocol 31 facts, merge credential, publication guards; step limit, kept timed-out work, shell use, CI units, merge identity (2026-11-26); measured 29062/24061.
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
@@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device
perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
-size internal/equipo/chat 35061 9910 Detail-only file facts, hosted projection, no-access merges, preview reads; unfinished work, free shell-less rounds, CI feedback (2026-11-26); measured 35061/9910.
+size internal/equipo/chat 35473 9910 File facts, hosted projection, no-access merges, preview reads; unfinished work, shell-less rounds, CI feedback; previews on done tasks (2026-11-26); measured 35473/9910.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -71,7 +71,7 @@ perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one im
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally).
size internal/headless - 11437 Grant scenarios for a named repository (hub #48); the sign-in's account email at 1280 and 390; measured 11437 test lines.
-size internal/thintest - 35444 Protocol 31 and detail-only contracts, stuck tasks, no-access merges; held retries, unfinished work, shard feedback, free rounds (2026-11-26); measured 35444 test lines.
+size internal/thintest - 35943 Protocol 31 and detail-only contracts, stuck tasks, no-access merges; held retries, unfinished work, shard feedback, free rounds; previews on done tasks (2026-11-26); measured 35943 test lines.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage.
diff --git a/internal/equipo/chat/change_files_exposure_test.go b/internal/equipo/chat/change_files_exposure_test.go
index adc40573..7d7b0f1b 100644
--- a/internal/equipo/chat/change_files_exposure_test.go
+++ b/internal/equipo/chat/change_files_exposure_test.go
@@ -61,7 +61,7 @@ func TestChangeFilesStayOutOfCoordinatorListsSnapshotAndEvents(t *testing.T) {
must(err)
noFacts("snapshot", snapshot)
must(r.s.tx(ctx, func(tx *txn) error {
- result, err := tx.readTask(k.ID)
+ result, err := tx.readTask(hkOwner, k.ID)
if err != nil {
return err
}
diff --git a/internal/equipo/chat/preview.go b/internal/equipo/chat/preview.go
index 0e2b0ad6..21ec1fbd 100644
--- a/internal/equipo/chat/preview.go
+++ b/internal/equipo/chat/preview.go
@@ -138,7 +138,9 @@ func (t *txn) previewRefusal(l Lease, s *stepRecord, purpose, digest string) (st
return "", err
}
p := progressFor(k, steps)
- if p.moved || p.candidate != s.CandidateSHA || p.review == nil || p.review.State != wire.StepDone || p.review.Verdict != wire.VerdictApprove {
+ // The approved candidate while the branch is at it, or once the task
+ // is done the commit a preview of it builds (its merged commit).
+ if !previewMayBuild(k, p, s.CandidateSHA) {
return "withdrawn", nil
}
grant := previewGrant(*s)
diff --git a/internal/equipo/chat/preview_retry.go b/internal/equipo/chat/preview_retry.go
new file mode 100644
index 00000000..6c58449c
--- /dev/null
+++ b/internal/equipo/chat/preview_retry.go
@@ -0,0 +1,388 @@
+package chat
+
+import (
+ "encoding/json"
+ "errors"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Previews on finished tasks (Paul, 2026-11-26: "Retry the Neary's
+// preview" was refused because both tasks were merged and done). A
+// preview is ancillary, so it may run again after its task ended: on a
+// task Equipo merged it builds the merged commit, otherwise the approved
+// candidate, as a new preview step; the task's stage, merge and other
+// steps stay as they are. It is published only through the preview's own
+// checks (previewRefusal). A preview that ended unconfirmed, or whose link
+// is gone, counts as one to run again, like a failed one.
+
+// Why a retry is refused, in fixed words: retry_step's result and
+// read_task's retry say them; people see the conflict, never these.
+const (
+ retryTaskCancelled = "task_cancelled"
+ retryTaskDone = "task_done"
+ retryNotEnded = "not_ended"
+ retryCompleted = "completed"
+ retryNotFailed = "not_failed"
+ retryNotNewest = "not_newest"
+ retryCommitChanged = "commit_changed"
+ retryNotApproved = "not_approved"
+ retryNoRunner = "no_runner"
+ retryNotYours = "not_yours"
+ retryNotOwner = "not_owner"
+ retryNoStep = "no_step"
+ // Notes beside a retry that can run (read_task's retry, retry_step's
+ // result): the merged commit could not be proven to be the merge of
+ // the approved candidate, so the approved candidate is built instead;
+ // a devbox link brought up after the task was done stays up until the
+ // next run replaces it.
+ retryMergeUnverified = "merge_unverified"
+ retryDevboxStaysUp = "devbox_stays_up"
+ // previewHostAuthority's reasons are used as they are:
+ // wire.ReasonRunnerOutdated, preview_host, preview_public_disabled.
+)
+
+// retryNotes is what the model reads back for each reason.
+var retryNotes = map[string]string{
+ retryTaskCancelled: "The task was cancelled: nothing of it runs again.",
+ retryTaskDone: "The task is done: only its preview can run again (step: preview). Its checks, review and merge stay as they are.",
+ retryNotEnded: "That step has not ended yet (queued or running, or its end is not proven). Wait for it; read_task shows it.",
+ retryCompleted: "That step did its work (its checks or review finished, or its preview link is up). There is nothing to run again.",
+ retryNotFailed: "That step was stopped, not failed: there is nothing to run again.",
+ retryNotNewest: "A newer step of that kind came after it: only the newest runs again.",
+ retryCommitChanged: "The commit it would judge or show is no longer the task's (the branch moved, or a new candidate came). read_task shows where it stands.",
+ retryNotApproved: "Review has not approved the task's commit, so no preview of it runs.",
+ retryNoRunner: "The person has no primary runner connected to run it on.",
+ retryNotYours: "That task is another person's: only the person who asked for it can run its steps again.",
+ retryNotOwner: "Only an owner's runner can run work.",
+ retryNoStep: "That task has no step of that kind yet.",
+ retryMergeUnverified: "Equipo could not prove the merged commit is exactly the merge of the approved commit, so a preview builds the approved commit itself, which Review approved, not the merged one.",
+ retryDevboxStaysUp: "Its preview link on the person's tailnet came up after the task was done; it stays up until the next preview of the task replaces it.",
+ wire.ReasonRunnerOutdated: "The person's primary runner is too old to make previews: it needs an update first.",
+ "preview_host": "The person's primary runner has no preview host now.",
+ "preview_public_disabled": "This project does not allow public previews now; an owner can turn them on in Settings.",
+ "not_retryable": toolStepNotRetried,
+}
+
+// retryRefusal is a refused retry with its fixed reason: errors.Is
+// matches its kind (ErrNotRetryable, ErrTaskEnded or ErrForbidden).
+type retryRefusal struct {
+ kind error
+ reason string
+}
+
+func (e retryRefusal) Error() string { return e.kind.Error() + ": " + e.reason }
+func (e retryRefusal) Unwrap() error { return e.kind }
+func refuseRetry(kind error, reason string) error { return retryRefusal{kind, reason} }
+
+// retryReasonOf is err's fixed reason, fallback when it has none.
+func retryReasonOf(err error, fallback string) string {
+ var r retryRefusal
+ if errors.As(err, &r) {
+ return r.reason
+ }
+ return fallback
+}
+
+// refusedRetry is retry_step's refusal: the code, and the reason with
+// what it means.
+func refusedRetry(code, reason string) wire.ToolResult {
+ note, ok := retryNotes[reason]
+ if !ok {
+ reason, note = "not_retryable", toolStepNotRetried
+ }
+ raw, _ := json.Marshal(map[string]string{"reason": reason, "note": note})
+ return refused(code, string(raw))
+}
+
+// approvedCandidate reports whether Review approved the task's candidate.
+func approvedCandidate(p progress) bool {
+ return p.candidate != "" && p.review != nil && p.review.State == wire.StepDone && p.review.Verdict == wire.VerdictApprove
+}
+
+// previewTarget is the commit a new preview of the task builds now: on a
+// done task Equipo merged, its merged commit when that is proven to be the
+// merge of the approved candidate (verifiedMerge), else the approved
+// candidate itself, which Review approved (note says merge_unverified);
+// otherwise the approved candidate while the branch is at it. "" when
+// there is none.
+func previewTarget(k taskRecord, p progress) (sha, note string) {
+ if !approvedCandidate(p) {
+ return "", ""
+ }
+ if k.Stage == wire.StageDone && k.MergedSHA != "" {
+ if m := verifiedMerge(k, p); m != "" {
+ return m, ""
+ }
+ // The candidate landed (the hub or the runner said so), so it is
+ // on the default branch's history whatever the branch did since.
+ return p.candidate, retryMergeUnverified
+ }
+ if p.moved {
+ return "", ""
+ }
+ return p.candidate, ""
+}
+
+// verifiedMerge is the task's merged commit when it is proven to bring in
+// exactly the approved candidate: the candidate itself (it landed as it
+// is), or the hub's own answer to this merge request, a merge commit whose
+// second parent is the candidate (MergeVerified, its parents recorded on
+// the merge step). "" otherwise: a reconciled or cached landing names the
+// commit the runner found, and past its 200-commit search the default
+// branch's tip, which may hold later work that nobody reviewed here.
+func verifiedMerge(k taskRecord, p progress) string {
+ m := p.merge
+ if k.Stage != wire.StageDone || k.MergedSHA == "" || m == nil || m.State != wire.StepDone || m.MergeSHA != k.MergedSHA || m.CandidateSHA != p.candidate {
+ return ""
+ }
+ if k.MergedSHA == p.candidate {
+ return k.MergedSHA
+ }
+ var parents []string
+ if json.Unmarshal([]byte(m.MergeParents), &parents) != nil {
+ return ""
+ }
+ if !k.MergeVerified || m.MergeSource != wire.MergeSourceHub || len(parents) != 2 || parents[1] != p.candidate || parents[0] == p.candidate || parents[0] == k.MergedSHA {
+ return ""
+ }
+ return k.MergedSHA
+}
+
+// previewMayBuild reports whether a preview of sha may run and publish
+// for the task now: the approved candidate while the branch is at it,
+// or, once the task is done, previewTarget.
+func previewMayBuild(k taskRecord, p progress, sha string) bool {
+ if sha == "" || !approvedCandidate(p) {
+ return false
+ }
+ target, _ := previewTarget(k, p)
+ return sha == p.candidate && !p.moved || k.Stage == wire.StageDone && sha == target
+}
+
+// previewOfTask reports whether a preview of sha stands for the task: of
+// its candidate cand, or of its merged commit once done (a preview of it
+// is only ever placed when verifiedMerge proved it).
+func previewOfTask(k taskRecord, cand, sha string) bool {
+ return sha != "" && (sha == cand || k.Stage == wire.StageDone && k.MergedSHA != "" && sha == k.MergedSHA)
+}
+
+// previewUp reports whether a preview step's link is served now:
+// deployed, before any expiry, and a devbox link only while its task runs
+// or is held for Publish (previewHeld), or one that came up after its task
+// was done (devboxAfterDone).
+func previewUp(k taskRecord, s stepRecord, now time.Time, held bool) bool {
+ r := decodePreview(s.Preview)
+ if s.State != wire.StepDone || r == nil || r.Outcome != wire.PreviewDeployed || r.URL == "" {
+ return false
+ }
+ if r.ExpiresAt != nil && !r.ExpiresAt.After(now) {
+ return false
+ }
+ if strings.HasPrefix(r.App, "eq-") && wire.FinalStage(k.Stage) && !held {
+ return devboxAfterDone(k, s)
+ }
+ return true
+}
+
+// devboxAfterDone: a devbox link that came up after its task was done (a
+// preview run again on a merged task). Nothing takes it down by itself:
+// the task's next preview replaces it, or the existing paths unshare it
+// (a known gap, retryDevboxStaysUp).
+func devboxAfterDone(k taskRecord, s stepRecord) bool {
+ r := decodePreview(s.Preview)
+ return r != nil && strings.HasPrefix(r.App, "eq-") && k.Stage == wire.StageDone && k.DoneAt != nil && s.FinishedAt != nil && s.FinishedAt.After(*k.DoneAt)
+}
+
+// previewRetryCheck is why a preview step cannot run again for person
+// now ("" when it can), and the commit it would build: the person's, on a
+// task not cancelled, the task's newest preview, ended and not up (failed,
+// cancelled, unconfirmed, expired, or a devbox link gone with its task),
+// a commit previewTarget names, on a primary whose preview host the
+// project allows now.
+func (t *txn) previewRetryCheck(k taskRecord, st stepRecord, person string) (reason, target string, err error) {
+ if st.Person != person {
+ return retryNotYours, "", nil
+ }
+ if k.CancelRequested || k.Stage == wire.StageCancelled {
+ return retryTaskCancelled, "", nil
+ }
+ steps, err := t.steps(k.ID)
+ if err != nil {
+ return "", "", err
+ }
+ for _, s := range steps {
+ if s.Specialist == wire.SpecialistPreview && s.Idx > st.Idx {
+ return retryNotNewest, "", nil
+ }
+ }
+ if !wire.StepTerminal(st.State) || !st.Terminated {
+ return retryNotEnded, "", nil
+ }
+ held := false
+ if wire.FinalStage(k.Stage) {
+ if held, err = t.previewHeld(k, steps); err != nil {
+ return "", "", err
+ }
+ }
+ // Up: nothing to run again, except a devbox link brought up after the
+ // task was done, which only the next run replaces.
+ if previewUp(k, st, t.now(), held) && !devboxAfterDone(k, st) {
+ return retryCompleted, "", nil
+ }
+ p := progressFor(k, steps)
+ if !approvedCandidate(p) {
+ return retryNotApproved, "", nil
+ }
+ target, _ = previewTarget(k, p)
+ if target == "" || k.Stage != wire.StageDone && st.CandidateSHA != target {
+ return retryCommitChanged, "", nil
+ }
+ primary, err := t.s.authority.PrimaryRunner(t.db, st.Person)
+ if err != nil || primary == "" {
+ return retryNoRunner, "", err
+ }
+ rs, err := t.runners(st.Person)
+ if err != nil {
+ return "", "", err
+ }
+ for _, r := range rs {
+ if r.ID == primary {
+ reason, err := t.previewHostAuthority(k.ProjectID, r)
+ return reason, target, err
+ }
+ }
+ return retryNoRunner, "", nil
+}
+
+// endedReason is why a step other than a preview cannot run again for
+// its state ("" when it failed and ended).
+func endedReason(st stepRecord, found bool) string {
+ switch {
+ case !found:
+ return retryNoStep
+ case !wire.StepTerminal(st.State) || !st.Terminated:
+ return retryNotEnded
+ case st.State == wire.StepDone:
+ return retryCompleted
+ case st.State == wire.StepCancelled:
+ return retryNotFailed
+ }
+ return ""
+}
+
+// retryReason is why person cannot run st again now ("" when they can),
+// as personRetry would decide for the coordinator: read_task's retry.
+func (t *txn) retryReason(k taskRecord, st stepRecord, person string) (string, error) {
+ if err := t.isOwner(person); errors.Is(err, ErrForbidden) {
+ return retryNotOwner, nil
+ } else if err != nil {
+ return "", err
+ }
+ if k.Creator != person {
+ return retryNotYours, nil
+ }
+ if k.CancelRequested || k.Stage == wire.StageCancelled {
+ return retryTaskCancelled, nil
+ }
+ if st.Specialist == wire.SpecialistPreview {
+ reason, _, err := t.previewRetryCheck(k, st, person)
+ return reason, err
+ }
+ if k.Stage == wire.StageDone {
+ return retryTaskDone, nil
+ }
+ latest, found, err := t.latestStep(k.ID)
+ if err != nil {
+ return "", err
+ }
+ if !found || latest.ID != st.ID {
+ return retryNotNewest, nil
+ }
+ if r := endedReason(st, true); r != "" {
+ return r, nil
+ }
+ if st.Person != person {
+ return retryNotYours, nil
+ }
+ primary, err := t.s.authority.PrimaryRunner(t.db, st.Person)
+ if err != nil || primary == "" {
+ return retryNoRunner, err
+ }
+ return "", nil
+}
+
+// retryView is read_task's word on running the task's newest step of a
+// kind again (wire.RetryStepKinds): Reason is "" when it can run.
+type retryView struct {
+ Step string `json:"step"`
+ StepID string `json:"step_id"`
+ Retryable bool `json:"retryable"`
+ Reason string `json:"reason,omitempty"`
+ // Note is a fixed note beside it (retryMergeUnverified,
+ // retryDevboxStaysUp), NoteText what it means.
+ Note string `json:"note,omitempty"`
+ NoteText string `json:"note_text,omitempty"`
+}
+
+func (t *txn) retryViews(k taskRecord, person string) ([]retryView, error) {
+ var out []retryView
+ for _, kind := range wire.RetryStepKinds {
+ var st stepRecord
+ res := t.db.Where("task_id = ? AND specialist = ? AND coalesce(retired, 0) = 0", k.ID, kind).Order("idx DESC").Limit(1).Find(&st)
+ if res.Error != nil {
+ return nil, res.Error
+ }
+ if res.RowsAffected == 0 {
+ continue
+ }
+ reason, err := t.retryReason(k, st, person)
+ if err != nil {
+ return nil, err
+ }
+ v := retryView{Step: kind, StepID: st.ID, Retryable: reason == "", Reason: reason}
+ if kind == wire.SpecialistPreview {
+ if v.Note, err = t.previewNote(k, st); err != nil {
+ return nil, err
+ }
+ v.NoteText = retryNotes[v.Note]
+ }
+ out = append(out, v)
+ }
+ return out, nil
+}
+
+// rerunPreview places a new preview step of target on a finished task,
+// beside its other steps (the timeline shows it after them); the task's
+// stage and its merge are untouched.
+func (t *txn) rerunPreview(k *taskRecord, st *stepRecord, target string, coordinator bool) (int64, error) {
+ steps, err := t.steps(k.ID)
+ if err != nil {
+ return 0, err
+ }
+ s := stepRecord{Specialist: wire.SpecialistPreview, Person: st.Person, Round: st.Round, BaseSHA: st.BaseSHA, CandidateSHA: target}
+ if coordinator {
+ s.CoordinatorAttempt = 1
+ }
+ if err := t.nextStep(k, steps, s); err != nil {
+ return 0, err
+ }
+ return 1, nil
+}
+
+// previewNote is the fixed note beside a task's newest preview: its link
+// on a done task stays up until replaced, or a new preview would build the
+// approved commit because the merged one is not proven.
+func (t *txn) previewNote(k taskRecord, st stepRecord) (string, error) {
+ if devboxAfterDone(k, st) && previewUp(k, st, t.now(), false) {
+ return retryDevboxStaysUp, nil
+ }
+ steps, err := t.steps(k.ID)
+ if err != nil {
+ return "", err
+ }
+ _, note := previewTarget(k, progressFor(k, steps))
+ return note, nil
+}
diff --git a/internal/equipo/chat/publish.go b/internal/equipo/chat/publish.go
index 70b68635..08349b69 100644
--- a/internal/equipo/chat/publish.go
+++ b/internal/equipo/chat/publish.go
@@ -660,14 +660,16 @@ func previewLink(k taskRecord, steps []stepRecord, cand string, now time.Time, h
}
for i := len(steps) - 1; i >= 0; i-- {
s := steps[i]
- if s.Specialist != wire.SpecialistPreview || s.CandidateSHA != cand || s.State != wire.StepDone {
+ // Of the candidate, or of the merged commit once done (a preview
+ // run again after the merge).
+ if s.Specialist != wire.SpecialistPreview || !previewOfTask(k, cand, s.CandidateSHA) || s.State != wire.StepDone {
continue
}
r := decodePreview(s.Preview)
if r == nil || r.Outcome != wire.PreviewDeployed || r.URL == "" {
continue
}
- if strings.HasPrefix(r.App, "eq-") && wire.FinalStage(k.Stage) && !held || r.ExpiresAt != nil && !r.ExpiresAt.After(now) {
+ if !previewUp(k, s, now, held) {
return ""
}
return r.URL
diff --git a/internal/equipo/chat/stuck.go b/internal/equipo/chat/stuck.go
index 6742300b..507e2b9f 100644
--- a/internal/equipo/chat/stuck.go
+++ b/internal/equipo/chat/stuck.go
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"slices"
+ "strings"
"gorm.io/gorm"
@@ -99,54 +100,30 @@ func (t *txn) offerRetry(r turnRecord, args json.RawMessage) (wire.ToolResult, e
return wire.ToolResult{Code: "offered", Text: toolRetryOffered}, nil
}
-// retryPreview runs a failed preview again as its next attempt, also when a
-// merge step came after it (the person's Retry on it, or retry_step): only
-// the task's newest preview, ended, of the candidate the task stands on
-// (approved, the branch at it), on a primary whose preview host the
-// project allows now. It is recomputed: the export is built and scanned
-// afresh and every publish is decided for that export (authorizePreview),
-// a public one only under the project's own setting. A preview is
-// ancillary, so the task's stage and its other steps are untouched.
+// retryPreview runs a preview again (the person's Retry on it, or
+// retry_step), also when a merge step came after it or the task is done:
+// only the task's newest preview, ended and not up, as previewRetryCheck
+// says. On a task still open it is the step's next attempt, of the
+// candidate the task stands on; on a done task a new preview step of
+// previewTarget (rerunPreview). It is recomputed: the export is built and
+// scanned afresh and every publish is decided for that export
+// (authorizePreview), a public one only under the project's own setting.
+// A preview is ancillary, so the task's stage and its other steps are
+// untouched.
func (t *txn) retryPreview(k *taskRecord, st *stepRecord, person string, coordinator bool) (int64, error) {
- if st.State != wire.StepFailed || !st.Terminated {
- return 0, ErrNotRetryable
- }
- if st.Person != person {
- return 0, ErrForbidden
- }
- steps, err := t.steps(k.ID)
- if err != nil {
- return 0, err
- }
- for _, s := range steps {
- if s.Specialist == wire.SpecialistPreview && s.Idx > st.Idx {
- return 0, ErrNotRetryable
- }
- }
- p := progressFor(*k, steps)
- if p.moved || p.candidate == "" || p.candidate != st.CandidateSHA || p.review == nil || p.review.State != wire.StepDone || p.review.Verdict != wire.VerdictApprove {
- return 0, ErrNotRetryable
- }
- primary, err := t.s.authority.PrimaryRunner(t.db, st.Person)
- if err != nil {
- return 0, err
- }
- rs, err := t.runners(st.Person)
- if err != nil {
+ reason, target, err := t.previewRetryCheck(*k, *st, person)
+ switch {
+ case err != nil:
return 0, err
+ case reason == retryNotYours:
+ return 0, refuseRetry(ErrForbidden, reason)
+ case reason == retryTaskCancelled:
+ return 0, refuseRetry(ErrTaskEnded, reason)
+ case reason != "":
+ return 0, refuseRetry(ErrNotRetryable, reason)
}
- allowed := false
- for _, r := range rs {
- if r.ID == primary && primary != "" {
- reason, err := t.previewHostAuthority(k.ProjectID, r)
- if err != nil {
- return 0, err
- }
- allowed = reason == ""
- }
- }
- if !allowed {
- return 0, ErrNotRetryable
+ if k.Stage == wire.StageDone {
+ return t.rerunPreview(k, st, target, coordinator)
}
st.Attempt++
st.State, st.Reason, st.Terminated, st.Summary, st.LogTail, st.StartedAt, st.FinishedAt, st.Headline, st.Activity = wire.StepQueued, "", false, "", "", nil, nil, "", ""
@@ -163,15 +140,22 @@ func (t *txn) retryPreview(k *taskRecord, st *stepRecord, person string, coordin
// More of what the model reads back for retry_step.
const (
- toolRetryKinds = "retry_step runs again only a failed preview, checks or review (step: preview, checks or review). A merge is the person's: use offer_retry. Engineering's work is theirs to ask for."
- toolRetryStarted = "Started again as attempt %d. Tell the person in one line; the task shows it."
- toolStepNotRetried = "Not started: that step has not failed and ended, is not the task's newest (a preview may be behind a merge), or its candidate is no longer the one to judge. read_task shows where it stands."
+ toolRetryKinds = "retry_step runs again only a failed preview, checks or review (step: preview, checks or review). A merge is the person's: use offer_retry. Engineering's work is theirs to ask for."
+ toolRetryStarted = "Started again as attempt %d. Tell the person in one line; the task shows it."
+ // A done task's preview runs again as a new step.
+ toolRetryNewPreview = "Started a new preview of the task's merged commit; the task stays done and merged. Tell the person in one line; the task shows it."
+ // The merged commit is not proven (merge_unverified), or Equipo did
+ // not merge it: the approved commit is built.
+ toolRetryApprovedPreview = "Started a new preview of the commit Review approved (Equipo could not prove the merged commit is exactly its merge, or did not merge it); the task stays done. Tell the person in one line; the task shows it."
+ toolStepNotRetried = "Not started: that step has not failed and ended, is not the task's newest (a preview may be behind a merge), or its candidate is no longer the one to judge. read_task shows where it stands."
)
// retryStepTool is the coordinator's retry_step: the person's Retry
// (personRetry, its checks for the turn's person), for the task's newest
// step of a kind in wire.RetryStepKinds, recorded as the coordinator's
// (CoordinatorAttempt) and audited. It never runs a merge or a publish.
+// On a done task only a preview runs again, as a new step of the merged
+// commit. A refusal says why in a fixed reason (retryNotes).
func (t *txn) retryStepTool(r turnRecord, args json.RawMessage) (wire.ToolResult, error) {
var in struct {
Task string `json:"task"`
@@ -183,31 +167,49 @@ func (t *txn) retryStepTool(r turnRecord, args json.RawMessage) (wire.ToolResult
if !slices.Contains(wire.RetryStepKinds, in.Step) {
return refused("invalid", toolRetryKinds), nil
}
- k, res, err := t.ownTask(r.Person, in.Task)
- if res != nil || err != nil {
- return deref(res), err
+ k, err := t.loadTask(strings.TrimSpace(in.Task))
+ if errors.Is(err, ErrNotFound) {
+ return refused("not_found", toolNoTask), nil
+ } else if err != nil {
+ return wire.ToolResult{}, err
+ }
+ if k.Creator != r.Person {
+ return refusedRetry("not_yours", retryNotYours), nil
}
var st stepRecord
if err := t.db.Where("task_id = ? AND specialist = ? AND coalesce(retired, 0) = 0", k.ID, in.Step).Order("idx DESC").First(&st).Error; errors.Is(err, gorm.ErrRecordNotFound) {
- return refused("not_retryable", toolStepNotRetried), nil
+ return refusedRetry("not_retryable", retryNoStep), nil
} else if err != nil {
return wire.ToolResult{}, err
}
attempt, err := t.personRetry(r.Person, k.ID, st.ID, true)
switch {
case errors.Is(err, ErrNotRetryable):
- return refused("not_retryable", toolStepNotRetried), nil
+ return refusedRetry("not_retryable", retryReasonOf(err, "not_retryable")), nil
case errors.Is(err, ErrTaskEnded):
- return refused("task_ended", toolTaskEnded), nil
+ return refusedRetry("task_ended", retryReasonOf(err, retryTaskCancelled)), nil
case errors.Is(err, ErrForbidden):
- return refused("not_yours", toolNotYours), nil
+ return refusedRetry("not_yours", retryReasonOf(err, retryNotYours)), nil
case err != nil:
return wire.ToolResult{}, err
}
+ text := fmt.Sprintf(toolRetryStarted, attempt)
+ var now stepRecord
+ if err := t.db.Where("task_id = ? AND specialist = ? AND coalesce(retired, 0) = 0", k.ID, in.Step).Order("idx DESC").First(&now).Error; err != nil {
+ return wire.ToolResult{}, err
+ }
+ if now.ID != st.ID {
+ // A done task's preview: a new step of the merged commit, or of the
+ // approved commit when the merged one is not proven.
+ text = toolRetryNewPreview
+ if now.CandidateSHA != k.MergedSHA {
+ text = toolRetryApprovedPreview
+ }
+ }
if t.s.authority.Audit != nil {
- if err := t.s.authority.Audit(t.db, "coordinator:"+r.Person, "task.retry", k.ID+"/"+st.ID+"/"+itoa64(attempt)); err != nil {
+ if err := t.s.authority.Audit(t.db, "coordinator:"+r.Person, "task.retry", k.ID+"/"+now.ID+"/"+itoa64(attempt)); err != nil {
return wire.ToolResult{}, err
}
}
- return wire.ToolResult{Code: "retrying", Text: fmt.Sprintf(toolRetryStarted, attempt)}, nil
+ return wire.ToolResult{Code: "retrying", Text: text}, nil
}
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index 3eba769f..2e798c0e 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -1233,7 +1233,7 @@ func (t *txn) dispatchStep(k *taskRecord, s *stepRecord) error {
}
// readTask is what the coordinator sees of a task.
-func (t *txn) readTask(id string) (wire.ToolResult, error) {
+func (t *txn) readTask(person, id string) (wire.ToolResult, error) {
k, err := t.loadTask(strings.TrimSpace(id))
if errors.Is(err, ErrNotFound) {
return refused("not_found", toolNoTask), nil
@@ -1251,10 +1251,17 @@ func (t *txn) readTask(id string) (wire.ToolResult, error) {
// The questions and answers are the person's with the specialists;
// the coordinator points people there and never relays them.
v.Questions = []wire.Question{}
+ // Whether each step retry_step may run again can run now, and if not
+ // why (a fixed reason), for this turn's person.
+ retry, err := t.retryViews(k, person)
+ if err != nil {
+ return wire.ToolResult{}, err
+ }
raw, _ := json.Marshal(struct {
- Link string `json:"link"`
+ Link string `json:"link"`
+ Retry []retryView `json:"retry,omitempty"`
wire.Task
- }{TaskLink(v.ID), v})
+ }{TaskLink(v.ID), retry, v})
return wire.ToolResult{Code: "task", Text: clipText(string(raw), 16<<10)}, nil
}
@@ -2028,11 +2035,14 @@ func (s *Store) retryTask(ctx context.Context, person, id, step string) (attempt
}
// personRetry is the person's Retry of the task's step ("" for its newest
-// step): an owner, the task's creator, a task that has not ended. The
-// coordinator's retry_step makes exactly these checks for its person
-// (coordinator), on RetryStepKinds only.
+// step): an owner, the task's creator, a task not cancelled; on a done
+// task only its preview (retryStepOf). The coordinator's retry_step makes
+// exactly these checks for its person (coordinator), on RetryStepKinds
+// only. A refusal carries its fixed reason (retryRefusal).
func (t *txn) personRetry(person, id, step string, coordinator bool) (int64, error) {
- if err := t.isOwner(person); err != nil {
+ if err := t.isOwner(person); errors.Is(err, ErrForbidden) {
+ return 0, refuseRetry(ErrForbidden, retryNotOwner)
+ } else if err != nil {
return 0, err
}
k, err := t.loadTask(id)
@@ -2041,10 +2051,10 @@ func (t *txn) personRetry(person, id, step string, coordinator bool) (int64, err
}
// Only the task's creator retries it, onto their own runner.
if k.Creator != person {
- return 0, ErrForbidden
+ return 0, refuseRetry(ErrForbidden, retryNotYours)
}
- if wire.FinalStage(k.Stage) || k.CancelRequested {
- return 0, ErrTaskEnded
+ if k.Stage == wire.StageCancelled || k.CancelRequested {
+ return 0, refuseRetry(ErrTaskEnded, retryTaskCancelled)
}
return t.retryStepOf(&k, person, step, coordinator)
}
@@ -2072,12 +2082,15 @@ func (t *txn) retryStepOf(k *taskRecord, person, step string, coordinator bool)
if step != "" {
var named stepRecord
if err := t.db.Where("id = ? AND task_id = ? AND coalesce(retired, 0) = 0", step, k.ID).First(&named).Error; errors.Is(err, gorm.ErrRecordNotFound) {
- return 0, ErrNotRetryable
+ return 0, refuseRetry(ErrNotRetryable, retryNoStep)
} else if err != nil {
return 0, err
}
if named.Specialist != wire.SpecialistPreview && (!found || named.ID != st.ID) {
- return 0, ErrNotRetryable
+ if k.Stage == wire.StageDone {
+ return 0, refuseRetry(ErrTaskEnded, retryTaskDone)
+ }
+ return 0, refuseRetry(ErrNotRetryable, retryNotNewest)
}
st, found = named, true
}
@@ -2087,6 +2100,11 @@ func (t *txn) retryStepOf(k *taskRecord, person, step string, coordinator bool)
if found && st.Specialist == wire.SpecialistPreview {
return t.retryPreview(k, &st, person, coordinator)
}
+ if wire.FinalStage(k.Stage) {
+ // A done task runs only its preview again; its merge, checks and
+ // review stay as they are.
+ return 0, refuseRetry(ErrTaskEnded, retryTaskDone)
+ }
if found && st.Specialist == wire.SpecialistEngineering && st.State == wire.StepDone && st.Publication == wire.PublicationFailed {
// A worker's commit the primary could not push: publish the
// recorded commit again, without running Engineering.
@@ -2102,11 +2120,11 @@ func (t *txn) retryStepOf(k *taskRecord, person, step string, coordinator bool)
attempt = st.Attempt
return attempt, t.saveTask(k)
}
- if !found || st.State != wire.StepFailed || !st.Terminated {
- return 0, ErrNotRetryable
+ if reason := endedReason(st, found); reason != "" {
+ return 0, refuseRetry(ErrNotRetryable, reason)
}
if st.Person != person {
- return 0, ErrForbidden
+ return 0, refuseRetry(ErrForbidden, retryNotYours)
}
if st.Specialist == wire.SpecialistMerge {
// Never merge a SHA that is not the judged one, as it stands; a
@@ -2120,7 +2138,7 @@ func (t *txn) retryStepOf(k *taskRecord, person, step string, coordinator bool)
}
p := progressFor(*k, steps)
if p.candidate != st.CandidateSHA || !p.mergeAllowed(st.WithoutChecks) {
- return 0, ErrNotRetryable
+ return 0, refuseRetry(ErrNotRetryable, retryCommitChanged)
}
_, protocol, err := t.primaryState(st.Person)
if err != nil {
@@ -2138,7 +2156,7 @@ func (t *txn) retryStepOf(k *taskRecord, person, step string, coordinator bool)
return 0, err
}
if primary == "" {
- return 0, ErrNotRetryable
+ return 0, refuseRetry(ErrNotRetryable, retryNoRunner)
}
from := st.Attempt
st.Attempt++
@@ -2359,7 +2377,7 @@ func (t *txn) runTaskTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, erro
if wire.Strict(v.Args, &in) != nil {
return refused("invalid", toolBadInput), nil
}
- return t.readTask(in.Task)
+ return t.readTask(r.Person, in.Task)
case wire.ToolCancelTask:
var in struct {
Task string `json:"task"`
diff --git a/internal/equipo/preview_pass_store.go b/internal/equipo/preview_pass_store.go
index 0286de4f..f236fe96 100644
--- a/internal/equipo/preview_pass_store.go
+++ b/internal/equipo/preview_pass_store.go
@@ -114,10 +114,15 @@ func (s *Store) previewDeployment(task wire.Task) (wire.Step, string, error) {
}
func (s *Store) validatePreview(task wire.Task, b previewBinding) error {
step, fingerprint, err := s.previewDeployment(task)
- if task.CandidateSHA != b.Candidate || err != nil || step.CandidateSHA != b.Candidate || step.ID != b.StepID || step.Attempt != b.Attempt || fingerprint != b.Fingerprint {
+ // Of the task's candidate, or, once it is done, of its merged commit
+ // (a preview run again after the merge).
+ merged := task.Stage == wire.StageDone && task.Merged != nil && task.Merged.SHA != "" && step.CandidateSHA == task.Merged.SHA
+ if task.CandidateSHA != b.Candidate || err != nil || step.CandidateSHA != b.Candidate && !merged || step.ID != b.StepID || step.Attempt != b.Attempt || fingerprint != b.Fingerprint {
return ErrPreviewChanged
}
- if (step.Preview.ExpiresAt != nil && !s.runnerClock.Now().Before(*step.Preview.ExpiresAt)) || (strings.HasPrefix(step.Preview.App, "eq-") && wire.FinalStage(task.Stage)) {
+ // A devbox link comes down with its task, unless it came up after the
+ // task was done (a preview run again on a merged task).
+ if (step.Preview.ExpiresAt != nil && !s.runnerClock.Now().Before(*step.Preview.ExpiresAt)) || (strings.HasPrefix(step.Preview.App, "eq-") && wire.FinalStage(task.Stage) && !devboxAfterDone(task, step)) {
return ErrPreviewExpired
}
return nil
diff --git a/internal/equipo/work_views.go b/internal/equipo/work_views.go
index 562eb714..e865b8e3 100644
--- a/internal/equipo/work_views.go
+++ b/internal/equipo/work_views.go
@@ -1148,7 +1148,11 @@ func timelineOf(t wire.Task, v taskLine) []timelineItem {
out = append(out, it)
continue
case wire.StepCancelled:
- out = append(out, timelineItem{Kind: "stopped", What: fmt.Sprintf(copyText("work.tl.cancelled"), title), At: s.FinishedAt})
+ it := timelineItem{Kind: "stopped", What: fmt.Sprintf(copyText("work.tl.cancelled"), title), At: s.FinishedAt}
+ if previewRetry(t, s, v.Mine) {
+ it.RetryPost, it.RetryStep = "/conversation/tasks/"+t.ID+"/retry", s.ID
+ }
+ out = append(out, it)
continue
}
switch s.Specialist {
@@ -1199,6 +1203,10 @@ func timelineOf(t wire.Task, v taskLine) []timelineItem {
if s.Preview.Outcome == wire.PreviewDeployed && s.Preview.URL != "" {
it.What, it.Markdown = copyText("work.tl.preview_ready"), "["+previewHostLabel(s.Preview.URL)+"](/tasks/"+t.ID+"/preview)"
}
+ if previewRetry(t, s, v.Mine) {
+ // Unconfirmed, or its link is gone: Retry, as for a failed one.
+ it.RetryPost, it.RetryStep = "/conversation/tasks/"+t.ID+"/retry", s.ID
+ }
out = append(out, it)
case wire.SpecialistReview:
one := t
@@ -1265,12 +1273,17 @@ func timelineOf(t wire.Task, v taskLine) []timelineItem {
return out
}
-// previewRetry reports whether the person may run a failed preview again
-// from its own entry: theirs, ended, the task's newest preview, of the
-// candidate the task stands on, the task not ended. The store decides
-// again (retryPreview).
+// previewRetry reports whether the person may run a preview again from
+// its own entry: theirs, ended without a link up now (failed, cancelled,
+// unconfirmed, expired, or a devbox link gone with its task), the task's
+// newest preview, of the candidate the task stands on, or on a done task
+// any (it builds the merged commit), the task not cancelled. The store
+// decides again (previewRetryCheck).
func previewRetry(t wire.Task, s wire.Step, mine bool) bool {
- if !mine || s.Specialist != wire.SpecialistPreview || s.State != wire.StepFailed || !s.Terminated || wire.FinalStage(t.Stage) || t.CandidateSHA == "" || s.CandidateSHA != t.CandidateSHA {
+ if !mine || s.Specialist != wire.SpecialistPreview || !wire.StepTerminal(s.State) || !s.Terminated || t.Stage == wire.StageCancelled || previewShown(t, s, time.Now()) && !devboxAfterDone(t, s) {
+ return false
+ }
+ if t.Stage != wire.StageDone && (t.CandidateSHA == "" || s.CandidateSHA != t.CandidateSHA) {
return false
}
for _, o := range t.Steps {
@@ -1281,6 +1294,31 @@ func previewRetry(t wire.Task, s wire.Step, mine bool) bool {
return true
}
+// previewShown reports whether a preview step's link is up now: deployed,
+// before any expiry, and a devbox link only while its task runs or one
+// that came up after its task was done (the store's previewUp, without a
+// Publish hold, which only keeps a link up longer).
+func previewShown(t wire.Task, s wire.Step, now time.Time) bool {
+ p := s.Preview
+ if s.State != wire.StepDone || p == nil || p.Outcome != wire.PreviewDeployed || p.URL == "" {
+ return false
+ }
+ if p.ExpiresAt != nil && !p.ExpiresAt.After(now) {
+ return false
+ }
+ if strings.HasPrefix(p.App, "eq-") && wire.FinalStage(t.Stage) {
+ return devboxAfterDone(t, s)
+ }
+ return true
+}
+
+// devboxAfterDone: a devbox link that came up after its task was done (a
+// preview run again on a merged task); any other comes down with the
+// task. It stays up until the task's next preview replaces it.
+func devboxAfterDone(t wire.Task, s wire.Step) bool {
+ return s.Preview != nil && strings.HasPrefix(s.Preview.App, "eq-") && t.Stage == wire.StageDone && t.DoneAt != nil && s.FinishedAt != nil && s.FinishedAt.After(*t.DoneAt)
+}
+
// sentenceCase capitalises a reason fragment for a line of its own.
func sentenceCase(s string) string {
if s == "" {
@@ -1545,8 +1583,9 @@ func previewCard(t wire.Task, now time.Time) (url, line string) {
p := s.Preview
if strings.HasPrefix(p.App, "eq-") {
// A CARLOS devbox link: no expiry; it comes down when the task
- // ends, and so does the line.
- if wire.FinalStage(t.Stage) {
+ // ends, and so does the line; one run again after the task was
+ // done stays until the next run replaces it.
+ if wire.FinalStage(t.Stage) && (!devboxAfterDone(t, s) || p.ExpiresAt != nil && !p.ExpiresAt.After(now)) {
return "", ""
}
return "/tasks/" + t.ID + "/preview", fmt.Sprintf(copyText("work.card.preview_tailnet"), previewHostLabel(p.URL))
diff --git a/internal/runner/thin/mcp.go b/internal/runner/thin/mcp.go
index a37cd600..9bec432b 100644
--- a/internal/runner/thin/mcp.go
+++ b/internal/runner/thin/mcp.go
@@ -172,7 +172,7 @@ var converseTools = []any{
map[string]any{"name": "propose_specialist", "description": "Ask the person to add a specialist to their team, from Equipo's fixed menu. Only when the person wants something researched on the public web. The one profile is research-v1: it reads public web pages Equipo fetches for a task and reports what they say; it never reaches repositories. Pass profile research-v1, a short name (for example Research), a brief of at most 2 KB on what it should look for, capabilities [\"web.research\"] and tools [\"submit_findings\", \"keep_image\"], exactly those. Nothing is added until an owner taps Add on the card it raises; do not ask again in your reply. If they tap Not now, propose it again only when they ask.", "inputSchema": toolSchema(map[string]any{"profile": map[string]any{"type": "string", "enum": []string{"research-v1"}}, "name": str, "brief": str, "capabilities": map[string]any{"type": "array", "items": str}, "tools": map[string]any{"type": "array", "items": str}}, "profile", "name", "brief", "capabilities", "tools")},
map[string]any{"name": "research", "description": "Ask Research (once it is on the team; see propose_specialist) to read public web pages for one of the person's tasks. Use it when an exploration or change names an outside site, brand, API or docs, or the person asking (their business, their own site), and the work needs what those pages say. task is the task id; question (at most 1,000 bytes) is what to look for, for example colours, logo, fonts, opening hours and services; urls are pages you propose (https or http, no query string, a path of at most 100 characters, at most 10), or []. URLs and bare domains the person typed on the task are read without asking; your urls are shown to the person in full on a card and read only if they tap Allow, so propose only pages the task needs and never put anything from a repository in them. This only requests a run: Equipo starts it only at the task's start (call it before start_task) or after a review round, before Engineering's next round, and Engineering waits until Research ends. At most one run per start or round and 3 per task, and Equipo never retries a run for you. Research's findings reach Engineering and Review; do not wait for them in your reply.", "inputSchema": toolSchema(map[string]any{"task": str, "question": str, "urls": map[string]any{"type": "array", "items": str, "maxItems": 10}}, "task", "question", "urls")},
map[string]any{"name": wire.ToolOfferRetry, "description": "When a task's merge failed and it waits at Ready to merge (read_task shows the failed merge step), put a card in front of the person asking whether to try the merge again. You cannot merge: only their tap merges, through Equipo's merge rules, and it is offered only when that tap could merge now. One card per task; do not ask again in your reply, and never say it is merged.", "inputSchema": toolSchema(map[string]any{"task": str}, "task")},
- map[string]any{"name": wire.ToolRetryStep, "description": "Run a task's failed preview, checks or review again, as the person's own Retry would (step: preview, checks or review). Only when read_task shows that step failed and why, and another try could help: a preview that failed for its scanner (status runner.tools) needs the runner fixed first. Never a merge (use offer_retry: only the person's tap merges) and never Engineering's work. The task shows that you started it. Call it once per step.", "inputSchema": toolSchema(map[string]any{"task": str, "step": map[string]any{"type": "string", "enum": wire.RetryStepKinds}}, "task", "step")},
+ map[string]any{"name": wire.ToolRetryStep, "description": "Run a task's preview, checks or review again, as the person's own Retry would (step: preview, checks or review). read_task's retry says for each whether it can run again now, and if not why, in a fixed reason; a refusal says it too. A failed step runs again as its next attempt. A preview also runs again when it ended unconfirmed or its link is gone, and on a done (merged) task as a new preview of the merged commit, the task staying done and merged. Only when another try could help: a preview that failed for its scanner (status runner.tools) needs the runner fixed first. Never a merge (use offer_retry: only the person's tap merges) and never Engineering's work. The task shows that you started it. Call it once per step.", "inputSchema": toolSchema(map[string]any{"task": str, "step": map[string]any{"type": "string", "enum": wire.RetryStepKinds}}, "task", "step")},
}
// stepTools are the tools the implement profile pins for an Engineering
diff --git a/internal/runner/thin/merge_identity_test.go b/internal/runner/thin/merge_identity_test.go
new file mode 100644
index 00000000..f04f18d4
--- /dev/null
+++ b/internal/runner/thin/merge_identity_test.go
@@ -0,0 +1,95 @@
+package thin
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strconv"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Merge identity (Astra, previews on done tasks): the commit a landing
+// names is publication authority only when it is proven to be the merge
+// of the approved candidate. These are the shapes, in real git, where the
+// runner's reconciled landing (inspectMerge) names something else: a
+// nested merge, or a merge more than 200 first-parent commits back, are
+// named by the default branch's tip, which holds later work. The
+// instance builds the approved candidate then (chat.verifiedMerge); only
+// the hub's own answer, with the candidate as second parent, is the merge.
+
+// landedThenMoved merges the candidate through the hub, then lets main
+// move on with work in a clone of the remote.
+func landedThenMoved(t *testing.T, more func(work string)) (*Engineer, *hubForge, stepRow, string, string) {
+ t.Helper()
+ e, f, r, cand := hubRig(t)
+ rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
+ if rep.State != wire.StepDone || rep.MergeSource != wire.MergeSourceHub || len(rep.MergeParents) != 2 || rep.MergeParents[1] != cand {
+ t.Fatalf("hub merge %+v", rep)
+ }
+ work := filepath.Join(t.TempDir(), "later")
+ gitOut(t, filepath.Dir(work), "clone", "-q", f.dir, work)
+ more(work)
+ gitOut(t, work, "push", "-q", "-f", "origin", "HEAD:main")
+ return e, f, r, cand, rep.MergeSHA
+}
+
+func commitFile(t *testing.T, work, name, body string) {
+ t.Helper()
+ if err := os.WriteFile(filepath.Join(work, name), []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ gitOut(t, work, "add", "-A")
+ gitOut(t, work, "commit", "-q", "-m", name)
+}
+
+// TestMergeIdentityLaterCommits: later commits after the merge leave the
+// merge commit itself the one that brought the candidate in.
+func TestMergeIdentityLaterCommits(t *testing.T) {
+ e, f, r, cand, merge := landedThenMoved(t, func(work string) {
+ for i := range 3 {
+ commitFile(t, work, "later-"+strconv.Itoa(i), "later\n")
+ }
+ })
+ st, err := e.inspectMerge(context.Background(), r.Repo, r.Branch, cand)
+ tip := gitOut(t, f.dir, "rev-parse", "main")
+ if err != nil || !st.Landed || st.MergeSHA != merge || tip == merge {
+ t.Fatalf("inspect %+v %v (merge %s, tip %s)", st, err, merge, tip)
+ }
+}
+
+// TestMergeIdentityFallsBackToTheTip: a nested merge (the candidate came
+// in through another branch's merge) and a merge more than 200
+// first-parent commits back are both named by the tip, whose parents do
+// not have the candidate second: never proof of the merge.
+func TestMergeIdentityFallsBackToTheTip(t *testing.T) {
+ for name, more := range map[string]func(string){
+ "nested": func(work string) {
+ // The candidate reaches main only through another branch's
+ // merge: integration merges it, then main merges integration.
+ gitOut(t, work, "checkout", "-q", "-b", "integration", "main~1")
+ gitOut(t, work, "merge", "-q", "--no-ff", "-m", "integration", "main^2")
+ commitFile(t, work, "integration-only", "x\n")
+ gitOut(t, work, "checkout", "-q", "-B", "main", "origin/main~1")
+ gitOut(t, work, "merge", "-q", "--no-ff", "-m", "bring integration", "integration")
+ },
+ "far": func(work string) {
+ for i := range 201 {
+ commitFile(t, work, "far", strconv.Itoa(i)+"\n")
+ }
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ e, f, r, cand, _ := landedThenMoved(t, more)
+ st, err := e.inspectMerge(context.Background(), r.Repo, r.Branch, cand)
+ tip := gitOut(t, f.dir, "rev-parse", "main")
+ if err != nil || !st.Landed || st.MergeSHA != tip {
+ t.Fatalf("inspect %+v %v (tip %s)", st, err, tip)
+ }
+ if parents := e.mergeParents(context.Background(), r.Repo, tip); len(parents) == 2 && parents[1] == cand {
+ t.Fatalf("the tip reads as the candidate's merge: %v", parents)
+ }
+ })
+ }
+}
diff --git a/internal/thintest/preview_retry_done_contract_test.go b/internal/thintest/preview_retry_done_contract_test.go
new file mode 100644
index 00000000..369c925d
--- /dev/null
+++ b/internal/thintest/preview_retry_done_contract_test.go
@@ -0,0 +1,499 @@
+package thintest
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Previews on finished tasks (Paul, 2026-11-26, production): "Retry the
+// Neary's preview" was refused because both tasks were merged and done,
+// one preview failed for its scanner and the other ended unconfirmed
+// (preview_headers), which did not count as a failure. A preview runs
+// again on a merged task from its merged commit, by the person's Retry or
+// the coordinator's retry_step, through the preview's own checks; the
+// task's stage, merge and other steps stay as they are. An unconfirmed
+// preview, or one whose link is gone, counts as one to run again. A
+// refusal says why in a fixed reason, in the tool's result and in
+// read_task.
+
+var mergedSHA = strings.Repeat("9", 40)
+
+// previewedThenMerged is previewedAndMerging with the preview ended by
+// end and the merge confirmed as mergedSHA, the hub's own merge commit
+// with the candidate as second parent: the task is done.
+func (r *toolRig) previewedThenMerged(key, base, cand string, end func(id string, pv *wire.DispatchCommand)) (string, *wire.DispatchCommand, *wire.DispatchCommand) {
+ r.t.Helper()
+ return r.previewedThenLanded(key, base, cand, end, func(m *wire.DispatchCommand) {
+ r.landed(key+"-m", m, mergedSHA, wire.MergeSourceHub, []string{base, cand})
+ })
+}
+
+// landed reports a merge step done as sha, from source with parents.
+func (r *toolRig) landed(key string, d *wire.DispatchCommand, sha, source string, parents []string) {
+ r.t.Helper()
+ r.step(key+"-run", wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: d.BaseSHA, CandidateSHA: d.CandidateSHA})
+ r.step(key, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, BaseSHA: d.BaseSHA, CandidateSHA: d.CandidateSHA, Termination: true, Findings: []wire.Finding{}, MergeSHA: sha, Into: "main", Strategy: wire.MergeCommit, MergeSource: source, MergeParents: parents})
+}
+
+// previewedThenLanded is previewedThenMerged with the merge reported by
+// land.
+func (r *toolRig) previewedThenLanded(key, base, cand string, end func(id string, pv *wire.DispatchCommand), land func(m *wire.DispatchCommand)) (string, *wire.DispatchCommand, *wire.DispatchCommand) {
+ r.t.Helper()
+ r.asksBeforeMerging()
+ id, _ := r.pushed(key, "Barber mockups", base, cand)
+ r.expect(wire.FrameWatchMerge)
+ c := r.dispatched(wire.SpecialistChecks, base, cand, 0)
+ r.checks(key+"-c", c, wire.ChecksPassed, exit(0), "", "ok\n")
+ rv := r.dispatched(wire.SpecialistReview, base, cand, 0)
+ r.step(key+"-r", wire.StepReport{TaskID: rv.TaskID, StepID: rv.StepID, Attempt: rv.Attempt, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Termination: true, Family: "codex", Account: "codex-a", Verdict: wire.VerdictApprove, ReviewLabel: wire.ReviewOtherFamily, Findings: []wire.Finding{}, Summary: "Read it.", HasPreview: true, Change: facts(rv)})
+ pv := r.previewDispatch(cand)
+ if pv == nil {
+ r.t.Fatal("no preview dispatched")
+ }
+ r.built(key+"-pv-built", pv, digestA)
+ end(id, pv)
+ // The preview's outcome may give the merge card a new revision.
+ var seen int64
+ for {
+ var card wire.Card
+ r.wait("merge card", func(c *Conversation) bool {
+ for _, k := range c.Cards {
+ if k.Kind == wire.CardMerge && k.TaskID == id && k.State == wire.CardOpen && k.Revision > seen {
+ card = k
+ }
+ }
+ return card.ID != ""
+ })
+ _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceMerge, card.Revision)
+ if err == nil {
+ break
+ }
+ if Status(err) != http.StatusConflict || seen > 5 {
+ r.t.Fatal(err)
+ }
+ seen = card.Revision
+ }
+ m := r.dispatched(wire.SpecialistMerge, base, cand, 0)
+ land(m)
+ r.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone })
+ return id, pv, m
+}
+
+// failedPreview ends a preview the way tkbstr6cjl7h's did.
+func (r *toolRig) failedPreview(reason string) func(string, *wire.DispatchCommand) {
+ return func(id string, pv *wire.DispatchCommand) {
+ r.step(id+"-pv-fail", wire.StepReport{TaskID: id, StepID: pv.StepID, Attempt: pv.Attempt, State: wire.StepFailed, Reason: reason, BaseSHA: pv.BaseSHA, CandidateSHA: pv.CandidateSHA, Termination: true, Findings: []wire.Finding{}})
+ }
+}
+
+// unconfirmedPreview ends a preview the way tkzmnycab3ml's did: done, its
+// link not confirmed, for reason.
+func (r *toolRig) unconfirmedPreview(reason, app string) func(string, *wire.DispatchCommand) {
+ return func(id string, pv *wire.DispatchCommand) {
+ r.step(id+"-pv-unconfirmed", wire.StepReport{TaskID: id, StepID: pv.StepID, Attempt: pv.Attempt, State: wire.StepDone, Reason: reason, BaseSHA: pv.BaseSHA, CandidateSHA: pv.CandidateSHA, Termination: true, Findings: []wire.Finding{}, Preview: &wire.PreviewResult{Phase: wire.PreviewDone, App: app + id, Digest: digestA, Outcome: wire.PreviewUnconfirmed}})
+ }
+}
+
+// refusal is a refused retry_step's fixed reason.
+func refusal(t *testing.T, res wire.ToolResult) string {
+ t.Helper()
+ var out struct {
+ Reason string `json:"reason"`
+ Note string `json:"note"`
+ }
+ if !res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil || out.Reason == "" || out.Note == "" {
+ t.Fatalf("not a refusal with a reason: %+v", res)
+ }
+ return out.Reason
+}
+
+// retryOf is read_task's word on running the task's newest step of kind
+// again: "" when it can run, else the fixed reason it cannot.
+func (r *toolRig) retryOf(key, id, kind string) (string, bool) {
+ r.t.Helper()
+ res := r.call(key, wire.ToolReadTask, map[string]string{"task": id})
+ var out struct {
+ Retry []struct {
+ Step string `json:"step"`
+ StepID string `json:"step_id"`
+ Retryable bool `json:"retryable"`
+ Reason string `json:"reason"`
+ } `json:"retry"`
+ }
+ if res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil {
+ r.t.Fatalf("read_task %+v", res)
+ }
+ for _, x := range out.Retry {
+ if x.Step == kind {
+ if x.Retryable == (x.Reason != "") || x.StepID == "" {
+ r.t.Fatalf("read_task retry %+v", x)
+ }
+ return x.Reason, true
+ }
+ }
+ return "", false
+}
+
+// TestContractRetryPreviewOnMergedTask (tkbstr6cjl7h): the person's Retry
+// on a done task's failed preview builds the merged commit as a new
+// preview step, published only through the preview's checks; the task
+// stays done, merged as it was, and its earlier steps are untouched.
+func TestContractRetryPreviewOnMergedTask(t *testing.T) {
+ r := publicPreviewRig(t)
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ id, pv, m := r.previewedThenMerged("pd", base, cand, r.failedPreview("preview_scanner"))
+ before, _ := r.client.Task(r.ctx, id)
+ if before.Stage != wire.StageDone || before.Merged == nil || before.Merged.SHA != mergedSHA {
+ t.Fatalf("not merged %+v", before)
+ }
+ page := r.get(r.inst.Cookie(), "/tasks/"+id, 200)
+ if !strings.Contains(page, `<input type="hidden" name="step" value="`+pv.StepID+`">`) || !strings.Contains(page, "data-step-retry") {
+ t.Fatal("the done task's failed preview offers no Retry")
+ }
+ if p := r.get(r.memberCookie(), "/tasks/"+id, 200); strings.Contains(p, "data-step-retry") {
+ t.Fatal("a teammate is offered the preview's Retry")
+ }
+ // Retry with no step means the newest step, the merge: never run again.
+ if _, err := r.client.RetryTask(r.ctx, id); Status(err) != http.StatusConflict {
+ t.Fatalf("Retry of the done task's merge: %v", err)
+ }
+ if status, at := r.post(r.inst.Cookie(), "/conversation/tasks/"+id+"/retry", url.Values{"from": {"task"}, "step": {pv.StepID}}); status != http.StatusSeeOther || at != "/tasks/"+id {
+ t.Fatalf("Retry the preview: %d %s", status, at)
+ }
+ again := r.previewDispatch(mergedSHA)
+ if again == nil || again.StepID == pv.StepID || again.Attempt != 1 || again.CandidateSHA != mergedSHA {
+ t.Fatalf("the preview of the merged commit %+v", again)
+ }
+ k, _ := r.client.Task(r.ctx, id)
+ if k.Stage != wire.StageDone || k.Merged == nil || *k.Merged != *before.Merged || k.DoneAt == nil || !k.DoneAt.Equal(*before.DoneAt) || len(k.Steps) != len(before.Steps)+1 {
+ t.Fatalf("the re-run moved the task %+v", k)
+ }
+ for i, s := range before.Steps {
+ got := k.Steps[i]
+ if got.ID != s.ID || got.State != s.State || got.Attempt != s.Attempt || got.Reason != s.Reason || got.CandidateSHA != s.CandidateSHA || got.MergeSHA != s.MergeSHA {
+ t.Fatalf("step %d changed: %+v to %+v", i, s, got)
+ }
+ }
+ if s := k.Steps[len(k.Steps)-1]; s.ID != again.StepID || s.Specialist != wire.SpecialistPreview || s.State != wire.StepQueued || s.CandidateSHA != mergedSHA || s.RetriedBy != "" {
+ t.Fatalf("the new preview step %+v", s)
+ }
+ if s := k.Steps[len(k.Steps)-2]; s.ID != m.StepID || s.State != wire.StepDone || s.MergeSHA != mergedSHA {
+ t.Fatalf("the merge %+v", s)
+ }
+ // Asked again while it runs: nothing more.
+ r.post(r.inst.Cookie(), "/conversation/tasks/"+id+"/retry", url.Values{"from": {"task"}, "step": {again.StepID}})
+ if extra := r.previewDispatch(mergedSHA); extra != nil {
+ t.Fatalf("a second preview %+v", extra)
+ }
+ // Published only through the preview's own checks, for its export.
+ if refused := r.lease(r.runner, "pd-start", wire.LeaseCheck{StepID: again.StepID, Attempt: 1}); refused != "" {
+ t.Fatalf("start refused %q", refused)
+ }
+ if refused := r.lease(r.runner, "pd-early", wire.LeaseCheck{StepID: again.StepID, Attempt: 1, Purpose: wire.LeasePurposePreview, Digest: digestB}); refused != wire.RefusedPreviewNotBuilt {
+ t.Fatalf("publish before built: %q", refused)
+ }
+ r.built("pd-built", again, digestB)
+ if refused := r.lease(r.runner, "pd-wrong", wire.LeaseCheck{StepID: again.StepID, Attempt: 1, Purpose: wire.LeasePurposePreview, Digest: digestA}); refused != "withdrawn" {
+ t.Fatalf("publish of another export: %q", refused)
+ }
+ if refused := r.lease(r.runner, "pd-pub", wire.LeaseCheck{StepID: again.StepID, Attempt: 1, Purpose: wire.LeasePurposePreview, Digest: digestB}); refused != "" {
+ t.Fatalf("publish refused %q", refused)
+ }
+ expires := time.Now().Add(7 * 24 * time.Hour).UTC().Truncate(time.Second)
+ link := "https://tmp-" + id + ".bds.oncarlos.com/"
+ r.previewDone("pd-up", again, wire.PreviewResult{Phase: wire.PreviewDone, App: "tmp-" + id, URL: link, Digest: digestB, ExpiresAt: &expires, Outcome: wire.PreviewDeployed})
+ k, _ = r.client.Task(r.ctx, id)
+ if k.Stage != wire.StageDone || *k.Merged != *before.Merged || !strings.HasSuffix(k.PreviewURL, "/tasks/"+id+"/preview") {
+ t.Fatalf("after the re-run: %s %+v %q", k.Stage, k.Merged, k.PreviewURL)
+ }
+ if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); !strings.Contains(page, "data-preview") || strings.Contains(page, "data-step-retry") {
+ t.Fatal("the re-run's link is not shown, or Retry is still offered while it is up")
+ }
+ if page := r.get(r.inst.Cookie(), "/tasks/"+id+"/preview", 200); !strings.Contains(page, `src="`+link+`"`) {
+ t.Fatal("the preview page does not open the re-run")
+ }
+}
+
+// TestContractCoordinatorRetryUnconfirmedPreviewOnMergedTask
+// (tkzmnycab3ml): a done task's preview that ended unconfirmed
+// (preview_headers) is the coordinator's to run again, once per task in
+// a turn, from the merged commit; the page credits the coordinator.
+func TestContractCoordinatorRetryUnconfirmedPreviewOnMergedTask(t *testing.T) {
+ r := publicPreviewRig(t)
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ id, pv, _ := r.previewedThenMerged("pu", base, cand, r.unconfirmedPreview("preview_headers", "tmp-"))
+ if reason, ok := r.retryOf("pu-read", id, wire.SpecialistPreview); !ok || reason != "" {
+ t.Fatalf("read_task: the unconfirmed preview is not retryable (%q)", reason)
+ }
+ res := r.call("pu1", wire.ToolRetryStep, map[string]string{"task": id, "step": wire.SpecialistPreview})
+ if res.IsError || res.Code != "retrying" {
+ t.Fatalf("retry_step %+v", res)
+ }
+ again := r.previewDispatch(mergedSHA)
+ if again == nil || again.StepID == pv.StepID || again.Attempt != 1 {
+ t.Fatalf("the preview of the merged commit %+v", again)
+ }
+ k, _ := r.client.Task(r.ctx, id)
+ if s := k.Steps[len(k.Steps)-1]; s.ID != again.StepID || s.RetriedBy != wire.RetriedByCoordinator || k.Stage != wire.StageDone {
+ t.Fatalf("the coordinator's preview %+v (%s)", s, k.Stage)
+ }
+ if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); !strings.Contains(page, "The coordinator started Preview again.") {
+ t.Fatal("the timeline does not say the coordinator started it")
+ }
+ if r.audits("task.retry") != 1 {
+ t.Fatalf("audits %d", r.audits("task.retry"))
+ }
+ if reason, _ := r.retryOf("pu-read2", id, wire.SpecialistPreview); reason != "not_ended" {
+ t.Fatalf("read_task while it runs: %q", reason)
+ }
+ // Once per task in a turn: a fresh call while it runs, and again once
+ // it failed and ended, is answered by the ledger; nothing more runs.
+ if res := r.call("pu2", wire.ToolRetryStep, map[string]string{"task": id, "step": wire.SpecialistPreview}); res.IsError || !res.Replayed {
+ t.Fatalf("second retry_step %+v", res)
+ }
+ r.step("pu-again-fail", wire.StepReport{TaskID: id, StepID: again.StepID, Attempt: 1, State: wire.StepFailed, Reason: "preview_failed", BaseSHA: again.BaseSHA, CandidateSHA: mergedSHA, Termination: true, Findings: []wire.Finding{}})
+ if res := r.call("pu3", wire.ToolRetryStep, map[string]string{"task": id, "step": wire.SpecialistPreview}); res.IsError || !res.Replayed {
+ t.Fatalf("retry_step after the re-run failed %+v", res)
+ }
+ if extra := r.previewDispatch(mergedSHA); extra != nil || r.audits("task.retry") != 1 {
+ t.Fatalf("a second preview in the turn %+v", extra)
+ }
+ if k2, _ := r.client.Task(r.ctx, id); len(k2.Steps) != len(k.Steps) || k2.Stage != wire.StageDone {
+ t.Fatalf("steps %d to %d, stage %s", len(k.Steps), len(k2.Steps), k2.Stage)
+ }
+}
+
+// TestContractRetryUnconfirmedPreview: on a task still open, a preview
+// that ended unconfirmed is offered and run again as its next attempt.
+func TestContractRetryUnconfirmedPreview(t *testing.T) {
+ r := publicPreviewRig(t)
+ r.asksBeforeMerging()
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ id, d := r.approvedWithPreview("uc", base, cand, true)
+ if d == nil {
+ t.Fatal("no preview")
+ }
+ r.built("uc-built", d, digestA)
+ r.unconfirmedPreview("preview_failed", "tmp-")(id, d)
+ page := r.get(r.inst.Cookie(), "/tasks/"+id, 200)
+ if !strings.Contains(page, `<input type="hidden" name="step" value="`+d.StepID+`">`) {
+ t.Fatal("an unconfirmed preview offers no Retry")
+ }
+ if status, _ := r.post(r.inst.Cookie(), "/conversation/tasks/"+id+"/retry", url.Values{"from": {"task"}, "step": {d.StepID}}); status != http.StatusSeeOther {
+ t.Fatalf("Retry %d", status)
+ }
+ again := r.previewDispatch(cand)
+ if again == nil || again.StepID != d.StepID || again.Attempt != 2 {
+ t.Fatalf("the preview again %+v", again)
+ }
+ if k, _ := r.client.Task(r.ctx, id); k.Stage != wire.StageReadyToMerge {
+ t.Fatalf("stage %s", k.Stage)
+ }
+}
+
+// TestContractRetryRefusalReasons: a retry that is still refused says
+// why, in a fixed reason, in retry_step's result and in read_task.
+func TestContractRetryRefusalReasons(t *testing.T) {
+ r := publicPreviewRig(t)
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ expires := time.Now().Add(7 * 24 * time.Hour).UTC().Truncate(time.Second)
+ id, pv, _ := r.previewedThenMerged("rr", base, cand, func(id string, pv *wire.DispatchCommand) {
+ r.previewDone("rr-up", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "tmp-" + id, URL: "https://tmp-" + id + ".bds.oncarlos.com/", Digest: digestA, ExpiresAt: &expires, Outcome: wire.PreviewDeployed})
+ })
+ // Deployed and still up: nothing to run again.
+ if res := r.call("rr1", wire.ToolRetryStep, map[string]string{"task": id, "step": wire.SpecialistPreview}); res.Code != "not_retryable" || refusal(t, res) != "completed" {
+ t.Fatalf("retry of a preview that is up %+v", res)
+ }
+ if reason, _ := r.retryOf("rr-read", id, wire.SpecialistPreview); reason != "completed" {
+ t.Fatalf("read_task %q", reason)
+ }
+ // A finished task's checks and review are not run again.
+ for _, kind := range []string{wire.SpecialistChecks, wire.SpecialistReview} {
+ if res := r.call("rr-"+kind, wire.ToolRetryStep, map[string]string{"task": id, "step": kind}); res.Code != "task_ended" || refusal(t, res) != "task_done" {
+ t.Fatalf("retry of a done task's %s %+v", kind, res)
+ }
+ if reason, _ := r.retryOf("rr-read-"+kind, id, kind); reason != "task_done" {
+ t.Fatalf("read_task %s %q", kind, reason)
+ }
+ }
+ // A cancelled task runs nothing again.
+ b2, c2 := strings.Repeat("3", 40), strings.Repeat("4", 40)
+ other, _ := r.pushed("rc", "Fix the README typo", b2, c2)
+ r.expect(wire.FrameWatchMerge)
+ r.checks("rc-c", r.dispatched(wire.SpecialistChecks, b2, c2, 0), wire.ChecksPassed, exit(0), "", "ok\n")
+ rv := r.dispatched(wire.SpecialistReview, b2, c2, 0)
+ r.step("rc-r", wire.StepReport{TaskID: rv.TaskID, StepID: rv.StepID, Attempt: rv.Attempt, State: wire.StepDone, BaseSHA: b2, CandidateSHA: c2, Termination: true, Family: "codex", Account: "codex-a", Verdict: wire.VerdictApprove, ReviewLabel: wire.ReviewOtherFamily, Findings: []wire.Finding{}, Summary: "Read it.", HasPreview: true})
+ d := r.previewDispatch(c2)
+ if d == nil {
+ t.Fatal("no preview of the second task")
+ }
+ if reason, _ := r.retryOf("rc-read", other, wire.SpecialistPreview); reason != "not_ended" {
+ t.Fatalf("read_task of a queued preview %q", reason)
+ }
+ if res := r.call("rc-cancel", wire.ToolCancelTask, map[string]string{"task": other}); res.IsError {
+ t.Fatalf("cancel %+v", res)
+ }
+ r.failedPreview("cancelled")(other, d)
+ if res := r.call("rc1", wire.ToolRetryStep, map[string]string{"task": other, "step": wire.SpecialistPreview}); res.Code != "task_ended" || refusal(t, res) != "task_cancelled" {
+ t.Fatalf("retry on a cancelled task %+v", res)
+ }
+ // Its link expired: it runs again, unless the project stopped
+ // allowing public previews since.
+ if err := r.inst.DB.G.Exec("UPDATE chat_steps SET preview = replace(preview, ?, ?) WHERE id = ?", expires.Format(time.RFC3339), time.Now().Add(-time.Hour).UTC().Format(time.RFC3339), pv.StepID).Error; err != nil {
+ t.Fatal(err)
+ }
+ if reason, _ := r.retryOf("rr-read-expired", id, wire.SpecialistPreview); reason != "" {
+ t.Fatalf("an expired preview: %q", reason)
+ }
+ project := r.project()
+ var revision int
+ if err := r.inst.DB.G.Raw("SELECT coalesce(autonomy_revision, 0) FROM chat_projects WHERE id = ?", project).Scan(&revision).Error; err != nil {
+ t.Fatal(err)
+ }
+ if code, _ := r.post(r.inst.Cookie(), "/settings/autonomy", url.Values{"project": {project}, "revision": {itoa(revision)}}); code != http.StatusSeeOther {
+ t.Fatalf("turn public previews off: %d", code)
+ }
+ if res := r.call("rr2", wire.ToolRetryStep, map[string]string{"task": id, "step": wire.SpecialistPreview}); res.Code != "not_retryable" || refusal(t, res) != "preview_public_disabled" {
+ t.Fatalf("retry with public previews off %+v", res)
+ }
+ if extra := r.previewDispatch(mergedSHA); extra != nil {
+ t.Fatalf("a refused retry dispatched %+v", extra)
+ }
+}
+
+// TestContractRetryDevboxPreviewOnMergedTask: a devbox link comes down
+// when its task ends, so a done task's deployed devbox preview counts as
+// one to run again. The re-run's link shows on the task, with no expiry:
+// it stays up until the next run replaces it (read_task says so), and
+// that next run may go ahead while it is up.
+func TestContractRetryDevboxPreviewOnMergedTask(t *testing.T) {
+ r := newToolRigAt(t, wire.ProtocolCurrent)
+ r.pairedWith(&wire.PreviewHost{Kind: wire.PreviewHostDevbox, Domain: "devbox.dev.example"})
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ id, _, _ := r.previewedThenMerged("dd", base, cand, func(id string, pv *wire.DispatchCommand) {
+ r.previewDone("dd-up", pv, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: "https://eq-" + id + ".devbox.dev.example/", Digest: digestA, Outcome: wire.PreviewDeployed})
+ })
+ line := "Preview: eq-" + id + ".devbox.dev.example (on your tailnet)"
+ if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); strings.Contains(page, line) || !strings.Contains(page, "data-step-retry") {
+ t.Fatal("the done task still shows its devbox link, or offers no Retry")
+ }
+ if res := r.call("dd1", wire.ToolRetryStep, map[string]string{"task": id, "step": wire.SpecialistPreview}); res.IsError {
+ t.Fatalf("retry_step %+v", res)
+ }
+ again := r.previewDispatch(mergedSHA)
+ if again == nil {
+ t.Fatal("no preview of the merged commit")
+ }
+ r.built("dd-built", again, digestB)
+ r.previewDone("dd-again", again, wire.PreviewResult{Phase: wire.PreviewDone, App: "eq-" + id, URL: "https://eq-" + id + ".devbox.dev.example/", Digest: digestB, Outcome: wire.PreviewDeployed})
+ if page := r.get(r.inst.Cookie(), "/tasks/"+id, 200); !strings.Contains(page, line) {
+ t.Fatal("the re-run's devbox link is not shown")
+ }
+ if page := r.get(r.inst.Cookie(), "/tasks/"+id+"/preview", 200); !strings.Contains(page, "<iframe") {
+ t.Fatal("the preview page does not open the re-run")
+ }
+ k, _ := r.client.Task(r.ctx, id)
+ if up := k.Steps[len(k.Steps)-1].Preview; up == nil || up.ExpiresAt != nil {
+ t.Fatalf("the re-run's link %+v", up)
+ }
+ if reason, note := r.retryNote("dd-read", id); reason != "" || note != "devbox_stays_up" {
+ t.Fatalf("read_task %q %q", reason, note)
+ }
+ // The next run replaces it: the person's Retry while it is up.
+ if status, _ := r.post(r.inst.Cookie(), "/conversation/tasks/"+id+"/retry", url.Values{"from": {"task"}, "step": {again.StepID}}); status != http.StatusSeeOther {
+ t.Fatalf("Retry %d", status)
+ }
+ if next := r.previewDispatch(mergedSHA); next == nil || next.StepID == again.StepID {
+ t.Fatalf("the next run %+v", next)
+ }
+ if k2, _ := r.client.Task(r.ctx, id); k2.Stage != wire.StageDone || *k2.Merged != *k.Merged {
+ t.Fatalf("the re-run moved the task %+v", k2)
+ }
+}
+
+// retryNote is read_task's retry for the preview: its reason and note.
+func (r *toolRig) retryNote(key, id string) (string, string) {
+ r.t.Helper()
+ res := r.call(key, wire.ToolReadTask, map[string]string{"task": id})
+ var out struct {
+ Retry []struct {
+ Step string `json:"step"`
+ Reason string `json:"reason"`
+ Note string `json:"note"`
+ NoteText string `json:"note_text"`
+ } `json:"retry"`
+ }
+ if res.IsError || json.Unmarshal([]byte(res.Text), &out) != nil {
+ r.t.Fatalf("read_task %+v", res)
+ }
+ for _, x := range out.Retry {
+ if x.Step == wire.SpecialistPreview {
+ if x.Note != "" && x.NoteText == "" {
+ r.t.Fatalf("a note without its words %+v", x)
+ }
+ return x.Reason, x.Note
+ }
+ }
+ r.t.Fatal("no preview in read_task's retry")
+ return "", ""
+}
+
+// TestContractRetryPreviewUnverifiedMerge (Astra round 1): a merged
+// commit is publication authority only when proven to be the merge of
+// the approved candidate (the hub's own answer, the candidate its second
+// parent). A reconciled landing past the runner's 200-commit search names
+// the default branch's tip; a nested merge's commit has another second
+// parent; a cached landing says nothing of parents. In each, a preview of
+// the done task builds the approved candidate itself, never the named
+// commit, and read_task and the result say why (merge_unverified).
+func TestContractRetryPreviewUnverifiedMerge(t *testing.T) {
+ later := strings.Repeat("7", 40)
+ for name, landing := range map[string]struct {
+ source string
+ parents func(base, cand string) []string
+ }{
+ "far tip": {wire.MergeSourceReconciled, func(string, string) []string { return nil }},
+ "nested": {wire.MergeSourceHub, func(base, _ string) []string { return []string{base, strings.Repeat("6", 40)} }},
+ "cached": {wire.MergeSourceCached, func(base, cand string) []string { return []string{base, cand} }},
+ "first only": {wire.MergeSourceHub, func(_, cand string) []string { return []string{cand, strings.Repeat("6", 40)} }},
+ } {
+ t.Run(name, func(t *testing.T) {
+ r := publicPreviewRig(t)
+ base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40)
+ id, pv, _ := r.previewedThenLanded("um", base, cand, r.failedPreview("preview_scanner"), func(m *wire.DispatchCommand) {
+ r.landed("um-m", m, later, landing.source, landing.parents(base, cand))
+ })
+ before, _ := r.client.Task(r.ctx, id)
+ if before.Stage != wire.StageDone || before.Merged == nil || before.Merged.SHA != later {
+ t.Fatalf("not merged as the landing said %+v", before.Merged)
+ }
+ if reason, note := r.retryNote("um-read", id); reason != "" || note != "merge_unverified" {
+ t.Fatalf("read_task %q %q", reason, note)
+ }
+ res := r.call("um1", wire.ToolRetryStep, map[string]string{"task": id, "step": wire.SpecialistPreview})
+ if res.IsError || res.Code != "retrying" || !strings.Contains(res.Text, "Review approved") {
+ t.Fatalf("retry_step %+v", res)
+ }
+ if wrong := r.previewDispatch(later); wrong != nil {
+ t.Fatalf("a preview of the unproven commit %+v", wrong)
+ }
+ again := r.previewDispatch(cand)
+ if again == nil || again.StepID == pv.StepID || again.Attempt != 1 {
+ t.Fatalf("the preview of the approved commit %+v", again)
+ }
+ r.built("um-built", again, digestB)
+ if refused := r.lease(r.runner, "um-pub", wire.LeaseCheck{StepID: again.StepID, Attempt: 1, Purpose: wire.LeasePurposePreview, Digest: digestB}); refused != "" {
+ t.Fatalf("publish of the approved commit refused %q", refused)
+ }
+ if k, _ := r.client.Task(r.ctx, id); k.Stage != wire.StageDone || *k.Merged != *before.Merged {
+ t.Fatalf("the preview moved the task %+v", k)
+ }
+ })
+ }
+}