Merge thin-v1-slice4c fixes (aaf04aa) into thin-v1-ux1
Adoption card, no cancel while merging, implementers askable after a merge. Conflicts: chat_tasks keeps 4c's ready_sha, merge_eligible and done_at, then duplicate_of from 0048.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
29 files changed,
+868
−100
docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+3 −0docs/superpowers/plans/SLICE4C-PROGRESS.md+51 −5internal/equipo/chat/http.go+2 −0internal/equipo/chat/merge.go+46 −11internal/equipo/chat/questions.go+28 −3internal/equipo/chat/review.go+19 −1internal/equipo/chat/tasks.go+26 −1internal/equipo/chat_page.go+1 −1internal/equipo/copy.go+3 −0internal/equipo/migrations/0047_thin_merge_eligibility.sql+5 −0internal/equipo/migrations/schema.sql+1 −1internal/equipo/templates/chat.html+1 −1internal/headless/ask_test.go+9 −9internal/headless/merge_test.go+6 −0internal/runner/thin/ask.go+10 −4internal/runner/thin/ask_test.go+38 −0internal/runner/thin/engineer.go+7 −7internal/runner/thin/held_test.go+140 −0internal/runner/thin/judge.go+3 −4internal/runner/thin/mergestep.go+21 −21internal/runner/thin/mergestep_test.go+103 −10internal/runner/thin/run.go+5 −0internal/runner/thin/state.go+7 −1internal/runner/thin/step.go+104 −4internal/thintest/merge_contract_test.go+200 −0internal/thintest/questions_contract_test.go+17 −15internal/wire/questions.go+8 −0internal/wire/tasks.go+3 −0internal/wire/wiretest/testdata/frames/forget_task.json+1 −1
Intent
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 3c00602a..330e55f2 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -4871,6 +4871,9 @@ records remain unchanged. |
| | `chat.merged` | Merged [%s](%s) into %s. | Thin v1 slice 4c the coordinator merges (conversation) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.merged_without_checks` | Merged [%s](%s) into %s without checks. | Thin v1 slice 4c the coordinator merges (conversation) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.activity.add_report` | Adding to the task… | Thin v1 slice 4c the coordinator merges (conversation activity line) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| +| `chat.card.merge_adopt` | Merge %s? | Thin v1 slice 4c review (merge card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| +| `chat.card.not_now` | Not now | Thin v1 slice 4c review (merge card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| +| `chat.card.merge_chose_not_now` | Not now. | Thin v1 slice 4c review (merge card) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `work.step` | %s, attempt %d: %s | Thin v1 slice 4 review and checks (task card, task and Tasks pages, sidebar) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `work.steps` | Steps | Thin v1 slice 4 review and checks (task card, task and Tasks pages, sidebar) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
| | `chat.card.home_ask` | Use %s for new projects? | Thin v1 slice 2b home card and receipts (chat page) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) | |
diff --git a/docs/superpowers/plans/SLICE4C-PROGRESS.md b/docs/superpowers/plans/SLICE4C-PROGRESS.md| index 89487073..37051421 100644 |
| --- a/docs/superpowers/plans/SLICE4C-PROGRESS.md |
| +++ b/docs/superpowers/plans/SLICE4C-PROGRESS.md |
| @@ -171,6 +171,55 @@ once it has earned Ready to merge. Conventions and scripts as in |
| 9. Merged `thin-v1-slice4b` round-1 fixes at 56a623b (ask output bounds, |
| ask termination proof, ReportAnswer retry, git_show range): clean. |
| +10. Review round 1 (Astra 4c, REQUEST CHANGES, three Important and one |
| + Minor), the 4b round 2 findings and Paul's request. Each fix has a |
| + test that failed without it (one mutation per fix, all observed |
| + failing): |
| + 1. No cancel while merging: the API (409 `task_merging`), the page |
| + and the coordinator's `cancel_task` (refused `merging`) refuse it; |
| + the runner settles a merge from its record and the default branch |
| + whatever the step's context, so a lost answer ends Done. |
| + `TestContractCancelRefusedWhileMerging`, |
| + `TestMergeStepSettlesDespiteCancel`. |
| + 2. Not retroactive: a candidate is eligible to merge on its own only |
| + if it first earned Ready under the policy with checks passed |
| + (`ready_sha`, `merge_eligible`, migration 0047; the migration marks |
| + candidates already Ready, or moved away from Ready, ineligible). |
| + Leaving Ready and coming back grants nothing. An ineligible |
| + candidate gets one card, "Merge <title>?" with Merge and Not now; |
| + Merge adopts it. `TestContractNoRetroactiveMerge` runs 0047's own |
| + statements on a Ready task. |
| + 3. The hub's CI wait releases the queue: the merge step is deferred |
| + (`not_before`, `deferred_since` on the runner's steps) and due |
| + again after 15 s; other steps and questions run meanwhile; each |
| + resumption runs afresh (lease, owner, judged head). Past ten |
| + minutes it ends `amadan_ci_pending`. `TestMergeCIWaitReleasesTheQueue` |
| + (and the branch moving while it waits: `branch_moved`, no merge). |
| + 4. The branch moving gives an open merge card a new revision; an |
| + answer from before the move is 409 once it is back. |
| + `TestContractMergeCardStaleAfterMove`; `4c_checks_card` answers |
| + with the refreshed revision. |
| + 5. (4b) Nothing is dispatched while a step or question waits for its |
| + namespace's exit to be verified; the worker looks again every 5 s. |
| + `TestNothingRunsBesideAnUnverifiedExit`. |
| + 6. (4b) The namespace is written before launch (containment's record |
| + callback); a record that cannot be written launches nothing. A held |
| + answer with no namespace is released only when no namespace of the |
| + runner remains. `TestNamespaceRecordedBeforeLaunch`, |
| + `TestHeldAnswerWithoutNamespaceNeedsVerification`. |
| + 7. Paul: a done task's specialists can be asked for 14 days |
| + (`done_at`); `forget_task` carries `keep_until` and the runner keeps |
| + the sessions until then (`expires_at`), the sweep removes them |
| + after; a cancelled task forgets at once. |
| + `TestContractAskImplementer`, `TestContractCancelledTaskForgetsNow`, |
| + `TestForgetTaskKeepsMergedSessions`; headless `4b_ask` asks after |
| + the merge. |
| + New copy (accepted for now, in the inventory): `chat.card.merge_adopt` |
| + "Merge %s?", `chat.card.not_now` "Not now", |
| + `chat.card.merge_chose_not_now` "Not now.". Fixture |
| + `frames/forget_task.json` gained `keep_until`. No live run (the |
| + staging account's weekly limit). |
| + |
| ## Decisions |
| - The merge is a step (specialist `merge`) in the runner's one queue: it |
| @@ -241,12 +290,9 @@ steps only). |
| - The two unapproved merges above: the controller decides whether to |
| revert them on oficina/suite. |
| -- A task Equipo merges is done, so the runner forgets its kept sessions: |
| - nobody can ask the implementer about merged work. `4b_ask` now asks |
| - while a task waits on its merge card. |
| - Amadan's `require_green` is not readable through the API; a merge |
| - waiting for Amadan's CI holds the runner's step queue up to 10 minutes |
| - before it reports `amadan_ci_pending`. |
| + waiting for Amadan's CI is deferred for up to 10 minutes before it |
| + reports `amadan_ci_pending`. |
| - Version skew as before: an old runner refuses a `merge` dispatch; |
| install runners right after the instance. |
| - The squash-merge detection of slice 4 still serves people's merges. |
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go| index d649a2d2..14c663c8 100644 |
| --- a/internal/equipo/chat/http.go |
| +++ b/internal/equipo/chat/http.go |
| @@ -130,6 +130,8 @@ func (h *HTTP) fail(w http.ResponseWriter, r *http.Request, err error) { |
| personapi.WriteError(w, r, 409, "task_ended", nil) |
| case errors.Is(err, ErrNotRetryable): |
| personapi.WriteError(w, r, 409, "not_retryable", nil) |
| + case errors.Is(err, ErrMerging): |
| + personapi.WriteError(w, r, 409, "task_merging", nil) |
| case errors.Is(err, ErrNotAskable): |
| personapi.WriteError(w, r, 409, "not_askable", nil) |
| default: |
diff --git a/internal/equipo/chat/merge.go b/internal/equipo/chat/merge.go| index ab7eaf19..074169b3 100644 |
| --- a/internal/equipo/chat/merge.go |
| +++ b/internal/equipo/chat/merge.go |
| @@ -23,8 +23,13 @@ import ( |
| // candidate is checked and reviewed afresh; only a judged SHA is ever |
| // merged, and the runner checks the head again right before. |
| -// mergeChoices are the merge card's options. |
| -var mergeChoices = []string{wire.ChoiceMerge, wire.ChoiceWait} |
| +// mergeChoices are the merge card's options: merging without checks |
| +// (Merge, Wait for checks), or adopting a candidate that was Ready before |
| +// Equipo merged on its own (Merge, Not now). |
| +var ( |
| + mergeChoices = []string{wire.ChoiceMerge, wire.ChoiceWait} |
| + adoptChoices = []string{wire.ChoiceMerge, wire.ChoiceNotNow} |
| +) |
| // merging reports whether s is a merge of the judged candidate the |
| // policy allows: approved, and checks passed or the person chose to |
| @@ -44,14 +49,21 @@ func (t *txn) autoMerge(k *taskRecord, p progress, steps []stepRecord) error { |
| // A merge of this SHA ran or runs; its report decides. |
| return nil |
| } |
| - if p.mergeAllowed(false) { |
| + if p.mergeAllowed(false) && k.MergeEligible == p.candidate { |
| return t.startMerge(k, p, steps, false) |
| } |
| checks, _, verdict, _ := p.judged() |
| - if verdict != wire.VerdictApprove || checks != wire.ChecksCannotRun && checks != wire.ChecksNone || k.MergeAsked == p.candidate { |
| + if verdict != wire.VerdictApprove || p.moved || k.MergeAsked == p.candidate { |
| return nil |
| } |
| - return t.askMerge(k, p) |
| + switch checks { |
| + case wire.ChecksCannotRun, wire.ChecksNone: |
| + return t.askMerge(k, p, false) |
| + case wire.ChecksPassed: |
| + // Ready before Equipo merged on its own: the person adopts it. |
| + return t.askMerge(k, p, true) |
| + } |
| + return nil |
| } |
| // startMerge dispatches the merge step for the judged candidate. |
| @@ -61,11 +73,16 @@ func (t *txn) startMerge(k *taskRecord, p progress, steps []stepRecord, withoutC |
| return t.nextStep(k, steps, s) |
| } |
| -// askMerge puts the one merge card in the creator's conversation. |
| -func (t *txn) askMerge(k *taskRecord, p progress) error { |
| +// askMerge puts the one merge card in the creator's conversation: merge |
| +// without checks, or (adopt) merge a candidate that was Ready already. |
| +func (t *txn) askMerge(k *taskRecord, p progress, adopt bool) error { |
| now := t.now() |
| - opts, _ := json.Marshal(mergeChoices) |
| - c := cardRecord{ID: newID("c_"), Person: k.Creator, Kind: wire.CardMerge, State: wire.CardOpen, ProjectID: k.ProjectID, TaskID: k.ID, Name: k.Title, Question: t.words("chat.card.merge_question", k.Title), Options: string(opts), Revision: 1, CreatedAt: now, UpdatedAt: now} |
| + choices, question := mergeChoices, t.words("chat.card.merge_question", k.Title) |
| + if adopt { |
| + choices, question = adoptChoices, t.words("chat.card.merge_adopt", k.Title) |
| + } |
| + opts, _ := json.Marshal(choices) |
| + c := cardRecord{ID: newID("c_"), Person: k.Creator, Kind: wire.CardMerge, State: wire.CardOpen, ProjectID: k.ProjectID, TaskID: k.ID, Name: k.Title, Question: question, Options: string(opts), Revision: 1, CreatedAt: now, UpdatedAt: now} |
| if err := t.db.Create(&c).Error; err != nil { |
| return err |
| } |
| @@ -85,7 +102,9 @@ func (t *txn) answerMerge(person string, c cardRecord, in wire.AnswerCard) (wire |
| if err != nil { |
| return wire.Card{}, wire.Card{}, err |
| } |
| - if in.Choice != wire.ChoiceMerge && in.Choice != wire.ChoiceWait { |
| + var options []string |
| + _ = json.Unmarshal([]byte(c.Options), &options) |
| + if !slices.Contains(options, in.Choice) { |
| return wire.Card{}, wire.Card{}, ErrInvalid |
| } |
| if c.State != wire.CardOpen || c.Revision != in.Revision { |
| @@ -119,7 +138,8 @@ func (t *txn) answerMerge(person string, c cardRecord, in wire.AnswerCard) (wire |
| return wire.Card{}, wire.Card{}, err |
| } |
| if in.Choice == wire.ChoiceMerge { |
| - if err := t.startMerge(&k, p, steps, true); err != nil { |
| + checks, _, _, _ := p.judged() |
| + if err := t.startMerge(&k, p, steps, checks != wire.ChecksPassed); err != nil { |
| return wire.Card{}, wire.Card{}, err |
| } |
| } |
| @@ -127,6 +147,21 @@ func (t *txn) answerMerge(person string, c cardRecord, in wire.AnswerCard) (wire |
| return out, wire.Card{}, err |
| } |
| +// touchMergeCards gives a task's open merge cards a new revision: the |
| +// branch moved, so an answer given before it did is refused as stale. |
| +func (t *txn) touchMergeCards(k taskRecord) error { |
| + var open []cardRecord |
| + if err := t.db.Where("task_id = ? AND kind = ? AND state = ?", k.ID, wire.CardMerge, wire.CardOpen).Find(&open).Error; err != nil { |
| + return err |
| + } |
| + for i := range open { |
| + if err := t.saveCard(&open[i]); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| // withdrawMergeCards resolves a task's open merge cards: the SHA they |
| // asked about is no longer the one to merge, or the task ended. |
| func (t *txn) withdrawMergeCards(k taskRecord) error { |
diff --git a/internal/equipo/chat/questions.go b/internal/equipo/chat/questions.go| index a34f7198..1b464cd0 100644 |
| --- a/internal/equipo/chat/questions.go |
| +++ b/internal/equipo/chat/questions.go |
| @@ -157,7 +157,7 @@ func (s *Store) Ask(ctx context.Context, person, taskID string, in wire.AskQuest |
| } else if !errors.Is(err, gorm.ErrRecordNotFound) { |
| return err |
| } |
| - if wire.FinalStage(k.Stage) || k.CancelRequested { |
| + if !askOpen(k, t.now()) { |
| return ErrTaskEnded |
| } |
| steps, err := t.steps(k.ID) |
| @@ -198,7 +198,7 @@ func (s *Store) Ask(ctx context.Context, person, taskID string, in wire.AskQuest |
| // nextQuestion sends the task's oldest waiting question to the runner, |
| // unless one is already there. |
| func (t *txn) nextQuestion(k taskRecord) error { |
| - if wire.FinalStage(k.Stage) || k.CancelRequested { |
| + if !askOpen(k, t.now()) { |
| return nil |
| } |
| var open int64 |
| @@ -490,6 +490,13 @@ func (t *txn) syncQuestions(l Lease, held []wire.AskRun) error { |
| // taskEnded runs once when a task becomes done or cancelled: its open |
| // questions stop, and the runner may delete the sessions it kept. |
| func (t *txn) taskEnded(k taskRecord) error { |
| + if k.Stage == wire.StageDone { |
| + // Done (merged): its specialists can still be asked about their |
| + // work for KeepMergedSessions (Paul, 2026-11-08); the runner keeps |
| + // their sessions until then and removes them after. |
| + keep := t.now().Add(wire.KeepMergedSessions) |
| + return t.forgetTask(k, &keep) |
| + } |
| var open []questionRecord |
| if err := t.db.Where("task_id = ? AND state IN ?", k.ID, []string{wire.QuestionQueued, wire.QuestionRunning}).Find(&open).Error; err != nil { |
| return err |
| @@ -499,14 +506,32 @@ func (t *txn) taskEnded(k taskRecord) error { |
| return err |
| } |
| } |
| + return t.forgetTask(k, nil) |
| +} |
| + |
| +// forgetTask tells the runners that kept the task's sessions to drop |
| +// them, now or after keep. |
| +func (t *txn) forgetTask(k taskRecord, keep *time.Time) error { |
| var persons []string |
| if err := t.db.Model(&stepRecord{}).Distinct("person").Where("task_id = ?", k.ID).Pluck("person", &persons).Error; err != nil { |
| return err |
| } |
| for _, p := range persons { |
| - if err := t.command(p, wire.FrameForgetTask, wire.ForgetTaskCommand{Person: p, TaskID: k.ID}); err != nil { |
| + if err := t.command(p, wire.FrameForgetTask, wire.ForgetTaskCommand{Person: p, TaskID: k.ID, KeepUntil: keep}); err != nil { |
| return err |
| } |
| } |
| return nil |
| } |
| + |
| +// askOpen reports whether the task's specialists may be asked: until it |
| +// ends, and for KeepMergedSessions after it is done; never once cancelled. |
| +func askOpen(k taskRecord, now time.Time) bool { |
| + switch { |
| + case k.CancelRequested || k.Stage == wire.StageCancelled: |
| + return false |
| + case k.Stage == wire.StageDone: |
| + return k.DoneAt != nil && now.Before(k.DoneAt.Add(wire.KeepMergedSessions)) |
| + } |
| + return true |
| +} |
diff --git a/internal/equipo/chat/review.go b/internal/equipo/chat/review.go| index bed569a4..0f2c3ae6 100644 |
| --- a/internal/equipo/chat/review.go |
| +++ b/internal/equipo/chat/review.go |
| @@ -172,9 +172,22 @@ func (t *txn) advance(k *taskRecord) error { |
| case p.review == nil: |
| return t.judge(k, p, wire.SpecialistReview) |
| case verdict == wire.VerdictApprove: |
| - if k.Stage != wire.StageReadyToMerge && k.Stage != wire.StageMerging { |
| + ready := k.Stage != wire.StageReadyToMerge && k.Stage != wire.StageMerging |
| + if ready { |
| // Ready to merge is seen (an event of its own) before the merge. |
| k.Stage = wire.StageReadyToMerge |
| + } |
| + if k.ReadySHA != p.candidate { |
| + // This candidate earns Ready for the first time under the merge |
| + // policy: with its checks passed it may be merged on its own. |
| + // Never granted again later (Ready left and regained), and never |
| + // to a candidate already Ready when the policy arrived. |
| + k.ReadySHA, k.MergeEligible, ready = p.candidate, "", true |
| + if checks == wire.ChecksPassed { |
| + k.MergeEligible = p.candidate |
| + } |
| + } |
| + if ready { |
| if err := t.saveTask(k); err != nil { |
| return err |
| } |
| @@ -396,6 +409,11 @@ func (t *txn) branchMoved(l Lease, v *wire.BranchReport) error { |
| if k.Stage == wire.StageReadyToMerge { |
| k.Stage = wire.StageInReview |
| } |
| + // An open merge card asked about what was judged: an answer from |
| + // before the move is stale once the branch is back. |
| + if err := t.touchMergeCards(k); err != nil { |
| + return err |
| + } |
| } |
| if err := t.saveTask(&k); err != nil { |
| return err |
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go| index ddbd3808..09739748 100644 |
| --- a/internal/equipo/chat/tasks.go |
| +++ b/internal/equipo/chat/tasks.go |
| @@ -18,6 +18,9 @@ import ( |
| var ( |
| // ErrTaskEnded means the task is done or cancelled. |
| ErrTaskEnded = errors.New("chat: task ended") |
| + // ErrMerging means Equipo is merging the task: it cannot be cancelled |
| + // until the hub's outcome is known (Done, or back at Ready to merge). |
| + ErrMerging = errors.New("chat: task merging") |
| // ErrNotRetryable means the task's step has not ended with the |
| // runner's termination proof, or there is nothing to retry. |
| ErrNotRetryable = errors.New("chat: step not retryable") |
| @@ -55,6 +58,16 @@ type taskRecord struct { |
| MergeStrategy string |
| MergedWithoutChecks bool |
| MergedAt *time.Time |
| + // ReadySHA is the candidate that first earned Ready to merge under the |
| + // merge policy (or was Ready when the policy arrived: migration 0047); |
| + // MergeEligible is the candidate Equipo may merge on its own, set only |
| + // at that first time with checks passed. Leaving Ready and coming back |
| + // grants nothing. |
| + ReadySHA string |
| + MergeEligible string |
| + // DoneAt is when the task became done: its specialists can be asked |
| + // about their work for wire.KeepMergedSessions after. |
| + DoneAt *time.Time |
| // DuplicateOf is an open task that read like this one when it was |
| // recorded anyway, or the task it was folded into. |
| DuplicateOf string |
| @@ -168,6 +181,7 @@ const ( |
| toolNotYours = "That task is another person's: you may read it, but only the person who asked for it can change, start or cancel it." |
| toolSimilar = "Nothing was recorded: these open tasks in the same project look like the same problem. If one of them is, call add_report with its task id and the person's words, then tell the person in one line that it is already logged, naming it as a markdown link [title](link), and where it stands. If this really is a different problem, call record_task again with separate: true." |
| toolReportAdded = "Added the person's report to this task. Tell them in one line that it is already logged, naming it as a markdown link [title](link), and where it stands. Do not record it again." |
| + toolMerging = "Equipo is merging that task now, so it cannot be cancelled. It ends Done, or back at Ready to merge if the merge is refused." |
| toolTaskEndedReport = "That task is done or cancelled. If the problem is back, record a new task with record_task and separate: true." |
| ) |
| @@ -347,7 +361,11 @@ func (t *txn) saveTask(k *taskRecord) error { |
| } |
| k.Revision++ |
| k.UpdatedAt = t.now() |
| - if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("stage", "base_sha", "cancel_requested", "revision", "updated_at", "moved_from", "branch_head", "merged_sha", "merged_into", "merge_strategy", "merged_without_checks", "merged_at", "duplicate_of").Updates(k).Error; err != nil { |
| + if k.Stage == wire.StageDone && before != wire.StageDone { |
| + now := t.now() |
| + k.DoneAt = &now |
| + } |
| + if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("stage", "base_sha", "cancel_requested", "revision", "updated_at", "moved_from", "branch_head", "merged_sha", "merged_into", "merge_strategy", "merged_without_checks", "merged_at", "ready_sha", "merge_eligible", "done_at", "duplicate_of").Updates(k).Error; err != nil { |
| return err |
| } |
| if wire.FinalStage(k.Stage) && !wire.FinalStage(before) { |
| @@ -681,6 +699,11 @@ func (t *txn) cancelTask(person, id string) (int64, error) { |
| if err != nil { |
| return 0, err |
| } |
| + if k.Stage == wire.StageMerging || found && s.Specialist == wire.SpecialistMerge && !wire.StepTerminal(s.State) { |
| + // A merge request may already be with the hub: the runner settles |
| + // it from the default branch, and a cancel must not hide a merge. |
| + return 0, ErrMerging |
| + } |
| if k.Watching != "" { |
| if err := t.watch(&k, s.Person, ""); err != nil { |
| return 0, err |
| @@ -1194,6 +1217,8 @@ func (t *txn) taskTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) |
| return refused("not_found", toolNoTask), nil |
| case errors.Is(err, ErrTaskEnded): |
| return refused("task_ended", toolTaskEnded), nil |
| + case errors.Is(err, ErrMerging): |
| + return refused("merging", toolMerging), nil |
| case errors.Is(err, ErrForbidden): |
| return refused("not_yours", toolNotYours), nil |
| case err != nil: |
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go| index 1c2beb13..b9bd0bdc 100644 |
| --- a/internal/equipo/chat_page.go |
| +++ b/internal/equipo/chat_page.go |
| @@ -315,7 +315,7 @@ func (a *application) chatNotebookReset(w http.ResponseWriter, r *http.Request) |
| } |
| func chatError(err error) error { |
| - for from, to := range map[error]error{chat.ErrBusy: ErrConflict, chat.ErrInvalid: ErrInvalid, chat.ErrConflict: ErrConflict, chat.ErrNotFound: ErrNotFound, chat.ErrForbidden: ErrForbidden, chat.ErrNotAllowed: ErrInvalid, chat.ErrTaskEnded: ErrConflict, chat.ErrNotRetryable: ErrConflict, chat.ErrNotAskable: ErrConflict} { |
| + for from, to := range map[error]error{chat.ErrBusy: ErrConflict, chat.ErrInvalid: ErrInvalid, chat.ErrConflict: ErrConflict, chat.ErrNotFound: ErrNotFound, chat.ErrForbidden: ErrForbidden, chat.ErrNotAllowed: ErrInvalid, chat.ErrTaskEnded: ErrConflict, chat.ErrNotRetryable: ErrConflict, chat.ErrMerging: ErrConflict, chat.ErrNotAskable: ErrConflict} { |
| if errors.Is(err, from) { |
| return to |
| } |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 532691a4..dca918d0 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -585,6 +585,9 @@ var pageCopy = map[string]string{ |
| "chat.card.merge_chose_merge": "Merging without checks.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.card.merge_chose_wait": "Waiting for checks.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.card.merge_resolved": "Nothing to decide any more.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.card.merge_adopt": "Merge %s?", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.card.not_now": "Not now", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| + "chat.card.merge_chose_not_now": "Not now.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.merged": "Merged [%s](%s) into %s.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.merged_without_checks": "Merged [%s](%s) into %s without checks.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.activity.add_report": "Adding to the task…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/internal/equipo/migrations/0047_thin_merge_eligibility.sql b/internal/equipo/migrations/0047_thin_merge_eligibility.sql| new file mode 100644 |
| index 00000000..b73af8c9 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0047_thin_merge_eligibility.sql |
| @@ -0,0 +1,5 @@ |
| +ALTER TABLE chat_tasks ADD COLUMN ready_sha text; |
| +ALTER TABLE chat_tasks ADD COLUMN merge_eligible text; |
| +ALTER TABLE chat_tasks ADD COLUMN done_at datetime; |
| +UPDATE chat_tasks SET ready_sha = (SELECT s.candidate_sha FROM chat_steps s WHERE s.task_id = chat_tasks.id AND s.specialist = 'engineering' AND s.pushed = 1 ORDER BY s.idx DESC LIMIT 1) WHERE stage IN ('ready_to_merge', 'merging') OR (stage = 'in_review' AND moved_from IS NOT NULL AND moved_from <> ''); |
| +UPDATE chat_tasks SET done_at = updated_at WHERE stage = 'done'; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 5cf0a7bd..ff564bca 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -592,7 +592,7 @@ CREATE TABLE chat_coordinators (person text PRIMARY KEY, state text, turn_id tex |
| CREATE TABLE chat_notebooks (person text PRIMARY KEY, entries text, revision integer, updated_at datetime); |
| CREATE INDEX chat_card_task ON chat_cards(task_id); |
| CREATE TABLE chat_project_attachments (project_id text, kind text, ref text, name text, created_at datetime, PRIMARY KEY (project_id, kind, ref)); |
| -CREATE TABLE chat_tasks (id text PRIMARY KEY, project_id text, title text, brief text, stage text, branch text, base_sha text, creator text, turn_id text, cancel_requested numeric, revision integer, created_at datetime, updated_at datetime, watching text, moved_from text, branch_head text, merge_asked text, merged_sha text, merged_into text, merge_strategy text, merged_without_checks numeric, merged_at datetime, duplicate_of text); |
| +CREATE TABLE chat_tasks (id text PRIMARY KEY, project_id text, title text, brief text, stage text, branch text, base_sha text, creator text, turn_id text, cancel_requested numeric, revision integer, created_at datetime, updated_at datetime, watching text, moved_from text, branch_head text, merge_asked text, merged_sha text, merged_into text, merge_strategy text, merged_without_checks numeric, merged_at datetime, ready_sha text, merge_eligible text, done_at datetime, duplicate_of text); |
| CREATE INDEX chat_task_project ON chat_tasks(project_id); |
| CREATE TABLE chat_steps (id text PRIMARY KEY, task_id text, idx integer, specialist text, person text, state text, reason text, attempt integer, base_sha text, candidate_sha text, pushed numeric, terminated numeric, summary text, log_tail text, started_at datetime, finished_at datetime, revision integer, created_at datetime, updated_at datetime, round integer, family text, account text, verdict text, review_label text, findings text, checks text, gate text, exit_code integer, output text, republish numeric, from_attempt integer, askable numeric, rebase numeric, from_base text, from_candidate text, merge_sha text, merge_into text, merge_strategy text, without_checks numeric, activity text); |
| CREATE INDEX chat_step_task ON chat_steps(task_id); |
diff --git a/internal/equipo/templates/chat.html b/internal/equipo/templates/chat.html| index e3552cb9..44e7bbd5 100644 |
| --- a/internal/equipo/templates/chat.html |
| +++ b/internal/equipo/templates/chat.html |
| @@ -5,7 +5,7 @@ |
| {{else if .Receipt}}<p equipo-card-line>{{icon "folder"}}<span>{{.Line}}</span></p>{{if .Open}}<button type="button" equipo-receipt-more aria-expanded="false" aria-controls="acts-{{.ID}}" aria-label="{{copy "chat.card.more"}}">⋯</button><span equipo-receipt-actions id="acts-{{.ID}}">{{if eq .Kind "home"}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form><input type="hidden" name="revision" value="{{.Revision}}"><button equipo-link name="choice" value="undo" type="submit">{{copy "chat.card.undo"}}</button></form>{{else}}<details equipo-change><summary equipo-link>{{.Change}}</summary><form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form><input type="hidden" name="revision" value="{{.Revision}}"><select rst-input name="choice" aria-label="{{.Change}}">{{range .Choices}}<option>{{.}}</option>{{end}}</select><button rst-btn="primary" type="submit">{{copy "chat.card.use"}}</button></form></details>{{if .Remove}}<form method="post" action="/conversation/projects/{{.ProjectID}}/remove" data-card-form><button equipo-link type="submit">{{copy "chat.card.remove"}}</button></form>{{end}}{{end}}</span>{{end}} |
| {{else if eq .Kind "question"}}<p equipo-card-line>{{.Line}}</p>{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{range .Options}}<button rst-btn name="choice" value="{{.}}" type="submit">{{.}}</button>{{else}}<input rst-input name="choice" required maxlength="2000" aria-label="{{copy "chat.card.answer"}}"><button rst-btn="primary" type="submit">{{copy "chat.card.answer"}}</button>{{end}}</form>{{else}}<p equipo-card-note>{{printf (copy "chat.card.answered") .Choice}}</p>{{end}} |
| {{else if eq .Kind "home"}}<p equipo-card-line>{{icon "folder"}}<span>{{.Line}}</span></p><form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}"><button rst-btn="primary" name="choice" value="confirm" type="submit">{{copy "chat.card.confirm"}}</button></form> |
| -{{else if eq .Kind "merge"}}<p equipo-card-line>{{.Line}}</p>{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}"><button rst-btn="primary" name="choice" value="merge" type="submit" data-merge-choice="merge">{{copy "chat.card.merge"}}</button><button rst-btn name="choice" value="wait" type="submit" data-merge-choice="wait">{{copy "chat.card.wait"}}</button></form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}} |
| +{{else if eq .Kind "merge"}}<p equipo-card-line>{{.Line}}</p>{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}">{{range .Options}}<button rst-btn="{{if eq . "merge"}}primary{{end}}" name="choice" value="{{.}}" type="submit" data-merge-choice="{{.}}">{{copy (printf "chat.card.%s" .)}}</button>{{end}}</form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}} |
| {{else if eq .Kind "access"}}<p equipo-card-line>{{.Line}}</p>{{if .Open}}<details equipo-grant><summary rst-btn>{{copy "chat.card.grant"}}</summary><p>{{copy "chat.card.grant_how"}}</p><code>amadan agent grant {{.Agent}} {{.Namespace}}</code><form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form><input type="hidden" name="revision" value="{{.Revision}}"><button rst-btn name="choice" value="check" type="submit" data-grant-check>{{copy "chat.card.grant_check"}}</button></form></details>{{end}} |
| {{end}}</li>{{end}} |
| {{define "work-task-receipt"}}{{with .Task}}<p equipo-card-line>{{icon "check-circle"}}<span><a href="/tasks/{{.ID}}">{{.Title}}</a></span><span equipo-stage data-stage="{{.Stage}}" data-needs="{{.NeedsYou}}">{{.StageLine}}</span></p>{{if and .Pushed (not .MergedLine)}}<p equipo-card-note data-pushed><span>{{.Pushed}}</span><a href="{{.URL}}" rel="noopener" target="_blank" data-open-amadan>{{copy "work.open"}}</a></p>{{end}}{{if or .ChecksLine .ReviewLine}}<p equipo-card-note data-judged>{{with .ChecksLine}}<span data-checks>{{.}}</span>{{end}}{{with .ReviewLine}}<span data-verdict>{{.}}</span>{{end}}</p>{{end}}{{if .MergedLine}}<p equipo-card-note data-merged><span>{{.MergedLine}}</span><a href="{{.RepoURL}}" rel="noopener" target="_blank" data-open-amadan>{{copy "work.open"}}</a></p>{{end}}{{end}}{{if .Open}}<button type="button" equipo-receipt-more aria-expanded="false" aria-controls="acts-{{.ID}}" aria-label="{{copy "chat.card.more"}}">⋯</button><span equipo-receipt-actions id="acts-{{.ID}}">{{template "work-task-actions" .Task}}</span>{{end}}{{end}} |
diff --git a/internal/headless/ask_test.go b/internal/headless/ask_test.go| index 7bcf1321..2e825168 100644 |
| --- a/internal/headless/ask_test.go |
| +++ b/internal/headless/ask_test.go |
| @@ -139,20 +139,20 @@ func scenarioAsk(t *testing.T, env *Env) { |
| s.wait(t, "cancelled", time.Minute, func(c *thintest.Conversation) bool { return c.Questions[q4.ID].State == wire.QuestionCancelled }) |
| Witness[t.Name()] = map[string]any{"task": id, "engineering": c1.seconds(), "review": c2.seconds()} |
| - // The person merges; the task is done and the sessions go. |
| + // The person merges; the task is done, and for 14 days (Paul, |
| + // 2026-11-08) Engineering can still be asked about the merged work, |
| + // from its own kept session. |
| if out, err := exec.Command("git", "--git-dir="+bare, "update-ref", "refs/heads/main", k.CandidateSHA).CombinedOutput(); err != nil { |
| t.Fatalf("merge: %v %s", err, out) |
| } |
| s.wait(t, "done", time.Minute, func(c *thintest.Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) |
| - deadline := time.Now().Add(30 * time.Second) |
| - for env.KeptSessions(t) != 0 { |
| - if time.Now().After(deadline) { |
| - t.Fatalf("%d sessions still kept after the task ended", env.KeptSessions(t)) |
| - } |
| - time.Sleep(200 * time.Millisecond) |
| + time.Sleep(2 * time.Second) |
| + if n := env.KeptSessions(t); n == 0 { |
| + t.Fatal("the sessions went with the merge") |
| } |
| - if _, err := env.Client.Ask(s.ctx, id, "Too late?", "", key()); thintest.Status(err) != 409 { |
| - t.Fatalf("asked an ended task: %v", err) |
| + after, _ := s.asked(t, id, "Now that it is merged, what did you change?", "", time.Minute) |
| + if after.State != wire.QuestionAnswered || after.Specialist != wire.SpecialistEngineering || !strings.Contains(after.Answer, "From my session:") { |
| + t.Fatalf("asked about merged work: %+v", after) |
| } |
| } |
diff --git a/internal/headless/merge_test.go b/internal/headless/merge_test.go| index b78177f5..83757688 100644 |
| --- a/internal/headless/merge_test.go |
| +++ b/internal/headless/merge_test.go |
| @@ -116,6 +116,12 @@ func scenarioChecksCard(t *testing.T, env *Env) { |
| m := c.Tasks[id] |
| return m.Stage == wire.StageReadyToMerge && m.NeedsYou == wire.NeedsMerge && m.Verdict == wire.VerdictApprove |
| }) |
| + // The move made the card's old revision stale (Astra 4c round 1). |
| + if _, err := env.Client.Answer(s.ctx, card.ID, wire.ChoiceWait, card.Revision); thintest.Status(err) != 409 { |
| + t.Fatalf("an answer from before the move: %v", err) |
| + } |
| + s.wait(t, "refreshed card", time.Minute, func(c *thintest.Conversation) bool { return c.Cards[card.ID].Revision > card.Revision }) |
| + s.conv.Locked(func(c *thintest.Conversation) { card = c.Cards[card.ID] }) |
| // Wait: nothing merges. |
| if out, err := env.Client.Answer(s.ctx, card.ID, wire.ChoiceWait, card.Revision); err != nil || out.Card.Choice != wire.ChoiceWait { |
| t.Fatalf("wait %+v %v", out, err) |
diff --git a/internal/runner/thin/ask.go b/internal/runner/thin/ask.go| index b5460fd1..f3066737 100644 |
| --- a/internal/runner/thin/ask.go |
| +++ b/internal/runner/thin/ask.go |
| @@ -77,7 +77,9 @@ func (s *State) touchKept(ctx context.Context, k keptSession, bytes int64) error |
| } |
| // ForgetTask records a forget_task frame once and drops the task's kept |
| -// sessions; it returns their directories for the caller to remove. |
| +// sessions; it returns their directories for the caller to remove. With |
| +// KeepUntil ahead (a merged task), they stay until then and the sweep |
| +// removes them after. |
| func (s *State) ForgetTask(ctx context.Context, frameID string, c wire.ForgetTaskCommand) ([]string, error) { |
| var dirs []string |
| err := s.tx(ctx, func(t *sql.Tx) error { |
| @@ -85,6 +87,10 @@ func (s *State) ForgetTask(ctx context.Context, frameID string, c wire.ForgetTas |
| if err != nil || !fresh { |
| return err |
| } |
| + if c.KeepUntil != nil && c.KeepUntil.After(time.Now()) { |
| + _, err = t.Exec("UPDATE kept_sessions SET expires_at=? WHERE task_id=? AND person=?", c.KeepUntil.UTC().Format(time.RFC3339Nano), c.TaskID, c.Person) |
| + return err |
| + } |
| rows, err := t.Query("SELECT dir FROM kept_sessions WHERE task_id=? AND person=?", c.TaskID, c.Person) |
| if err != nil { |
| return err |
| @@ -108,8 +114,8 @@ func (s *State) ForgetTask(ctx context.Context, frameID string, c wire.ForgetTas |
| // directories, and reports what stays kept (sessions and bytes). |
| func (s *State) expiredKept(ctx context.Context, before time.Time) (dirs []string, kept, bytes int64, err error) { |
| err = s.tx(ctx, func(t *sql.Tx) error { |
| - cut := before.UTC().Format(time.RFC3339Nano) |
| - rows, err := t.Query("SELECT dir FROM kept_sessions WHERE used_at < ?", cut) |
| + cut, now := before.UTC().Format(time.RFC3339Nano), time.Now().UTC().Format(time.RFC3339Nano) |
| + rows, err := t.Query("SELECT dir FROM kept_sessions WHERE used_at < ? OR (expires_at <> '' AND expires_at < ?)", cut, now) |
| if err != nil { |
| return err |
| } |
| @@ -122,7 +128,7 @@ func (s *State) expiredKept(ctx context.Context, before time.Time) (dirs []strin |
| dirs = append(dirs, d) |
| } |
| rows.Close() |
| - if _, err = t.Exec("DELETE FROM kept_sessions WHERE used_at < ?", cut); err != nil { |
| + if _, err = t.Exec("DELETE FROM kept_sessions WHERE used_at < ? OR (expires_at <> '' AND expires_at < ?)", cut, now); err != nil { |
| return err |
| } |
| return t.QueryRow("SELECT COUNT(*), COALESCE(SUM(bytes), 0) FROM kept_sessions").Scan(&kept, &bytes) |
diff --git a/internal/runner/thin/ask_test.go b/internal/runner/thin/ask_test.go| index 56f59893..f1ba7648 100644 |
| --- a/internal/runner/thin/ask_test.go |
| +++ b/internal/runner/thin/ask_test.go |
| @@ -288,3 +288,41 @@ func TestRecoverAsks(t *testing.T) { |
| t.Fatalf("acked question still held: %+v", runs) |
| } |
| } |
| + |
| +// Paul, 2026-11-08: a merged task's sessions stay for questions until |
| +// keep_until, then the sweep removes them; a cancelled task's go now. |
| +func TestForgetTaskKeepsMergedSessions(t *testing.T) { |
| + ctx := context.Background() |
| + s, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + r := stepRow{DispatchCommand: dispatchFor("tk1", "s1", 1)} |
| + if err := s.keepSession(ctx, r, wire.SpecialistEngineering, "claude-a", "00000000-0000-4000-8000-000000000001", "/root/a/steps/1", "", 10); err != nil { |
| + t.Fatal(err) |
| + } |
| + until := time.Now().Add(2 * time.Second) |
| + if dirs, err := s.ForgetTask(ctx, "f1", wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk1", KeepUntil: &until}); err != nil || len(dirs) != 0 { |
| + t.Fatalf("a merged task's sessions went at once: %v %v", dirs, err) |
| + } |
| + if _, ok, _ := s.keptSessionFor(ctx, "s1"); !ok { |
| + t.Fatal("not kept") |
| + } |
| + // Used recently, but past keep_until: removed. |
| + if dirs, kept, _, _ := s.expiredKept(ctx, time.Now().Add(-time.Hour)); len(dirs) != 0 || kept != 1 { |
| + t.Fatalf("removed before keep_until: %v", dirs) |
| + } |
| + time.Sleep(2100 * time.Millisecond) |
| + if dirs, kept, _, _ := s.expiredKept(ctx, time.Now().Add(-time.Hour)); len(dirs) != 1 || kept != 0 { |
| + t.Fatalf("kept past keep_until: %v %d", dirs, kept) |
| + } |
| + // A keep_until already past forgets now. |
| + if err := s.keepSession(ctx, r, wire.SpecialistEngineering, "claude-a", "00000000-0000-4000-8000-000000000001", "/root/a/steps/1", "", 10); err != nil { |
| + t.Fatal(err) |
| + } |
| + past := time.Now().Add(-time.Second) |
| + if dirs, _ := s.ForgetTask(ctx, "f2", wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk1", KeepUntil: &past}); len(dirs) != 1 { |
| + t.Fatalf("past keep_until kept %v", dirs) |
| + } |
| +} |
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go| index 03195500..ae1ae88e 100644 |
| --- a/internal/runner/thin/engineer.go |
| +++ b/internal/runner/thin/engineer.go |
| @@ -478,17 +478,17 @@ func (e *Engineer) run(ctx context.Context, r stepRow, tree workspace.TaskTree, |
| launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "step/" + stepKey(r) + "/" + uuid(), Workspace: tree.Dir, Selection: sel, Binding: binding, Policy: policy} |
| pctx, kill := context.WithCancel(context.Background()) |
| defer kill() |
| - proc, err := o.Manager.StartRecorded(pctx, launch, in.Argv, nil) |
| - if err != nil { |
| - e.log("step start", err) |
| - return stepResult{reason: "policy_rejected", terminated: true} |
| - } |
| record := spec.record |
| if record == nil { |
| record = func(ctx context.Context, id string) error { return e.O.State.setStepNamespace(ctx, r, id) } |
| } |
| - if err := record(context.WithoutCancel(ctx), proc.ID()); err != nil { |
| - e.log("step namespace", err) |
| + // The namespace is recorded before it launches: a record that cannot |
| + // be written launches nothing, so an unverified exit always has a |
| + // namespace to verify. |
| + proc, err := recordedStart(pctx, o.Manager, launch, in.Argv, record) |
| + if err != nil { |
| + e.log("step start", err) |
| + return stepResult{reason: "policy_rejected", terminated: true} |
| } |
| // exited carries Wait's verdict: nil only when the containment |
| // verified the namespace's exit and stored its proof durably. |
diff --git a/internal/runner/thin/held_test.go b/internal/runner/thin/held_test.go| new file mode 100644 |
| index 00000000..23aa9ed7 |
| --- /dev/null |
| +++ b/internal/runner/thin/held_test.go |
| @@ -0,0 +1,140 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Astra 4b round 2, finding 2a: after a question's answer is held for an |
| +// unverified exit, the worker runs nothing else (another question or a |
| +// step) until the exit is verified. |
| +func TestNothingRunsBesideAnUnverifiedExit(t *testing.T) { |
| + old := heldRetry |
| + heldRetry = 20 * time.Millisecond |
| + t.Cleanup(func() { heldRetry = old }) |
| + ctx := context.Background() |
| + s, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + var verified atomic.Bool |
| + var asked, stepped atomic.Int32 |
| + e := &StepEngine{State: s, Notify: func() {}, Verify: func(context.Context, string) bool { return verified.Load() }, |
| + Ask: func(_ context.Context, a askRow, _ func(wire.AnswerReport)) askResult { |
| + asked.Add(1) |
| + // The first answer's namespace exit is not verified. |
| + return askResult{Report: wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionAnswered, Text: "x"}, Terminated: a.QuestionID != "q1"} |
| + }, |
| + Exec: func(_ context.Context, r stepRow, _ func(wire.StepReport)) wire.StepReport { |
| + stepped.Add(1) |
| + return wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, State: wire.StepFailed, Reason: "no_changes", Termination: true} |
| + }} |
| + runCtx, cancel := context.WithCancel(ctx) |
| + defer func() { cancel(); e.Wait() }() |
| + if err := e.Start(runCtx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.AcceptAsk(ctx, "c1", wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q1", Attempt: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e.Wake() |
| + waitFor(t, func() bool { return asked.Load() == 1 }) |
| + if err := s.AcceptAsk(ctx, "c2", wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q2", Attempt: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.AcceptDispatch(ctx, "c3", dispatchFor("tk2", "s2", 1)); err != nil { |
| + t.Fatal(err) |
| + } |
| + e.Wake() |
| + time.Sleep(200 * time.Millisecond) |
| + if asked.Load() != 1 || stepped.Load() != 0 { |
| + t.Fatalf("ran beside an unverified exit: %d questions, %d steps", asked.Load(), stepped.Load()) |
| + } |
| + verified.Store(true) |
| + waitFor(t, func() bool { return asked.Load() == 2 && stepped.Load() == 1 }) |
| +} |
| + |
| +// Astra 4b round 2, finding 2b: a held answer with no namespace recorded |
| +// is never released unless no namespace remains at all. |
| +func TestHeldAnswerWithoutNamespaceNeedsVerification(t *testing.T) { |
| + ctx := context.Background() |
| + s, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + a := askRow{AskCommand: wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q1", Attempt: 1}} |
| + if err := s.AcceptAsk(ctx, "c1", a.AskCommand); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.startAsk(ctx, a); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.FinishAsk(ctx, a, wire.AnswerReport{TaskID: "tk1", QuestionID: "q1", Attempt: 1, State: wire.QuestionAnswered, Text: "x"}, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + var asked []string |
| + e := &StepEngine{State: s, Notify: func() {}, Verify: func(_ context.Context, id string) bool { asked = append(asked, id); return false }} |
| + e.Probe(ctx) |
| + if got := outboxAnswers(t, s); len(got) != 0 || len(asked) != 1 || asked[0] != "" { |
| + t.Fatalf("released without verification: %+v (verify asked %q)", got, asked) |
| + } |
| +} |
| + |
| +// fakeStarter follows containment's contract: record first, launch only |
| +// if it succeeded. |
| +type fakeStarter struct{ launched bool } |
| + |
| +func (f *fakeStarter) StartRecorded(ctx context.Context, _ provider.Launch, _ []string, record func(context.Context, containment.Record) error) (provider.Process, error) { |
| + if err := record(ctx, containment.Record{ID: "ns-1"}); err != nil { |
| + return nil, err |
| + } |
| + f.launched = true |
| + return nil, nil |
| +} |
| + |
| +// Astra 4b round 2, finding 2c: the namespace is written before the |
| +// process launches; when it cannot be written nothing launches. |
| +func TestNamespaceRecordedBeforeLaunch(t *testing.T) { |
| + ctx := context.Background() |
| + s, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a := askRow{AskCommand: wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q1", Attempt: 1}} |
| + if err := s.AcceptAsk(ctx, "c1", a.AskCommand); err != nil { |
| + t.Fatal(err) |
| + } |
| + f := &fakeStarter{} |
| + if _, err := recordedStart(ctx, f, provider.Launch{}, []string{"/bin/true"}, func(ctx context.Context, id string) error { return s.setAskNamespace(ctx, a, id) }); err != nil || !f.launched { |
| + t.Fatalf("launch %v %v", f.launched, err) |
| + } |
| + var ns string |
| + s.db.QueryRow("SELECT ns_id FROM asks WHERE question_id='q1'").Scan(&ns) |
| + if ns != "ns-1" { |
| + t.Fatalf("namespace %q", ns) |
| + } |
| + s.Close() |
| + f = &fakeStarter{} |
| + if _, err := recordedStart(ctx, f, provider.Launch{}, []string{"/bin/true"}, func(ctx context.Context, id string) error { return s.setAskNamespace(ctx, a, id) }); err == nil || f.launched { |
| + t.Fatalf("launched without its namespace recorded: %v", err) |
| + } |
| +} |
| + |
| +func waitFor(t *testing.T, cond func() bool) { |
| + t.Helper() |
| + deadline := time.Now().Add(5 * time.Second) |
| + for !cond() { |
| + if time.Now().After(deadline) { |
| + t.Fatal("timed out") |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| +} |
diff --git a/internal/runner/thin/judge.go b/internal/runner/thin/judge.go| index b576e2e7..e5746d30 100644 |
| --- a/internal/runner/thin/judge.go |
| +++ b/internal/runner/thin/judge.go |
| @@ -435,14 +435,13 @@ func (e *Engineer) runGate(ctx context.Context, r stepRow, work string, g gate) |
| } |
| pctx, kill := context.WithCancel(context.Background()) |
| defer kill() |
| - proc, err := e.O.Manager.StartRecorded(pctx, provider.Launch{AttemptKey: "checks/" + stepKey(r) + "/" + uuid(), Workspace: work, Policy: policy}, g.argv, nil) |
| + proc, err := recordedStart(pctx, e.O.Manager, provider.Launch{AttemptKey: "checks/" + stepKey(r) + "/" + uuid(), Workspace: work, Policy: policy}, g.argv, func(ctx context.Context, id string) error { |
| + return e.O.State.setStepNamespace(ctx, r, id) |
| + }) |
| if err != nil { |
| e.log("checks start", err) |
| return gateResult{reason: "checks_unavailable", terminated: true} |
| } |
| - if err := e.O.State.setStepNamespace(context.WithoutCancel(ctx), r, proc.ID()); err != nil { |
| - e.log("checks namespace", err) |
| - } |
| out := &lineTail{max: wire.MaxChecksLines} |
| copied := make(chan struct{}, 2) |
| for _, rd := range []io.Reader{proc.Stdout(), proc.Stderr()} { |
diff --git a/internal/runner/thin/mergestep.go b/internal/runner/thin/mergestep.go| index 2f2dfcc0..ff8cb7bb 100644 |
| --- a/internal/runner/thin/mergestep.go |
| +++ b/internal/runner/thin/mergestep.go |
| @@ -26,7 +26,8 @@ import ( |
| // Merge step bounds: how often an uncertain outcome is tried again, and |
| // how long the hub's own CI on the commit is waited for (the repository |
| -// may require it green before a merge). |
| +// may require it green before a merge), polled every mergeCIPoll with the |
| +// attempt deferred in between, so other work runs meanwhile. |
| var ( |
| mergeAttempts = 3 |
| mergeBackoff = 3 * time.Second |
| @@ -66,27 +67,29 @@ func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire. |
| return e.Forge.Merge(ctx, r.Repo, r.Branch, req) |
| }, |
| Confirm: e.confirm} |
| + // Once the request may be with the hub, a cancel never stops the |
| + // merge from being settled: the forge calls outlive the step's context |
| + // (the instance refuses cancels while merging; shutdown keeps the |
| + // attempt held and it runs again). |
| + mctx := context.WithoutCancel(ctx) |
| var out forge.MergeOutcome |
| var err error |
| - uncertain, waited := 0, time.Duration(0) |
| - for { |
| - out, err = forge.MergeBranch(ctx, m) |
| - var wait time.Duration |
| - switch { |
| - case err == nil || ctx.Err() != nil: |
| - case errors.Is(err, forge.ErrMergeUncertain) && uncertain+1 < mergeAttempts: |
| - uncertain++ |
| - wait = time.Duration(uncertain) * mergeBackoff |
| - case errors.Is(err, forge.ErrMergeCIPending) && waited < mergeCIWait: |
| - wait = mergeCIPoll |
| - waited += wait |
| - } |
| - if wait == 0 { |
| + for uncertain := 0; ; uncertain++ { |
| + cctx, cancel := context.WithTimeout(mctx, 3*time.Minute) |
| + out, err = forge.MergeBranch(cctx, m) |
| + cancel() |
| + if !errors.Is(err, forge.ErrMergeUncertain) || uncertain+1 >= mergeAttempts { |
| break |
| } |
| - select { |
| - case <-ctx.Done(): |
| - case <-time.After(wait): |
| + time.Sleep(time.Duration(uncertain+1) * mergeBackoff) |
| + } |
| + if errors.Is(err, forge.ErrMergeCIPending) { |
| + // The hub's own CI is still running: held for later, releasing |
| + // the queue, and run afresh then (lease, owner, judged SHA). |
| + since := e.O.State.deferredSince(mctx, r) |
| + if since.IsZero() || time.Since(since) < mergeCIWait { |
| + rep.State = stepDeferred |
| + return rep |
| } |
| } |
| switch { |
| @@ -96,9 +99,6 @@ func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire. |
| e.log("merge watch", e.O.State.endWatch(context.WithoutCancel(ctx), r.TaskID, r.CandidateSHA)) |
| rep.State, rep.MergeSHA, rep.Into, rep.Strategy = wire.StepDone, out.SHA, out.Into, out.Strategy |
| return rep |
| - case ctx.Err() != nil: |
| - rep.State, rep.Reason = wire.StepCancelled, "cancelled" |
| - return rep |
| case errors.Is(err, forge.ErrMergeConflict): |
| return fail("merge_conflict") |
| case errors.Is(err, forge.ErrMergeMoved): |
diff --git a/internal/runner/thin/mergestep_test.go b/internal/runner/thin/mergestep_test.go| index 7afdf5a3..abbe4e47 100644 |
| --- a/internal/runner/thin/mergestep_test.go |
| +++ b/internal/runner/thin/mergestep_test.go |
| @@ -7,6 +7,7 @@ import ( |
| "os/exec" |
| "path/filepath" |
| "strings" |
| + "sync/atomic" |
| "testing" |
| "time" |
| @@ -162,7 +163,6 @@ func TestMergeStepRefusals(t *testing.T) { |
| }{ |
| {forge.HubMergeResult{Status: 409, Reason: "conflicts"}, "merge_conflict"}, |
| {forge.HubMergeResult{Status: 409, Reason: "ci_not_green", CIState: "failure"}, "amadan_ci_failed"}, |
| - {forge.HubMergeResult{Status: 409, Reason: "ci_not_green", CIState: "running"}, "amadan_ci_pending"}, |
| {forge.HubMergeResult{Status: 403}, "merge_forbidden"}, |
| {forge.HubMergeResult{Status: 409, Reason: "archived"}, "merge_failed"}, |
| } { |
| @@ -172,17 +172,23 @@ func TestMergeStepRefusals(t *testing.T) { |
| t.Fatalf("%+v: %+v", c.res, rep) |
| } |
| } |
| - // The hub's CI finishes while the runner waits: merged. |
| - f.requests = 0 |
| - f.answer = func(n int, merge func() (forge.HubMergeResult, error)) (forge.HubMergeResult, error) { |
| - if n < 3 { |
| - return forge.HubMergeResult{Status: 409, Reason: "ci_not_green", CIState: "running"}, nil |
| - } |
| - return merge() |
| + // The hub's CI still running: deferred (the queue moves on), and past |
| + // the wait it ends amadan_ci_pending. |
| + f.answer = func(int, func() (forge.HubMergeResult, error)) (forge.HubMergeResult, error) { |
| + return forge.HubMergeResult{Status: 409, Reason: "ci_not_green", CIState: "running"}, nil |
| + } |
| + if err := e.O.State.AcceptDispatch(context.Background(), "d1", r.DispatchCommand); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != stepDeferred { |
| + t.Fatalf("CI running %+v", rep) |
| } |
| - if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepDone || f.requests != 3 { |
| - t.Fatalf("after waiting for CI %+v (%d requests)", rep, f.requests) |
| + e.O.State.deferStep(context.Background(), r, time.Millisecond) |
| + e.O.State.db.Exec("UPDATE steps SET deferred_since=? WHERE step_id=?", stamp(time.Now().Add(-time.Hour)), r.StepID) |
| + if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "amadan_ci_pending" { |
| + t.Fatalf("after the wait %+v", rep) |
| } |
| + f.answer = nil |
| // Policy: not this runner's person, or not a task branch. |
| other := r |
| other.Person = "q@x" |
| @@ -225,3 +231,90 @@ func TestRecoverStepsRerunsAMerge(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| + |
| +// Astra 4c round 1, finding 3: a merge waiting for the hub's CI is held |
| +// between polls and releases the serial queue: another step runs while it |
| +// waits; each resumption runs the merge afresh (lease, judged SHA), so a |
| +// branch that moved meanwhile is never merged. |
| +func TestMergeCIWaitReleasesTheQueue(t *testing.T) { |
| + old := []any{mergeCIPoll, mergeCIWait} |
| + mergeCIPoll, mergeCIWait = 50*time.Millisecond, time.Minute |
| + t.Cleanup(func() { mergeCIPoll, mergeCIWait = old[0].(time.Duration), old[1].(time.Duration) }) |
| + for _, moves := range []bool{false, true} { |
| + e, f, r, cand := hubRig(t) |
| + s := e.O.State |
| + var stepped atomic.Int32 |
| + hubSawStep := false |
| + f.answer = func(n int, merge func() (forge.HubMergeResult, error)) (forge.HubMergeResult, error) { |
| + if n < 3 { |
| + return forge.HubMergeResult{Status: 409, Reason: "ci_not_green", CIState: "running"}, nil |
| + } |
| + hubSawStep = stepped.Load() == 1 |
| + return merge() |
| + } |
| + engine := &StepEngine{State: s, Notify: func() {}, Exec: func(ctx context.Context, row stepRow, p func(wire.StepReport)) wire.StepReport { |
| + if row.Specialist == wire.SpecialistMerge { |
| + if moves && f.requests == 2 { |
| + // The branch moves while the merge waits. |
| + gitOut(t, filepath.Dir(f.dir), "--git-dir="+f.dir, "update-ref", "refs/heads/"+r.Branch, gitOut(t, filepath.Dir(f.dir), "--git-dir="+f.dir, "rev-parse", "main")) |
| + } |
| + return e.Exec(ctx, row, p) |
| + } |
| + stepped.Add(1) |
| + return wire.StepReport{TaskID: row.TaskID, StepID: row.StepID, Attempt: row.Attempt, State: wire.StepFailed, Reason: "no_changes", Termination: true} |
| + }} |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + if err := engine.Start(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.AcceptDispatch(ctx, "c1", r.DispatchCommand); err != nil { |
| + t.Fatal(err) |
| + } |
| + other := dispatchFor("tk2", "s2", 1) |
| + if err := s.AcceptDispatch(ctx, "c2", other); err != nil { |
| + t.Fatal(err) |
| + } |
| + engine.Wake() |
| + var final wire.StepReport |
| + waitFor(t, func() bool { |
| + for _, rep := range outbox(t, s) { |
| + if rep.StepID == r.StepID && wire.StepTerminal(rep.State) { |
| + final = rep |
| + return true |
| + } |
| + } |
| + return false |
| + }) |
| + cancel() |
| + engine.Wait() |
| + if stepped.Load() != 1 { |
| + t.Fatalf("moves=%v: the other step did not run while the merge waited", moves) |
| + } |
| + if moves { |
| + if final.State != wire.StepFailed || final.Reason != "branch_moved" || f.requests != 2 { |
| + t.Fatalf("moved while waiting: %+v (%d requests)", final, f.requests) |
| + } |
| + continue |
| + } |
| + if final.State != wire.StepDone || final.CandidateSHA != cand || f.requests != 3 || !hubSawStep { |
| + t.Fatalf("after waiting %+v (%d requests, step before merge %v)", final, f.requests, hubSawStep) |
| + } |
| + } |
| +} |
| + |
| +// Astra 4c round 1, finding 1: a merge asked to stop still reports what |
| +// the hub did: the answer was lost and the step cancelled, yet the |
| +// default branch shows the merge, so it reports done. |
| +func TestMergeStepSettlesDespiteCancel(t *testing.T) { |
| + e, f, r, _ := hubRig(t) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + f.answer = func(_ int, merge func() (forge.HubMergeResult, error)) (forge.HubMergeResult, error) { |
| + merge() |
| + cancel() |
| + return forge.HubMergeResult{}, forge.ErrMergeUncertain |
| + } |
| + rep := e.Exec(ctx, r, func(wire.StepReport) {}) |
| + if rep.State != wire.StepDone || rep.MergeSHA == "" || f.requests != 1 { |
| + t.Fatalf("cancelled mid-merge: %+v (%d requests)", rep, f.requests) |
| + } |
| +} |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index 4a0243a1..f184cacf 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -453,6 +453,11 @@ func verifiedExit(ctx context.Context, m *containment.Manager, id string) bool { |
| if err != nil { |
| return false |
| } |
| + if id == "" { |
| + // No namespace recorded for the attempt: verified only when none |
| + // of this runner's namespaces remains. |
| + return len(records) == 0 |
| + } |
| for _, r := range records { |
| if r.ID == id { |
| return m.Forget(ctx, r) == nil |
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go| index 8d3825ab..85dc46b7 100644 |
| --- a/internal/runner/thin/state.go |
| +++ b/internal/runner/thin/state.go |
| @@ -81,12 +81,18 @@ func OpenState(ctx context.Context, dir string) (*State, error) { |
| d.Close() |
| return nil, err |
| } |
| - for _, col := range []string{"ns_id", "final_state", "final_reason"} { |
| + for _, col := range []string{"ns_id", "final_state", "final_reason", "not_before", "deferred_since"} { |
| if _, err = d.ExecContext(ctx, "ALTER TABLE steps ADD COLUMN "+col+" TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| d.Close() |
| return nil, err |
| } |
| } |
| + // Added in slice 4c review: until when a merged task's kept sessions |
| + // stay (Paul: ask about merged work for 14 days). |
| + if _, err = d.ExecContext(ctx, "ALTER TABLE kept_sessions ADD COLUMN expires_at TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| + d.Close() |
| + return nil, err |
| + } |
| s := &State{db: d} |
| if s.prefix, err = s.meta(ctx, "frame_prefix"); err != nil { |
| d.Close() |
diff --git a/internal/runner/thin/step.go b/internal/runner/thin/step.go| index ad1c0103..30b24a33 100644 |
| --- a/internal/runner/thin/step.go |
| +++ b/internal/runner/thin/step.go |
| @@ -5,10 +5,13 @@ import ( |
| "database/sql" |
| "encoding/json" |
| "errors" |
| + "fmt" |
| "log/slog" |
| "sync" |
| "time" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -90,10 +93,18 @@ func scanStep(scan func(...any) error) (stepRow, error) { |
| return r, json.Unmarshal([]byte(body), &r.DispatchCommand) |
| } |
| -// nextStep is the oldest running step attempt. |
| +// stepDeferred is what a StepFunc returns to run the attempt again later |
| +// (a merge waiting for the hub's CI): the attempt stays held, the queue |
| +// moves on, and the attempt is due again after deferStep's delay. |
| +const stepDeferred = "deferred" |
| + |
| +// stamp is a time as a fixed-width, ordered string (unix milliseconds). |
| +func stamp(t time.Time) string { return fmt.Sprintf("%015d", t.UnixMilli()) } |
| + |
| +// nextStep is the oldest running step attempt that is due. |
| func (s *State) nextStep(ctx context.Context) (stepRow, bool, error) { |
| var created string |
| - row := s.db.QueryRowContext(ctx, "SELECT body, state, cancel, phase, base_sha, candidate_sha, created_at FROM steps WHERE state=? ORDER BY created_at, step_id LIMIT 1", runRunning) |
| + row := s.db.QueryRowContext(ctx, "SELECT body, state, cancel, phase, base_sha, candidate_sha, created_at FROM steps WHERE state=? AND (not_before='' OR not_before<=? OR cancel=1) ORDER BY created_at, step_id LIMIT 1", runRunning, stamp(time.Now())) |
| r, err := scanStep(func(dest ...any) error { return row.Scan(append(dest, &created)...) }) |
| if errors.Is(err, sql.ErrNoRows) { |
| return r, false, nil |
| @@ -102,6 +113,38 @@ func (s *State) nextStep(ctx context.Context) (stepRow, bool, error) { |
| return r, err == nil, err |
| } |
| +// deferStep holds an attempt for after: it stays running and is due |
| +// again then. The first deferral's time is kept (deferredSince). |
| +func (s *State) deferStep(ctx context.Context, r stepRow, after time.Duration) error { |
| + now := time.Now() |
| + _, err := s.db.ExecContext(ctx, "UPDATE steps SET not_before=?, deferred_since=CASE WHEN deferred_since='' THEN ? ELSE deferred_since END WHERE step_id=? AND attempt=? AND state=?", stamp(now.Add(after)), stamp(now), r.StepID, r.Attempt, runRunning) |
| + return err |
| +} |
| + |
| +// deferredSince is when the attempt was first deferred (zero: never). |
| +func (s *State) deferredSince(ctx context.Context, r stepRow) time.Time { |
| + var v string |
| + _ = s.db.QueryRowContext(ctx, "SELECT deferred_since FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&v) |
| + var ms int64 |
| + if _, err := fmt.Sscanf(v, "%d", &ms); err != nil || ms == 0 { |
| + return time.Time{} |
| + } |
| + return time.UnixMilli(ms) |
| +} |
| + |
| +// nextDue is when the earliest deferred attempt is due again. |
| +func (s *State) nextDue(ctx context.Context) (time.Time, bool) { |
| + var v string |
| + if s.db.QueryRowContext(ctx, "SELECT MIN(not_before) FROM steps WHERE state=? AND not_before<>''", runRunning).Scan(&v) != nil || v == "" { |
| + return time.Time{}, false |
| + } |
| + var ms int64 |
| + if _, err := fmt.Sscanf(v, "%d", &ms); err != nil { |
| + return time.Time{}, false |
| + } |
| + return time.UnixMilli(ms), true |
| +} |
| + |
| // stepCancelled re-reads an attempt's cancel mark. |
| func (s *State) stepCancelled(ctx context.Context, r stepRow) bool { |
| var cancel int |
| @@ -338,7 +381,9 @@ func (e *StepEngine) Probe(ctx context.Context) { |
| e.log("ask probe", err) |
| } |
| for _, h := range held { |
| - if h.ns != "" && !e.Verify(ctx, h.ns) { |
| + // Never released unverified: with no namespace recorded, Verify |
| + // requires that no namespace of this runner remains at all. |
| + if !e.Verify(ctx, h.ns) { |
| continue |
| } |
| e.log("ask probe", e.State.releaseAsk(ctx, h)) |
| @@ -433,6 +478,12 @@ func (e *StepEngine) loop(ctx context.Context) { |
| e.Sweep(ctx) |
| } |
| for ctx.Err() == nil { |
| + // Nothing runs beside an earlier attempt whose namespace's exit |
| + // is not verified yet: try again shortly. |
| + if e.held(ctx) { |
| + time.AfterFunc(heldRetry, e.Wake) |
| + break |
| + } |
| r, ok, err := e.State.nextStep(ctx) |
| if err != nil { |
| e.log("step state", err) |
| @@ -457,9 +508,35 @@ func (e *StepEngine) loop(ctx context.Context) { |
| } |
| e.askOne(ctx, a) |
| } |
| + // A deferred attempt (a merge waiting for the hub's CI) wakes the |
| + // worker when it is due, also after a restart. |
| + if due, ok := e.State.nextDue(ctx); ok { |
| + time.AfterFunc(max(time.Until(due), 10*time.Millisecond), e.Wake) |
| + } |
| } |
| } |
| +// heldRetry is how soon a worker held by an unverified exit looks again. |
| +var heldRetry = 5 * time.Second |
| + |
| +// held probes, then reports whether a step or question attempt still |
| +// waits for its namespace's exit to be verified (or the state cannot |
| +// tell). |
| +func (e *StepEngine) held(ctx context.Context) bool { |
| + e.Probe(ctx) |
| + steps, err := e.State.pendingSteps(ctx) |
| + if err != nil { |
| + e.log("step state", err) |
| + return true |
| + } |
| + asks, err := e.State.heldAsks(ctx) |
| + if err != nil { |
| + e.log("ask state", err) |
| + return true |
| + } |
| + return len(steps) > 0 || len(asks) > 0 |
| +} |
| + |
| // earlier compares two recorded times (RFC 3339, variable precision). |
| func earlier(a, b string) bool { |
| x, errA := time.Parse(time.RFC3339Nano, a) |
| @@ -557,7 +634,15 @@ func (e *StepEngine) runOne(ctx context.Context, r stepRow) { |
| // Shutting down: the attempt stays held; the next start settles it. |
| return |
| } |
| - if sctx.Err() != nil && rep.State != wire.StepDone { |
| + if rep.State == stepDeferred { |
| + // Held for later; the queue moves on meanwhile. |
| + e.log("step defer", e.State.deferStep(context.WithoutCancel(ctx), r, mergeCIPoll)) |
| + time.AfterFunc(mergeCIPoll, e.Wake) |
| + return |
| + } |
| + // A merge reports its real outcome even when asked to stop: the hub |
| + // may have merged it (the instance refuses cancels while merging). |
| + if sctx.Err() != nil && rep.State != wire.StepDone && r.Specialist != wire.SpecialistMerge { |
| rep.State, rep.Reason = wire.StepCancelled, "cancelled" |
| } |
| if !wire.StepTerminal(rep.State) { |
| @@ -568,3 +653,18 @@ func (e *StepEngine) runOne(ctx context.Context, r stepRow) { |
| // stepWait bounds one wait for the lease before an attempt starts. |
| const stepWait = time.Second |
| + |
| +// starter launches a contained process, calling record with its |
| +// namespace before the launch (and again once it runs); a record error |
| +// launches nothing (containment.Manager.StartRecorded). |
| +type starter interface { |
| + StartRecorded(context.Context, provider.Launch, []string, func(context.Context, containment.Record) error) (provider.Process, error) |
| +} |
| + |
| +// recordedStart starts a step's or question's process with its namespace |
| +// written durably before it launches. |
| +func recordedStart(ctx context.Context, m starter, l provider.Launch, argv []string, record func(context.Context, string) error) (provider.Process, error) { |
| + return m.StartRecorded(ctx, l, argv, func(_ context.Context, r containment.Record) error { |
| + return record(context.WithoutCancel(ctx), r.ID) |
| + }) |
| +} |
diff --git a/internal/thintest/merge_contract_test.go b/internal/thintest/merge_contract_test.go| index e7ea9f9f..62e37d55 100644 |
| --- a/internal/thintest/merge_contract_test.go |
| +++ b/internal/thintest/merge_contract_test.go |
| @@ -3,6 +3,8 @@ package thintest |
| import ( |
| "encoding/json" |
| "net/http" |
| + "net/url" |
| + "os" |
| "slices" |
| "strings" |
| "testing" |
| @@ -437,3 +439,201 @@ func TestContractDuplicateReports(t *testing.T) { |
| t.Fatalf("a cancelled task offered as similar: %+v", again) |
| } |
| } |
| + |
| +// syncNow sends a runner sync holding the rig's turn, so the instance |
| +// passes over every open task again. |
| +func (r *toolRig) syncNow(key string) { |
| + r.t.Helper() |
| + if err := r.runner.Send(r.ctx, key, wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: r.turn, Attempt: 1, State: wire.TurnRunning}}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}}); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + r.client.Snapshot(r.ctx) |
| +} |
| + |
| +// legacyReady is a task that was Ready to merge before Equipo merged on |
| +// its own: judged and approved, no merge step, and migration 0047's own |
| +// statements applied to it. |
| +func (r *toolRig) legacyReady(key, title, base, cand string) string { |
| + r.t.Helper() |
| + id := r.judgedTask(key, title, base, cand, wire.ChecksPassed, "") |
| + m := r.dispatched(wire.SpecialistMerge, base, cand, 0) |
| + db := r.inst.DB.Writer() |
| + if _, err := db.Exec("DELETE FROM chat_steps WHERE id = ?", m.StepID); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + if _, err := db.Exec("UPDATE chat_tasks SET stage = 'ready_to_merge', ready_sha = NULL, merge_eligible = NULL WHERE id = ?", id); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + raw, err := os.ReadFile("../equipo/migrations/0047_thin_merge_eligibility.sql") |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + for _, stmt := range strings.Split(string(raw), ";") { |
| + if s := strings.TrimSpace(stmt); strings.HasPrefix(s, "UPDATE") { |
| + if _, err := db.Exec(s); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + } |
| + } |
| + return id |
| +} |
| + |
| +func (r *toolRig) cardOf(id string) wire.Card { |
| + r.t.Helper() |
| + snap, err := r.client.Snapshot(r.ctx) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + for _, c := range snap.Cards { |
| + if c.Kind == wire.CardMerge && c.TaskID == id { |
| + return c |
| + } |
| + } |
| + return wire.Card{} |
| +} |
| + |
| +// Astra 4c round 1, finding 2: the merge policy is not retroactive. A |
| +// candidate already Ready when it arrived (migration 0047) is never |
| +// merged on its own: the creator gets one card, "Merge <title>?" with |
| +// Merge and Not now. Leaving Ready and coming back grants nothing; Merge |
| +// on the card adopts it. |
| +func TestContractNoRetroactiveMerge(t *testing.T) { |
| + r := newToolRig(t) |
| + ctx := r.ctx |
| + base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| + id := r.legacyReady("l", "Fix the README typo", base, cand) |
| + if k, _ := r.client.Task(ctx, id); k.Stage != wire.StageReadyToMerge { |
| + t.Fatalf("legacy %+v", k) |
| + } |
| + r.syncNow("l-sync") |
| + card := r.cardOf(id) |
| + if card.State != wire.CardOpen || card.Question != "Merge Fix the README typo?" || !slices.Equal(card.Options, []string{"merge", "not_now"}) { |
| + t.Fatalf("adoption card %+v", card) |
| + } |
| + if r.heldKinds(wire.FrameDispatch) != 0 { |
| + t.Fatal("merged a candidate that was Ready before the policy") |
| + } |
| + // Away and back: still not eligible, and the card's old revision is |
| + // stale. |
| + for _, head := range []string{strings.Repeat("9", 40), cand} { |
| + if err := r.runner.Send(ctx, "l-b-"+head[:1], wire.FrameBranch, wire.BranchReport{TaskID: id, CandidateSHA: cand, Head: head}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if head != cand { |
| + r.wait("moved", func(c *Conversation) bool { return c.Tasks[id].NeedsYou == wire.NeedsBranchMoved }) |
| + } |
| + } |
| + r.wait("ready again", func(c *Conversation) bool { |
| + return c.Tasks[id].Stage == wire.StageReadyToMerge && c.Tasks[id].NeedsYou == wire.NeedsMerge |
| + }) |
| + r.syncNow("l-sync2") |
| + if r.heldKinds(wire.FrameDispatch) != 0 { |
| + t.Fatal("leaving Ready and coming back made it eligible") |
| + } |
| + if page := r.get(r.inst.Cookie(), "/conversation", 200); !strings.Contains(page, ">Not now</button>") || !strings.Contains(page, "Merge Fix the README typo?") { |
| + t.Fatalf("adoption card on the page: %s", page) |
| + } |
| + fresh := r.cardOf(id) |
| + if out, err := r.client.Answer(ctx, fresh.ID, wire.ChoiceNotNow, fresh.Revision); err != nil || out.Card.Choice != wire.ChoiceNotNow { |
| + t.Fatalf("not now %+v %v", out, err) |
| + } |
| + if k, _ := r.client.Task(ctx, id); k.Stage != wire.StageReadyToMerge || r.heldKinds(wire.FrameDispatch) != 0 { |
| + t.Fatalf("after Not now %+v", k) |
| + } |
| + // Another legacy task, adopted: merged (checks passed, so not labelled |
| + // without checks). |
| + id2 := r.legacyReady("m", "Fix the second typo", base, strings.Repeat("3", 40)) |
| + r.syncNow("m-sync") |
| + c2 := r.cardOf(id2) |
| + if _, err := r.client.Answer(ctx, c2.ID, wire.ChoiceMerge, c2.Revision); err != nil { |
| + t.Fatal(err) |
| + } |
| + m := r.dispatched(wire.SpecialistMerge, base, strings.Repeat("3", 40), 0) |
| + r.mergedStep("m-m", m, strings.Repeat("e", 40)) |
| + r.wait("adopted and merged", func(c *Conversation) bool { return c.Tasks[id2].Stage == wire.StageDone }) |
| + if k, _ := r.client.Task(ctx, id2); k.Merged == nil || k.Merged.WithoutChecks { |
| + t.Fatalf("adopted merge %+v", k.Merged) |
| + } |
| +} |
| + |
| +// Astra 4c round 1, finding 4: the branch moving bumps an open merge |
| +// card's revision, so an answer from before the move is refused once the |
| +// branch is back; the refreshed revision merges. |
| +func TestContractMergeCardStaleAfterMove(t *testing.T) { |
| + r := newToolRig(t) |
| + ctx := r.ctx |
| + base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| + id := r.judgedTask("s", "Swipe back on iOS", base, cand, wire.ChecksCannotRun, "needs_macos") |
| + r.wait("card", func(c *Conversation) bool { return r.cardOf(id).ID != "" }) |
| + before := r.cardOf(id) |
| + for _, head := range []string{strings.Repeat("9", 40), cand} { |
| + if err := r.runner.Send(ctx, "s-b-"+head[:1], wire.FrameBranch, wire.BranchReport{TaskID: id, CandidateSHA: cand, Head: head}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if head != cand { |
| + r.wait("moved", func(c *Conversation) bool { return c.Tasks[id].NeedsYou == wire.NeedsBranchMoved }) |
| + } |
| + } |
| + r.wait("ready again", func(c *Conversation) bool { |
| + return c.Tasks[id].Stage == wire.StageReadyToMerge && c.Tasks[id].NeedsYou == wire.NeedsMerge |
| + }) |
| + after := r.cardOf(id) |
| + if after.Revision <= before.Revision || after.State != wire.CardOpen { |
| + t.Fatalf("card after the move %+v (before %+v)", after, before) |
| + } |
| + if _, err := r.client.Answer(ctx, before.ID, wire.ChoiceMerge, before.Revision); Status(err) != http.StatusConflict { |
| + t.Fatalf("an answer from before the move: %v", err) |
| + } |
| + if r.heldKinds(wire.FrameDispatch) != 0 { |
| + t.Fatal("merged on a stale answer") |
| + } |
| + if _, err := r.client.Answer(ctx, after.ID, wire.ChoiceMerge, after.Revision); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.dispatched(wire.SpecialistMerge, base, cand, 0) |
| +} |
| + |
| +// Astra 4c round 1, finding 1: a task cannot be cancelled while Equipo is |
| +// merging it (API and the coordinator's tool); the runner's report of the |
| +// hub's outcome ends it, here Done after a lost answer was settled. |
| +func TestContractCancelRefusedWhileMerging(t *testing.T) { |
| + r := newToolRig(t) |
| + ctx := r.ctx |
| + base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| + id := r.judgedTask("c", "Fix the README typo", base, cand, wire.ChecksPassed, "") |
| + m := r.dispatched(wire.SpecialistMerge, base, cand, 0) |
| + r.step("c-m-run", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, CandidateSHA: cand}) |
| + if _, err := r.client.CancelTask(ctx, id); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "task_merging") { |
| + t.Fatalf("cancelled while merging: %v", err) |
| + } |
| + if res := r.call("c-cancel", wire.ToolCancelTask, map[string]string{"task": id}); !res.IsError || res.Code != "merging" { |
| + t.Fatalf("tool cancelled while merging: %+v", res) |
| + } |
| + if status, _ := r.post(r.inst.Cookie(), "/conversation/tasks/"+id+"/cancel", url.Values{"from": {"task"}}); status != http.StatusConflict { |
| + t.Fatalf("page cancel while merging: %d", status) |
| + } |
| + if r.heldKinds(wire.FrameCancelStep) != 0 { |
| + t.Fatal("a cancel reached the runner") |
| + } |
| + r.step("c-m-done", wire.StepReport{TaskID: id, StepID: m.StepID, Attempt: 1, State: wire.StepDone, BaseSHA: base, CandidateSHA: cand, Termination: true, Findings: []wire.Finding{}, MergeSHA: strings.Repeat("e", 40), Into: "main", Strategy: wire.MergeCommit}) |
| + r.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) |
| +} |
| + |
| +// Paul, 2026-11-08: only a cancelled task forgets its sessions at once. |
| +func TestContractCancelledTaskForgetsNow(t *testing.T) { |
| + r := newToolRig(t) |
| + id, _ := r.pushed("f", "Fix the README typo", strings.Repeat("1", 40), strings.Repeat("2", 40)) |
| + r.expect(wire.FrameWatchMerge) |
| + r.dispatched(wire.SpecialistChecks, strings.Repeat("1", 40), strings.Repeat("2", 40), 0) |
| + // The checks step is queued: cancel goes through the runner. |
| + if _, err := r.client.CancelTask(r.ctx, id); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, body := r.expect(wire.FrameCancelStep) |
| + c := body.(*wire.CancelStepCommand) |
| + r.step("f-cancelled", wire.StepReport{TaskID: id, StepID: c.StepID, Attempt: c.Attempt, State: wire.StepCancelled, Reason: "cancelled", Termination: true}) |
| + _, body = r.expect(wire.FrameForgetTask) |
| + if f := body.(*wire.ForgetTaskCommand); f.TaskID != id || f.KeepUntil != nil { |
| + t.Fatalf("forget %+v", f) |
| + } |
| +} |
diff --git a/internal/thintest/questions_contract_test.go b/internal/thintest/questions_contract_test.go| index dd7ba710..e6c6d7ef 100644 |
| --- a/internal/thintest/questions_contract_test.go |
| +++ b/internal/thintest/questions_contract_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "net/url" |
| "strings" |
| "testing" |
| + "time" |
| "amadan.net/oficina/equipo/internal/equipo" |
| "amadan.net/oficina/equipo/internal/wire" |
| @@ -236,8 +237,9 @@ func TestContractAskImplementer(t *testing.T) { |
| t.Fatalf("asked a step with no session: %v", err) |
| } |
| - // The task ends (merged): a waiting question stops, the runner may |
| - // forget the task's sessions, and nobody can ask any more. |
| + // The task is merged (Paul, 2026-11-08): its specialists can still be |
| + // asked for 14 days. Questions carry on; the runner is told to keep |
| + // the task's sessions until then and remove them after. |
| q5, err := r.client.Ask(ctx, id, "One more thing?", "", "k5") |
| if err != nil { |
| t.Fatal(err) |
| @@ -246,25 +248,25 @@ func TestContractAskImplementer(t *testing.T) { |
| if a5 := body.(*wire.AskCommand); a5.QuestionID != q5.ID { |
| t.Fatalf("fifth ask %+v", a5) |
| } |
| - q6, err := r.client.Ask(ctx, id, "And another?", "", "k6") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| r.step2("r-merged", wire.FrameMerged, wire.MergedReport{TaskID: id, CandidateSHA: cand}) |
| - r.wait("done", func(c *Conversation) bool { |
| - return c.Tasks[id].Stage == wire.StageDone && c.Questions[q6.ID].State == wire.QuestionCancelled |
| - }) |
| - _, body = r.expect(wire.FrameCancelAsk) |
| - if c := body.(*wire.CancelAskCommand); c.QuestionID != q5.ID { |
| - t.Fatalf("cancel_ask on the end %+v", c) |
| - } |
| + r.wait("done", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) |
| _, body = r.expect(wire.FrameForgetTask) |
| shape(t, "frames/forget_task.json", r.runner.Received[len(r.runner.Received)-1]) |
| - if f := body.(*wire.ForgetTaskCommand); f.TaskID != id || f.Person != Owner { |
| + if f := body.(*wire.ForgetTaskCommand); f.TaskID != id || f.Person != Owner || f.KeepUntil == nil || time.Until(*f.KeepUntil) < wire.KeepMergedSessions-time.Minute || time.Until(*f.KeepUntil) > wire.KeepMergedSessions { |
| t.Fatalf("forget %+v", f) |
| } |
| + if q, _ := r.client.Question(ctx, q5.ID); wire.QuestionTerminal(q.State) { |
| + t.Fatalf("the merge stopped a question %+v", q) |
| + } |
| + if _, err := r.client.Ask(ctx, id, "And after the merge?", "", "k6"); err != nil { |
| + t.Fatalf("asking about merged work: %v", err) |
| + } |
| + // Fourteen days after it was done, nobody can ask any more. |
| + if _, err := r.inst.DB.Writer().Exec("UPDATE chat_tasks SET done_at = ? WHERE id = ?", time.Now().Add(-wire.KeepMergedSessions-time.Hour).UTC(), id); err != nil { |
| + t.Fatal(err) |
| + } |
| if _, err := r.client.Ask(ctx, id, "Too late?", "", "k7"); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "task_ended") { |
| - t.Fatalf("asked an ended task: %v", err) |
| + t.Fatalf("asked 14 days after the merge: %v", err) |
| } |
| // The task carries its thread of questions. |
| k, _ := mate.client.Task(ctx, id) |
diff --git a/internal/wire/questions.go b/internal/wire/questions.go| index cacaf3ac..66ec0341 100644 |
| --- a/internal/wire/questions.go |
| +++ b/internal/wire/questions.go |
| @@ -134,8 +134,16 @@ type AnswerReport struct { |
| type ForgetTaskCommand struct { |
| Person string `json:"person"` |
| TaskID string `json:"task_id"` |
| + // KeepUntil, when set, keeps the task's sessions until then (a merged |
| + // task can still be asked about for KeepMergedSessions); null forgets |
| + // them now (a cancelled task). |
| + KeepUntil *time.Time `json:"keep_until"` |
| } |
| +// KeepMergedSessions is how long a done task's specialists can still be |
| +// asked about their work (Paul, 2026-11-08). |
| +const KeepMergedSessions = 14 * 24 * time.Hour |
| + |
| // AskRun is a question attempt the runner holds, in sync. |
| type AskRun struct { |
| QuestionID string `json:"question_id"` |
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go| index 20a32c0e..ce35777e 100644 |
| --- a/internal/wire/tasks.go |
| +++ b/internal/wire/tasks.go |
| @@ -135,6 +135,9 @@ const ( |
| CardMerge = "merge" |
| ChoiceMerge = "merge" |
| ChoiceWait = "wait" |
| + // ChoiceNotNow declines adopting a candidate that was Ready before |
| + // Equipo merged on its own ("Merge <title>?"). |
| + ChoiceNotNow = "not_now" |
| // ChoiceCheck is the answer on an access card: the person granted |
| // access, so the runner checks its reach now. |
| ChoiceCheck = "check" |
diff --git a/internal/wire/wiretest/testdata/frames/forget_task.json b/internal/wire/wiretest/testdata/frames/forget_task.json| index 455218d8..b4d5962b 100644 |
| --- a/internal/wire/wiretest/testdata/frames/forget_task.json |
| +++ b/internal/wire/wiretest/testdata/frames/forget_task.json |
| @@ -1 +1 @@ |
| -{"id":"c23","type":"forget_task","data":{"person":"owner@example.com","task_id":"tk0001"}} |
| +{"id":"c23","type":"forget_task","data":{"person":"owner@example.com","task_id":"tk0001","keep_until":"2026-11-21T10:00:00Z"}} |