instance: task priority and by, holds, Needs you card, Run now
record_task and start_task take low or normal and by, at creation only;
PUT /tasks/{id}/priority is the creator's tap (revision, roster, audit)
and reaches the runner; a held step shows its hold, stays queued and,
where the creator's input matters, is Needs you with a recommendation;
POST /tasks/{id}/run-now writes one release per step revision and never
passes a spending bar; preference until; migration 0073. New copy is
marked for review.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
25 files changed,
+1,163
−28
internal/equipo/app.go+2 −0internal/equipo/chat/connections.go+62 −9internal/equipo/chat/http.go+38 −0internal/equipo/chat/inner.go+1 −1internal/equipo/chat/models.go+1 −1internal/equipo/chat/projects.go+5 −0internal/equipo/chat/review.go+5 −0internal/equipo/chat/schedule.go+459 −0internal/equipo/chat/schedule_store_test.go+54 −0internal/equipo/chat/tasks.go+78 −6internal/equipo/chat/tools.go+2 −0internal/equipo/copy.go+25 −0internal/equipo/migrations/0073_thin_scheduler.sql+7 −0internal/equipo/migrations/schema.sql+5 −2internal/equipo/templates/task_card.html+2 −1internal/equipo/templates/work_task.html+1 −0internal/equipo/work_pages.go+117 −0internal/equipo/work_views.go+17 −1internal/runner/thin/mcp.go+11 −2internal/thintest/client.go+10 −0internal/thintest/scheduler_contract_test.go+219 −0internal/wire/runners.go+27 −3internal/wire/schedule_test.go+13 −0internal/wire/wiretest/testdata/api/card-held.json+1 −1internal/wire/wiretest/testdata/api/task-held.json+1 −1
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index 62591a05..be3a3abc 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -240,6 +240,8 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| r.Post("/conversation/tasks/{id}/cancel", a.workTaskAction(false)) |
| r.Post("/conversation/tasks/{id}/recover", a.workTaskRecover) |
| r.Post("/conversation/tasks/{id}/unsandboxed", a.workTaskUnsandboxed) |
| + r.Post("/conversation/tasks/{id}/priority", a.workTaskPriority) |
| + r.Post("/conversation/tasks/{id}/run-now", a.workTaskRunNow) |
| r.Post("/tasks/{id}/duplicate", a.workDuplicate) |
| r.Post("/projects/{id}/star", a.workStar) |
| r.Post("/tasks/{id}/uncombine", a.workUncombine) |
diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go| index a18e151e..c695f6e3 100644 |
| --- a/internal/equipo/chat/connections.go |
| +++ b/internal/equipo/chat/connections.go |
| @@ -433,14 +433,39 @@ func (s *Store) Forget(ctx context.Context, person, id string) error { |
| // ("" is Automatic). |
| func preferenceKey(person string) string { return "prefer:" + person } |
| +// preferenceUntilKey holds when the person's preference ends by itself |
| +// (RFC 3339, "" for no end). |
| +func preferenceUntilKey(person string) string { return "prefer_until:" + person } |
| + |
| +// preferenceOf is the stored preference at now: one whose end has passed |
| +// is Automatic (connectors spec §7). |
| +func (t *txn) preferenceOf(person string) (wire.Preferences, error) { |
| + value, _, revision, err := t.settingRevision(preferenceKey(person)) |
| + if err != nil { |
| + return wire.Preferences{}, err |
| + } |
| + out := wire.Preferences{Provider: value, Revision: revision} |
| + until, _, _, err := t.settingRevision(preferenceUntilKey(person)) |
| + if err != nil { |
| + return out, err |
| + } |
| + if at, perr := time.Parse(time.RFC3339, until); until != "" && perr == nil { |
| + if !t.now().Before(at) { |
| + out.Provider = "" |
| + } else { |
| + out.Until = &at |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| // Preference reads the person's preference. |
| func (s *Store) Preference(ctx context.Context, person string) (out wire.Preferences, err error) { |
| err = s.read(ctx, func(tx *gorm.DB) error { |
| if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| return err |
| } |
| - value, _, revision, err := (&txn{s: s, db: tx}).settingRevision(preferenceKey(person)) |
| - out = wire.Preferences{Provider: value, Revision: revision} |
| + out, err = (&txn{s: s, db: tx}).preferenceOf(person) |
| return err |
| }) |
| return out, err |
| @@ -448,9 +473,11 @@ func (s *Store) Preference(ctx context.Context, person string) (out wire.Prefere |
| // SetPreference records the person's preference against the revision |
| // they saw (ErrConflict when it moved) and tells their runner, so its |
| -// choice has it offline. The same preference again changes nothing. |
| +// choice has it offline. The same preference again changes nothing. One |
| +// with an end (Until) ends by itself; a runner too old to know an end is |
| +// refused one rather than keeping it for ever. |
| func (s *Store) SetPreference(ctx context.Context, person string, in wire.Preferences) (out wire.Preferences, err error) { |
| - if !wire.PreferenceProviders[in.Provider] { |
| + if !wire.PreferenceProviders[in.Provider] || in.Until != nil && in.Provider == "" { |
| return out, ErrInvalid |
| } |
| err = s.tx(ctx, func(t *txn) error { |
| @@ -464,18 +491,44 @@ func (s *Store) SetPreference(ctx context.Context, person string, in wire.Prefer |
| if in.Revision != revision { |
| return ErrConflict |
| } |
| - if value == in.Provider && revision > 0 { |
| - out = wire.Preferences{Provider: value, Revision: revision} |
| - return nil |
| + until := "" |
| + if in.Until != nil { |
| + at := in.Until.UTC().Truncate(time.Second) |
| + if !at.After(t.now()) || at.Sub(t.now()) > wire.MaxByAhead { |
| + return ErrInvalid |
| + } |
| + primary, err := t.s.authority.PrimaryRunner(t.db, person) |
| + if err != nil { |
| + return err |
| + } |
| + if proto, err := t.runnerProtocol(person, primary); err != nil { |
| + return err |
| + } else if proto < wire.ProtocolScheduler { |
| + return ErrRunnerTooOld |
| + } |
| + in.Until, until = &at, at.Format(time.RFC3339) |
| + } |
| + held, _, _, err := t.settingRevision(preferenceUntilKey(person)) |
| + if err != nil { |
| + return err |
| + } |
| + if value == in.Provider && held == until && revision > 0 { |
| + out, err = t.preferenceOf(person) |
| + return err |
| } |
| if revision, err = t.setSetting(preferenceKey(person), in.Provider, person); err != nil { |
| return err |
| } |
| - out = wire.Preferences{Provider: in.Provider, Revision: revision} |
| + if held != until { |
| + if _, err = t.setSetting(preferenceUntilKey(person), until, person); err != nil { |
| + return err |
| + } |
| + } |
| + out = wire.Preferences{Provider: in.Provider, Revision: revision, Until: in.Until} |
| if err := t.event(person, wire.EventPreference, "preference", person, revision, "", "", 0, out); err != nil { |
| return err |
| } |
| - return t.command(person, wire.FramePreference, wire.PreferenceCommand{Person: person, Provider: in.Provider, Revision: revision}) |
| + return t.command(person, wire.FramePreference, wire.PreferenceCommand{Person: person, Provider: in.Provider, Revision: revision, Until: in.Until}) |
| }) |
| return out, err |
| } |
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go| index 8891cd49..63a04a59 100644 |
| --- a/internal/equipo/chat/http.go |
| +++ b/internal/equipo/chat/http.go |
| @@ -78,6 +78,8 @@ func (h *HTTP) Mount(r chi.Router) { |
| r.Get("/tasks/{id}", h.thinOr("GET /tasks/{id}", thinTask, h.bearer(h.task))) |
| r.Post("/tasks/{id}/cancel", h.thinOr("POST /tasks/{id}/cancel", thinTask, h.bearer(h.cancelTask))) |
| r.Post("/tasks/{id}/retry", h.bearer(h.retryTask)) |
| + r.Put("/tasks/{id}/priority", h.bearer(h.setPriority)) |
| + r.Post("/tasks/{id}/run-now", h.bearer(h.runNow)) |
| r.Post("/tasks/{id}/kind", h.bearer(h.setKind)) |
| r.Post("/tasks/{id}/round", h.bearer(h.roundTask)) |
| r.Post("/tasks/{id}/recover", h.bearer(h.recoverTask)) |
| @@ -369,6 +371,8 @@ func (h *HTTP) fail(w http.ResponseWriter, r *http.Request, err error) { |
| personapi.WriteError(w, r, 409, "runner_offline", nil) |
| case errors.Is(err, ErrConfirmation): |
| personapi.WriteError(w, r, 422, "confirmation_required", nil) |
| + case errors.Is(err, ErrHoldBar): |
| + personapi.WriteError(w, r, http.StatusConflict, "hold_bar", nil) |
| case errors.Is(err, ErrRunnerTooOld): |
| personapi.WriteError(w, r, 409, "runner_too_old", nil) |
| case errors.Is(err, ErrActionConflict): |
| @@ -723,6 +727,40 @@ func (h *HTTP) retryTask(w http.ResponseWriter, r *http.Request, p personapi.Per |
| writeJSON(w, http.StatusAccepted, wire.TaskAccepted{Attempt: attempt}) |
| } |
| +// setPriority is PUT /api/v1/tasks/{id}/priority {priority, by, |
| +// revision}: the task creator's own tap; 409 when the revision moved. |
| +func (h *HTTP) setPriority(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| + var in wire.SetPriority |
| + if err := readJSON(r, &in); err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + out, err := h.Store.SetPriority(r.Context(), p.Address, chi.URLParam(r, "id"), in) |
| + if err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + writeJSON(w, 200, out) |
| +} |
| + |
| +// runNow is POST /api/v1/tasks/{id}/run-now {step, step_revision}: the |
| +// task creator's leave for the held step at that revision, 202 with the |
| +// release; 409 when the step is not held at that revision, the hold is a |
| +// spending bar, or the runner is too old. |
| +func (h *HTTP) runNow(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| + var in wire.RunNow |
| + if err := readJSON(r, &in); err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + out, err := h.Store.RunNow(r.Context(), p.Address, chi.URLParam(r, "id"), in) |
| + if err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + writeJSON(w, http.StatusAccepted, out) |
| +} |
| + |
| // roundTask is Try another round, after the automatic rounds. |
| func (h *HTTP) roundTask(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| attempt, err := h.Store.RoundTask(r.Context(), p.Address, chi.URLParam(r, "id")) |
diff --git a/internal/equipo/chat/inner.go b/internal/equipo/chat/inner.go| index de058848..8934a10c 100644 |
| --- a/internal/equipo/chat/inner.go |
| +++ b/internal/equipo/chat/inner.go |
| @@ -336,7 +336,7 @@ func (s *Store) OpenMergeCards(ctx context.Context, person string) (out map[stri |
| out = map[string]wire.Card{} |
| err = s.read(ctx, func(tx *gorm.DB) error { |
| var rows []cardRecord |
| - if err := tx.Where("person = ? AND kind IN ? AND state = ?", person, []string{wire.CardMerge, wire.CardDirection}, wire.CardOpen).Order("created_at, id").Find(&rows).Error; err != nil { |
| + if err := tx.Where("person = ? AND kind IN ? AND state = ?", person, []string{wire.CardMerge, wire.CardDirection, wire.CardHeld}, wire.CardOpen).Order("created_at, id").Find(&rows).Error; err != nil { |
| return err |
| } |
| t := &txn{s: s, db: tx} |
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go| index bf109a8b..02eabb74 100644 |
| --- a/internal/equipo/chat/models.go |
| +++ b/internal/equipo/chat/models.go |
| @@ -7,7 +7,7 @@ package chat |
| import "time" |
| // Models are the tables this package owns, for the migration check. |
| -var Models = []any{&turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, ¬ebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}} |
| +var Models = []any{&turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, ¬ebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}} |
| type turnRecord struct { |
| ID string `gorm:"primaryKey"` |
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go| index 8503f09d..acad61e0 100644 |
| --- a/internal/equipo/chat/projects.go |
| +++ b/internal/equipo/chat/projects.go |
| @@ -598,6 +598,11 @@ func (s *Store) Answer(ctx context.Context, person, id string, in wire.AnswerCar |
| out.Card, current = card, cur |
| return e |
| } |
| + if c.Kind == wire.CardHeld { |
| + card, cur, e := t.answerHeld(person, c, in) |
| + out.Card, current = card, cur |
| + return e |
| + } |
| if c.Kind == wire.CardMerge { |
| card, cur, e := t.answerMerge(person, c, in) |
| out.Card, current = card, cur |
diff --git a/internal/equipo/chat/review.go b/internal/equipo/chat/review.go| index 68f3befb..412ded47 100644 |
| --- a/internal/equipo/chat/review.go |
| +++ b/internal/equipo/chat/review.go |
| @@ -151,6 +151,11 @@ func (p progress) needsYou(k taskRecord) string { |
| } |
| return wire.NeedsRetry |
| } |
| + if h := stepHold(*p.last); h != nil && h.NeedsPerson != "" && !wire.StepTerminal(p.last.State) { |
| + // The scheduler holds the step and the person's input changes the |
| + // outcome (connectors spec §8). |
| + return wire.NeedsHeld |
| + } |
| if p.last.State != wire.StepDone || p.eng == nil || p.eng.Round < wire.MaxFixRounds || p.candidate != p.eng.CandidateSHA { |
| return "" |
| } |
diff --git a/internal/equipo/chat/schedule.go b/internal/equipo/chat/schedule.go| new file mode 100644 |
| index 00000000..178ebbcf |
| --- /dev/null |
| +++ b/internal/equipo/chat/schedule.go |
| @@ -0,0 +1,459 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "slices" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// The scheduler on the instance (connectors spec 2026-11-12 rev 3.1, §6 |
| +// and §8, slice S3). A task has a priority and an optional deadline: the |
| +// coordinator may set low or normal, and by, only when it creates the |
| +// task; every later change and every urgent is the task creator's own |
| +// tap. The runner holds steps and says why; the task shows the hold, and |
| +// asks its creator only where their input changes the outcome (the |
| +// deadline check, no reset in sight, nothing that can run it), with |
| +// Equipo's recommendation. Run now is the creator's leave for one step |
| +// revision: a durable release the runner consumes with the admission it |
| +// causes. |
| + |
| +// releaseRecord is one Run now: at most one per step revision. |
| +type releaseRecord struct { |
| + ID string `gorm:"primaryKey"` |
| + TaskID string `gorm:"index:chat_release_task"` |
| + StepID string `gorm:"uniqueIndex:chat_release_step,priority:1"` |
| + StepRevision int64 `gorm:"uniqueIndex:chat_release_step,priority:2"` |
| + Person string |
| + RunnerID string |
| + CreatedAt time.Time |
| +} |
| + |
| +func (releaseRecord) TableName() string { return "chat_releases" } |
| + |
| +// ErrHoldBar: Run now cannot pass a spending bar (the budget, the spend |
| +// unknown); the hold offers Raise the budget or Resume instead. |
| +var ErrHoldBar = errors.New("chat: run now cannot pass this hold") |
| + |
| +// Choices on the held card. |
| +const ( |
| + ChoiceWait = "wait_reset" |
| + ChoiceRunNow = "run_now" |
| +) |
| + |
| +// toolPriority reads the coordinator's priority and deadline on |
| +// record_task or start_task: low or normal (never urgent), and a |
| +// deadline in the future, at most a year ahead. ok false: refused. |
| +func toolPriority(priority, by string, now time.Time) (string, *time.Time, bool) { |
| + if priority != "" && !wire.CoordinatorPriority(priority) { |
| + return "", nil, false |
| + } |
| + if by == "" { |
| + return priority, nil, true |
| + } |
| + t, err := time.Parse(time.RFC3339, by) |
| + if err != nil { |
| + d, derr := time.Parse("2006-01-02", by) |
| + if derr != nil { |
| + return "", nil, false |
| + } |
| + // A date is the end of that day, UTC until a zone is known. |
| + t = d.Add(24*time.Hour - time.Second) |
| + } |
| + if !t.After(now) || t.Sub(now) > wire.MaxByAhead { |
| + return "", nil, false |
| + } |
| + t = t.UTC() |
| + return priority, &t, true |
| +} |
| + |
| +// coordinatorSetsPriority records the coordinator's priority and deadline |
| +// on a task it is creating (in this turn, nothing set before). Anything |
| +// else is refused: the model can describe, never loosen (§6). |
| +func (t *txn) coordinatorSetsPriority(k *taskRecord, r turnRecord, priority string, by *time.Time) error { |
| + if priority == "" && by == nil { |
| + return nil |
| + } |
| + if k.TurnID != r.ID || k.PrioritySetBy != "" { |
| + return nil |
| + } |
| + k.Priority, k.DueBy, k.PrioritySetBy = priority, by, wire.PrioritySetByCoordinator |
| + return t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Updates(map[string]any{"priority": k.Priority, "due_by": k.DueBy, "priority_set_by": k.PrioritySetBy}).Error |
| +} |
| + |
| +// taskPriority is a task's priority on its read shape; absent while it |
| +// is the default (normal, no deadline, nobody set it). |
| +func taskPriority(k taskRecord) *wire.TaskPriority { |
| + if k.Priority == "" && k.DueBy == nil && k.PrioritySetBy == "" { |
| + return nil |
| + } |
| + p := k.Priority |
| + if p == "" { |
| + p = wire.PriorityNormal |
| + } |
| + return &wire.TaskPriority{Priority: p, By: k.DueBy, SetBy: k.PrioritySetBy} |
| +} |
| + |
| +// stepHold is a step's hold as stored ("" none). |
| +func stepHold(s stepRecord) *wire.StepHold { |
| + if s.Hold == "" { |
| + return nil |
| + } |
| + var h wire.StepHold |
| + if json.Unmarshal([]byte(s.Hold), &h) != nil { |
| + return nil |
| + } |
| + return &h |
| +} |
| + |
| +// acceptHold records a held step's hold from its runner's report, or |
| +// clears it. A hold the instance cannot read is not kept. |
| +func acceptHold(s *stepRecord, v *wire.StepReport) bool { |
| + if v.Hold == nil || wire.StepTerminal(v.State) { |
| + changed := s.Hold != "" |
| + s.Hold = "" |
| + return changed |
| + } |
| + h := *v.Hold |
| + if !wire.HoldReasons[h.Reason] || !wire.HoldNeeds[h.NeedsPerson] || len(h.Connection) > 200 || len(h.Provider) > 40 || h.StepRevision < 0 { |
| + return false |
| + } |
| + raw := asJSON(h) |
| + changed := raw != s.Hold |
| + s.Hold = raw |
| + return changed |
| +} |
| + |
| +// SetPriority is the task creator's priority and deadline (PUT |
| +// /api/v1/tasks/{id}/priority): the actor from the session, the roster |
| +// checked in the transaction, against the task's revision. A step the |
| +// runner holds takes it at once (the durable priority frame). |
| +func (s *Store) SetPriority(ctx context.Context, person, id string, in wire.SetPriority) (out wire.Task, err error) { |
| + if !wire.ValidPriority(in.Priority) { |
| + return out, ErrInvalid |
| + } |
| + err = s.tx(ctx, func(t *txn) error { |
| + if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| + return err |
| + } |
| + if err := t.isOwner(person); err != nil { |
| + return err |
| + } |
| + k, err := t.loadTask(id) |
| + if err != nil { |
| + return err |
| + } |
| + if k.Creator != person { |
| + return ErrForbidden |
| + } |
| + if wire.FinalStage(k.Stage) || k.CancelRequested { |
| + return ErrTaskEnded |
| + } |
| + if in.Revision != k.Revision { |
| + return ErrConflict |
| + } |
| + var by *time.Time |
| + if in.By != nil { |
| + b := in.By.UTC() |
| + if !b.After(t.now()) || b.Sub(t.now()) > wire.MaxByAhead { |
| + return ErrInvalid |
| + } |
| + by = &b |
| + } |
| + k.Priority, k.DueBy, k.PrioritySetBy = in.Priority, by, wire.PrioritySetByPerson |
| + if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("priority", "due_by", "priority_set_by").Updates(&k).Error; err != nil { |
| + return err |
| + } |
| + if err := t.saveTask(&k); err != nil { |
| + return err |
| + } |
| + if err := t.audit(person, "task.priority", k.ID+"@"+in.Priority); err != nil { |
| + return err |
| + } |
| + if err := t.sendPriority(k); err != nil { |
| + return err |
| + } |
| + out, err = t.taskView(k) |
| + return err |
| + }) |
| + return out, err |
| +} |
| + |
| +// sendPriority tells the runner of the task's queued or running step its |
| +// new priority (a runner below the scheduler's protocol never spends, |
| +// and takes the priority with its next dispatch). |
| +func (t *txn) sendPriority(k taskRecord) error { |
| + var held []stepRecord |
| + if err := t.db.Where("task_id = ? AND state IN ? AND runner_id <> ''", k.ID, []string{wire.StepQueued, wire.StepRunning}).Find(&held).Error; err != nil { |
| + return err |
| + } |
| + sent := map[string]bool{} |
| + for _, st := range held { |
| + if sent[st.RunnerID] { |
| + continue |
| + } |
| + sent[st.RunnerID] = true |
| + proto, err := t.runnerProtocol(st.Person, st.RunnerID) |
| + if err != nil { |
| + return err |
| + } |
| + if proto < wire.ProtocolScheduler { |
| + continue |
| + } |
| + p := k.Priority |
| + if p == "" { |
| + p = wire.PriorityNormal |
| + } |
| + if err := t.commandTo(st.RunnerID, st.Person, wire.FramePriority, wire.PriorityCommand{Person: st.Person, TaskID: k.ID, Priority: p, By: k.DueBy, Revision: k.Revision}); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// RunNow is the task creator's Run it now anyway (POST |
| +// /api/v1/tasks/{id}/run-now): leave for the held step at the revision |
| +// its hold shows, written as a durable release (one per step revision; |
| +// a second tap answers the first). It never passes a spending bar, and |
| +// an older runner is refused rather than handed it. |
| +func (s *Store) RunNow(ctx context.Context, person, id string, in wire.RunNow) (out wire.RunNowAccepted, err error) { |
| + err = s.tx(ctx, func(t *txn) error { |
| + if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| + return err |
| + } |
| + if err := t.isOwner(person); err != nil { |
| + return err |
| + } |
| + k, err := t.loadTask(id) |
| + if err != nil { |
| + return err |
| + } |
| + if k.Creator != person { |
| + return ErrForbidden |
| + } |
| + if wire.FinalStage(k.Stage) || k.CancelRequested { |
| + return ErrTaskEnded |
| + } |
| + rel, err := t.release(k, person, in.Step, in.StepRevision) |
| + out.Release = rel |
| + return err |
| + }) |
| + return out, err |
| +} |
| + |
| +// release writes the release for the task's held step at revision, in t. |
| +func (t *txn) release(k taskRecord, person, step string, revision int64) (string, error) { |
| + var st stepRecord |
| + if err := t.db.Where("id = ? AND task_id = ?", step, k.ID).First(&st).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| + return "", ErrNotFound |
| + } else if err != nil { |
| + return "", err |
| + } |
| + var prior releaseRecord |
| + err := t.db.Where("step_id = ? AND step_revision = ?", st.ID, revision).First(&prior).Error |
| + if err == nil { |
| + return prior.ID, nil |
| + } |
| + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return "", err |
| + } |
| + h := stepHold(st) |
| + if wire.StepTerminal(st.State) || h == nil || h.StepRevision != revision { |
| + // Not held, or held at another revision now: stale. |
| + return "", ErrConflict |
| + } |
| + if h.Reason == wire.HoldBudget || h.Reason == wire.HoldSpendUnknown { |
| + return "", ErrHoldBar |
| + } |
| + proto, err := t.runnerProtocol(st.Person, st.RunnerID) |
| + if err != nil { |
| + return "", err |
| + } |
| + if proto < wire.ProtocolScheduler { |
| + return "", ErrRunnerTooOld |
| + } |
| + r := releaseRecord{ID: newID("rl_"), TaskID: k.ID, StepID: st.ID, StepRevision: revision, Person: person, RunnerID: st.RunnerID, CreatedAt: t.now()} |
| + if err := t.db.Create(&r).Error; err != nil { |
| + return "", err |
| + } |
| + if err := t.audit(person, "task.run_now", st.ID+"@"+itoa64(revision)); err != nil { |
| + return "", err |
| + } |
| + // The held card for this step is answered by the tap too. |
| + if err := t.closeHeldCards(k.ID, ChoiceRunNow); err != nil { |
| + return "", err |
| + } |
| + return r.ID, t.commandTo(st.RunnerID, st.Person, wire.FrameRelease, wire.ReleaseCommand{ID: r.ID, Person: st.Person, TaskID: k.ID, StepID: st.ID, StepRevision: revision}) |
| +} |
| + |
| +// openRelease is an unconsumed release the instance wrote for the step's |
| +// dispatched attempt (a step placed again carries it). |
| +func (t *txn) openRelease(s stepRecord) (string, error) { |
| + var r releaseRecord |
| + err := t.db.Where("step_id = ? AND step_revision = ?", s.ID, s.Attempt).First(&r).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return "", nil |
| + } |
| + return r.ID, err |
| +} |
| + |
| +// heldCard asks the task's creator about a held step where their input |
| +// changes the outcome (§8), once per step revision and need, with |
| +// Equipo's recommendation; a hold that no longer needs them resolves it. |
| +func (t *txn) heldCard(k taskRecord, s stepRecord) error { |
| + h := stepHold(s) |
| + if h == nil || h.NeedsPerson == "" || wire.FinalStage(k.Stage) || k.CancelRequested { |
| + return t.closeHeldCards(k.ID, "") |
| + } |
| + name := heldName(s.ID, h) |
| + var n int64 |
| + if err := t.db.Model(&cardRecord{}).Where("task_id = ? AND kind = ? AND name = ?", k.ID, wire.CardHeld, name).Count(&n).Error; err != nil || n > 0 { |
| + return err |
| + } |
| + if err := t.closeHeldCards(k.ID, ""); err != nil { |
| + return err |
| + } |
| + options := []string{ChoiceWait, ChoiceRunNow} |
| + if h.Reason == wire.HoldBudget || h.Reason == wire.HoldSpendUnknown { |
| + // Run now cannot pass a spending bar: the hold's own actions are |
| + // on the task. |
| + options = []string{ChoiceWait} |
| + } |
| + opts, _ := json.Marshal(options) |
| + now := t.now() |
| + c := cardRecord{ID: newID("c_"), Person: k.Creator, Kind: wire.CardHeld, State: wire.CardOpen, ProjectID: k.ProjectID, TaskID: k.ID, Name: name, Question: t.heldQuestion(k, h, now), Options: string(opts), Revision: 1, CreatedAt: now, UpdatedAt: now} |
| + if err := t.db.Create(&c).Error; err != nil { |
| + return err |
| + } |
| + return t.cardEvent(c) |
| +} |
| + |
| +// heldName binds a held card to its step, revision and need. |
| +func heldName(step string, h *wire.StepHold) string { |
| + return step + "@" + itoa64(h.StepRevision) + ":" + h.NeedsPerson |
| +} |
| + |
| +// closeHeldCards resolves the task's open held cards (answered with |
| +// choice when given, else withdrawn). |
| +func (t *txn) closeHeldCards(task, choice string) error { |
| + var open []cardRecord |
| + if err := t.db.Where("task_id = ? AND kind = ? AND state = ?", task, wire.CardHeld, wire.CardOpen).Find(&open).Error; err != nil { |
| + return err |
| + } |
| + for _, c := range open { |
| + c.State, c.Choice = wire.CardResolved, choice |
| + if choice != "" { |
| + c.State = wire.CardAnswered |
| + } |
| + if err := t.saveCard(&c); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// heldQuestion is the card's words, Equipo's recommendation (merge |
| +// authority §4.1): wait when a reset comes in time, run it now when none |
| +// does or nothing else can run it. |
| +func (t *txn) heldQuestion(k taskRecord, h *wire.StepHold, now time.Time) string { |
| + name := providerWord(h.Provider) |
| + switch { |
| + case h.NeedsPerson == wire.HoldNeedsNoConnection: |
| + return t.words("chat.held.run.no_connection") |
| + case h.ResetsAt != nil && k.DueBy != nil && h.ResetsAt.Before(*k.DueBy): |
| + return t.words("chat.held.wait.before", name, clock(*h.ResetsAt), day(*k.DueBy)) |
| + case h.ResetsAt != nil && h.ResetsAt.Sub(now) <= 72*time.Hour && h.NeedsPerson != wire.HoldNeedsDeadline: |
| + return t.words("chat.held.wait.reset", name, clock(*h.ResetsAt)) |
| + case h.ResetsAt != nil && k.DueBy != nil: |
| + return t.words("chat.held.run.after_by", name, clock(*h.ResetsAt), day(*k.DueBy)) |
| + case h.Reason == wire.HoldSpendUnknown: |
| + return t.words("chat.held.spend_unknown", name) |
| + case h.Reason == wire.HoldBudget: |
| + return t.words("chat.held.budget", name) |
| + } |
| + return t.words("chat.held.run.no_reset", name) |
| +} |
| + |
| +// providerWord is a provider as people say it. |
| +func providerWord(p string) string { |
| + switch p { |
| + case wire.ProviderClaude: |
| + return "Claude" |
| + case wire.ProviderCodex: |
| + return "Codex" |
| + case wire.ProviderTensorX: |
| + return "TensorX" |
| + case "": |
| + return "Equipo" |
| + } |
| + return strings.ToUpper(p[:1]) + p[1:] |
| +} |
| + |
| +func clock(t time.Time) string { return t.UTC().Format("Mon 15:04") + " UTC" } |
| +func day(t time.Time) string { return t.UTC().Format("Monday 2 Jan") } |
| + |
| +// answerHeld is the creator's answer on a held card: Wait closes it; Run |
| +// it now writes the release for the step revision the card asked about. |
| +func (t *txn) answerHeld(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| + if err := t.hkForbid("run now"); err != nil { |
| + return wire.Card{}, wire.Card{}, err |
| + } |
| + v, err := t.cardView(c) |
| + if err != nil { |
| + return wire.Card{}, wire.Card{}, err |
| + } |
| + 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 { |
| + return wire.Card{}, v, ErrCardConflict |
| + } |
| + k, err := t.loadTask(c.TaskID) |
| + if err != nil { |
| + return wire.Card{}, wire.Card{}, err |
| + } |
| + if k.Creator != person || c.Person != person { |
| + return wire.Card{}, wire.Card{}, ErrForbidden |
| + } |
| + if err := t.isOwner(person); err != nil { |
| + return wire.Card{}, wire.Card{}, err |
| + } |
| + if in.Choice == ChoiceRunNow { |
| + step, rest, _ := strings.Cut(c.Name, "@") |
| + rev, _, _ := strings.Cut(rest, ":") |
| + var revision int64 |
| + for _, ch := range rev { |
| + revision = revision*10 + int64(ch-'0') |
| + } |
| + if _, err := t.release(k, person, step, revision); errors.Is(err, ErrConflict) || errors.Is(err, ErrHoldBar) { |
| + return wire.Card{}, v, ErrCardConflict |
| + } else if err != nil { |
| + return wire.Card{}, wire.Card{}, err |
| + } |
| + fresh, err := t.loadCard(c.ID) |
| + if err != nil { |
| + return wire.Card{}, wire.Card{}, err |
| + } |
| + out, err := t.cardView(fresh) |
| + return out, wire.Card{}, err |
| + } |
| + c.State, c.Choice = wire.CardAnswered, in.Choice |
| + if err := t.saveCard(&c); err != nil { |
| + return wire.Card{}, wire.Card{}, err |
| + } |
| + out, err := t.cardView(c) |
| + return out, wire.Card{}, err |
| +} |
| + |
| +func (t *txn) loadCard(id string) (cardRecord, error) { |
| + var c cardRecord |
| + err := t.db.Where("id = ?", id).First(&c).Error |
| + return c, err |
| +} |
diff --git a/internal/equipo/chat/schedule_store_test.go b/internal/equipo/chat/schedule_store_test.go| new file mode 100644 |
| index 00000000..5f941aad |
| --- /dev/null |
| +++ b/internal/equipo/chat/schedule_store_test.go |
| @@ -0,0 +1,54 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "slices" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// The scheduler's writes (connectors spec S3): the priority and Run now |
| +// are the task creator's own taps. Another owner, and a roster check |
| +// failing between authentication and the write, change nothing; a |
| +// priority change is audited in its transaction. |
| +func TestSchedulerWritesCheckCreatorAndRoster(t *testing.T) { |
| + r := newMeteredRig(t) |
| + now := r.s.now() |
| + g := r.s.db.G |
| + if err := g.Create(&projectRecord{ID: "p_1", Repo: "amadan.net/oficina/sample", State: wire.ProjectActive, CreatedAt: now, UpdatedAt: now}).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := g.Create(&taskRecord{ID: "tk1", ProjectID: "p_1", Title: "T", Stage: wire.StageInProgress, Creator: "owner@example.com", Revision: 3, CreatedAt: now, UpdatedAt: now}).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + hold := asJSON(wire.StepHold{Reason: wire.HoldHeadroom, NeedsPerson: wire.HoldNeedsNoReset, StepRevision: 1}) |
| + if err := g.Create(&stepRecord{ID: "s1", TaskID: "tk1", Idx: 1, Specialist: wire.SpecialistEngineering, Person: "owner@example.com", State: wire.StepQueued, Attempt: 1, Hold: hold, Revision: 1, CreatedAt: now, UpdatedAt: now}).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + set := wire.SetPriority{Priority: wire.PriorityUrgent, Revision: 3} |
| + if _, err := r.s.SetPriority(ctx, "other@example.com", "tk1", set); !errors.Is(err, ErrForbidden) { |
| + t.Fatalf("another owner's priority: %v", err) |
| + } |
| + if _, err := r.s.RunNow(ctx, "other@example.com", "tk1", wire.RunNow{Step: "s1", StepRevision: 1}); !errors.Is(err, ErrForbidden) { |
| + t.Fatalf("another owner's Run now: %v", err) |
| + } |
| + r.removed = true |
| + if _, err := r.s.SetPriority(ctx, "owner@example.com", "tk1", set); !errors.Is(err, ErrForbidden) { |
| + t.Fatalf("a removed creator's priority: %v", err) |
| + } |
| + if _, err := r.s.RunNow(ctx, "owner@example.com", "tk1", wire.RunNow{Step: "s1", StepRevision: 1}); !errors.Is(err, ErrForbidden) { |
| + t.Fatalf("a removed creator's Run now: %v", err) |
| + } |
| + r.unchanged("refused writes") |
| + r.removed = false |
| + out, err := r.s.SetPriority(ctx, "owner@example.com", "tk1", set) |
| + if err != nil || out.Priority == nil || out.Priority.Priority != wire.PriorityUrgent { |
| + t.Fatalf("the creator's priority: %+v %v", out.Priority, err) |
| + } |
| + if !slices.Contains(r.audits, "owner@example.com task.priority tk1@urgent") { |
| + t.Fatalf("audits %v", r.audits) |
| + } |
| +} |
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go| index f4ee868f..20b15064 100644 |
| --- a/internal/equipo/chat/tasks.go |
| +++ b/internal/equipo/chat/tasks.go |
| @@ -102,6 +102,12 @@ type taskRecord struct { |
| DirectionAsked string |
| BuiltAs string |
| ExploredFrom string |
| + // The scheduler (connectors spec S3): the task's priority ("" is |
| + // normal), its deadline, and who set them: the coordinator at the |
| + // task's creation, or the creator's own tap. |
| + Priority string |
| + DueBy *time.Time |
| + PrioritySetBy string |
| } |
| func (taskRecord) TableName() string { return "chat_tasks" } |
| @@ -234,6 +240,9 @@ type stepRecord struct { |
| // one at that revision (authorizeResearch). |
| ResearchGrant string |
| ResearchGrantRevision int64 |
| + // Hold is why the runner holds the step now (wire.StepHold JSON, "" |
| + // when it does not): the scheduler's report. |
| + Hold string |
| } |
| func (stepRecord) TableName() string { return "chat_steps" } |
| @@ -404,9 +413,11 @@ func stepView(s stepRecord) wire.Step { |
| Rebase: s.Rebase, MergeSHA: s.MergeSHA, Into: s.MergeInto, Strategy: s.MergeStrategy, WithoutChecks: s.WithoutChecks, Activity: decodeActivity(s.Activity), Preview: decodePreview(s.Preview)} |
| } |
| -// stepViewSwitched adds the switched line, when the step moved. |
| +// stepViewSwitched adds the switched line, when the step moved, and the |
| +// scheduler's hold. |
| func stepViewSwitched(s stepRecord) wire.Step { |
| v := stepView(s) |
| + v.Hold = stepHold(s) |
| if s.Switched != "" { |
| v.Switched = &wire.Switched{} |
| if json.Unmarshal([]byte(s.Switched), v.Switched) != nil { |
| @@ -467,6 +478,7 @@ func (t *txn) taskView(k taskRecord) (wire.Task, error) { |
| v.ChecksSandbox = pr.checks.ChecksSandbox |
| } |
| v.NeedsYou = pr.needsYou(k) |
| + v.Priority = taskPriority(k) |
| if pr.eng != nil { |
| v.FixRounds = pr.eng.Round |
| } |
| @@ -592,7 +604,7 @@ func (t *txn) writeStep(s *stepRecord) error { |
| } |
| s.Revision++ |
| s.UpdatedAt = t.now() |
| - if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision").Updates(s).Error; err != nil { |
| + if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Select("state", "reason", "attempt", "base_sha", "candidate_sha", "pushed", "terminated", "summary", "log_tail", "started_at", "finished_at", "revision", "updated_at", "headline", "family", "account", "verdict", "review_label", "findings", "checks", "gate", "exit_code", "output", "republish", "from_attempt", "askable", "rebase", "from_base", "from_candidate", "merge_sha", "merge_into", "merge_strategy", "without_checks", "switched", "activity", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id", "apple", "checks_sandbox", "change_facts", "decided_by", "merge_source", "merge_parents", "hosted_ci", "kind", "note", "sandbox_runner", "unsandboxed_by", "unsandboxed_at", "unsandboxed_attempt", "unsandboxed_runner", "has_preview", "preview", "boundary", "question", "request_turn", "sources_card", "sources_hash", "research_grant", "research_grant_revision", "hold").Updates(s).Error; err != nil { |
| return err |
| } |
| members, err := t.members() |
| @@ -879,6 +891,16 @@ func (t *txn) dispatchStep(k *taskRecord, s *stepRecord) error { |
| return err |
| } |
| cmd := wire.DispatchCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt, Specialist: s.Specialist, Repo: p.Repo, Branch: k.Branch, BaseSHA: base, Title: k.Title, Brief: brief, Findings: v.Findings, Round: s.Round, Republish: s.Republish, FromAttempt: s.FromAttempt} |
| + // The scheduler's facts (protocol 14; Encode drops them for an older |
| + // runner): the task's priority and deadline, and a Run now written for |
| + // this attempt. Housekeeping's own dispatches count as low and carry |
| + // no release: they never spend (§7, Housekeeping). |
| + cmd.Priority, cmd.By = k.Priority, k.DueBy |
| + if t.hk != nil { |
| + cmd.Priority = wire.PriorityLow |
| + } else if cmd.Release, err = t.openRelease(*s); err != nil { |
| + return err |
| + } |
| if s.Specialist != wire.SpecialistEngineering || s.Republish { |
| cmd.CandidateSHA = s.CandidateSHA |
| } |
| @@ -1134,6 +1156,11 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error { |
| s.Terminated, changed = true, true |
| } |
| } else { |
| + // The scheduler's hold: kept while the runner holds the step, |
| + // cleared by any report without it. |
| + if acceptHold(&s, v) { |
| + changed = true |
| + } |
| if wire.StepTerminal(v.State) { |
| if err := t.recordUsage(l.Protocol, s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil { |
| return err |
| @@ -1164,7 +1191,8 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error { |
| } |
| switch v.State { |
| case wire.StepRunning: |
| - if s.State == wire.StepQueued { |
| + if s.State == wire.StepQueued && v.Hold == nil { |
| + // A held step is still queued: it starts when it runs. |
| s.State, s.StartedAt, changed = wire.StepRunning, &now, true |
| } |
| if previewBuilt(l, role, &s, v) { |
| @@ -1300,6 +1328,11 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error { |
| if err := t.saveStep(&s, &k); err != nil { |
| return err |
| } |
| + // Needs you for a hold where the creator's input changes the outcome |
| + // (connectors spec §8), or the card withdrawn once it does not. |
| + if err := t.heldCard(k, s); err != nil { |
| + return err |
| + } |
| return t.advance(&k) |
| } |
| @@ -1730,10 +1763,18 @@ func (t *txn) taskTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) |
| Brief string `json:"brief"` |
| Separate bool `json:"separate"` |
| Kind string `json:"kind"` |
| + // The scheduler (protocol 14): low or normal, and a deadline, |
| + // from what the person said. |
| + Priority string `json:"priority"` |
| + By string `json:"by"` |
| } |
| if wire.Strict(v.Args, &in) != nil || in.Kind != "" && in.Kind != wire.KindChange && in.Kind != wire.KindExplore || in.Repo == "" || len(in.Repo) > 300 || strings.ContainsAny(in.Repo, "\x00\r\n") { |
| return refused("invalid", toolBadInput), nil |
| } |
| + priority, by, ok := toolPriority(in.Priority, in.By, t.now()) |
| + if !ok { |
| + return refused("invalid", toolBadPriority), nil |
| + } |
| title, ok := cleanText(in.Title, wire.MaxTaskTitle) |
| if !ok || taskTitleBad.MatchString(title) { |
| return refused("invalid", toolBadInput), nil |
| @@ -1742,7 +1783,23 @@ func (t *txn) taskTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) |
| if len(brief) > wire.MaxTaskBrief || !utf8.ValidString(brief) || strings.ContainsRune(brief, 0) { |
| return refused("invalid", toolBadInput), nil |
| } |
| - return t.recordTask(r, in.Repo, title, brief, in.Kind, in.Separate) |
| + res, err := t.recordTask(r, in.Repo, title, brief, in.Kind, in.Separate) |
| + if err != nil || res.Code != "recorded" { |
| + return res, err |
| + } |
| + var rec struct { |
| + Task string `json:"task"` |
| + } |
| + if json.Unmarshal([]byte(res.Text), &rec) == nil { |
| + k, err := t.loadTask(rec.Task) |
| + if err != nil { |
| + return res, err |
| + } |
| + if err := t.coordinatorSetsPriority(&k, r, priority, by); err != nil { |
| + return res, err |
| + } |
| + } |
| + return res, nil |
| case wire.ToolAddReport: |
| return t.addReport(r, v.Args) |
| case wire.ToolHoldMerge: |
| @@ -1753,12 +1810,27 @@ func (t *txn) taskTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) |
| return t.addFinding(r, v.Args) |
| case wire.ToolStartTask: |
| var in struct { |
| - Task string `json:"task"` |
| - Brief string `json:"brief"` |
| + Task string `json:"task"` |
| + Brief string `json:"brief"` |
| + Priority string `json:"priority"` |
| + By string `json:"by"` |
| } |
| if wire.Strict(v.Args, &in) != nil { |
| return refused("invalid", toolBadInput), nil |
| } |
| + priority, by, ok := toolPriority(in.Priority, in.By, t.now()) |
| + if !ok { |
| + return refused("invalid", toolBadPriority), nil |
| + } |
| + if priority != "" || by != nil { |
| + // Only on a task this turn recorded and nobody set before: the |
| + // coordinator sets them at creation, never later (§6). |
| + if k, err := t.loadTask(strings.TrimSpace(in.Task)); err == nil && k.Creator == r.Person { |
| + if err := t.coordinatorSetsPriority(&k, r, priority, by); err != nil { |
| + return wire.ToolResult{}, err |
| + } |
| + } |
| + } |
| return t.startTask(r, in.Task, in.Brief) |
| case wire.ToolReadTask: |
| var in struct { |
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go| index 2471b21b..c0211c7e 100644 |
| --- a/internal/equipo/chat/tools.go |
| +++ b/internal/equipo/chat/tools.go |
| @@ -21,6 +21,8 @@ const ( |
| toolTurnEnded = "This turn has ended; the tool did nothing." |
| toolUnknown = "Unknown tool." |
| toolBadInput = "The input is not valid for this tool." |
| + // toolBadPriority: the scheduler's fields on record_task or start_task. |
| + toolBadPriority = "priority is low or normal (urgent is the person's own choice), and by is a date in the future, within a year." |
| toolAsked = "The question is on the person's screen. Their answer will arrive as their next message. Finish this reply now; do not wait for it." |
| toolNotAllowed = "That repository is not on this person's runner. Repositories you can add: " |
| toolNoneAllow = "none. The person adds repositories to their runner's forge credential file." |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index e8bd80dc..86b6d6cb 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -961,6 +961,31 @@ var pageCopy = map[string]string{ |
| "work.ask.held.busy": "Waiting: this connection is busy", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
| "work.ask.held.budget": "Waiting: this connection has reached its budget", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
| "work.ask.held.spend_unknown": "Waiting: this connection’s spend is unknown. Check your spending with the provider, then choose Resume", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
| + "work.hold.headroom": "Waiting for headroom on %s", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.hold.headroom_reset": "Waiting for headroom on %s, resets %s", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.hold.budget": "Waiting: %s has reached today’s budget", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.hold.spend_unknown": "Waiting: %s spend unknown, check it, then Resume", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.hold.busy": "Waiting: %s is running another step", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.hold.no_connection": "Waiting: nothing you connected can run it without spending", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.hold.run_now": "Run it now anyway", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.hold.raise_budget": "Raise the budget", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.hold.resume": "Resume", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.priority.urgent": "Urgent", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.priority.normal": "Normal priority", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.priority.low": "Low priority", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.priority.by": "By %s", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.priority.from_message": "set from your message", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.priority.mark_urgent": "Mark urgent", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "work.priority.make_normal": "Not urgent", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "chat.held.wait.before": "I’d wait: %s resets %s, before %s.", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "chat.held.wait.reset": "I’d wait: %s resets %s.", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "chat.held.run.after_by": "I’d run it now: %s resets %s, after %s.", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "chat.held.run.no_reset": "I’d run it now: %s has no reset in the next three days.", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "chat.held.run.no_connection": "I’d run it now: only a metered connection can run it.", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "chat.held.spend_unknown": "%s spend is unknown. Check it, then Resume.", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "chat.held.budget": "%s has reached its budget. Raise it, or wait for tomorrow.", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "chat.card.wait_reset": "Wait", // COPY REVIEW REQUIRED (S3 scheduler) |
| + "chat.card.run_now": "Run it now", // COPY REVIEW REQUIRED (S3 scheduler) |
| "chat.connections.loading_sub": "This takes a moment.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.codex_sub": "Your ChatGPT account, through Codex.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.connections.claude_sub": "Claude signs in on the machine that runs your runner.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/internal/equipo/migrations/0073_thin_scheduler.sql b/internal/equipo/migrations/0073_thin_scheduler.sql| new file mode 100644 |
| index 00000000..51054e85 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0073_thin_scheduler.sql |
| @@ -0,0 +1,7 @@ |
| +ALTER TABLE chat_tasks ADD COLUMN priority text; |
| +ALTER TABLE chat_tasks ADD COLUMN due_by datetime; |
| +ALTER TABLE chat_tasks ADD COLUMN priority_set_by text; |
| +ALTER TABLE chat_steps ADD COLUMN hold text; |
| +CREATE TABLE chat_releases (id text PRIMARY KEY, task_id text, step_id text, step_revision integer, person text, runner_id text, created_at datetime); |
| +CREATE INDEX chat_release_task ON chat_releases(task_id); |
| +CREATE UNIQUE INDEX chat_release_step ON chat_releases(step_id, step_revision); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 2f87c08c..604558ee 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -596,9 +596,9 @@ 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, ready_sha text, merge_eligible text, done_at datetime, duplicate_of text, folded_into text, folded_stage text, folded_at datetime, engineering_runner text, merge_hold text, merge_verified numeric, revert_of text, revert_sha text, kind text, direction_asked text, built_as text, explored_from 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, folded_into text, folded_stage text, folded_at datetime, engineering_runner text, merge_hold text, merge_verified numeric, revert_of text, revert_sha text, kind text, direction_asked text, built_as text, explored_from text, priority text, due_by datetime, priority_set_by 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, switched text, headline text, runner_id text, needs text, placement text, waiting_since datetime, refused_by text, withdrawn numeric, termination_kind text, publication text, publication_id text, apple numeric, checks_sandbox text, recheck_by text, change_facts text, decided_by text, merge_source text, merge_parents text, hosted_ci text, sandbox_runner text, unsandboxed_by text, unsandboxed_at datetime, unsandboxed_attempt integer, unsandboxed_runner text, has_preview numeric, preview text, kind text, note text, boundary text, question text, request_turn text, sources_card text, sources_hash text, research_grant text, research_grant_revision integer); |
| +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, switched text, headline text, runner_id text, needs text, placement text, waiting_since datetime, refused_by text, withdrawn numeric, termination_kind text, publication text, publication_id text, apple numeric, checks_sandbox text, recheck_by text, change_facts text, decided_by text, merge_source text, merge_parents text, hosted_ci text, sandbox_runner text, unsandboxed_by text, unsandboxed_at datetime, unsandboxed_attempt integer, unsandboxed_runner text, has_preview numeric, preview text, kind text, note text, boundary text, question text, request_turn text, sources_card text, sources_hash text, research_grant text, research_grant_revision integer, hold text); |
| CREATE INDEX chat_step_task ON chat_steps(task_id); |
| CREATE TABLE chat_task_entries (id text PRIMARY KEY, task_id text, idempotency_key text, kind text, author text, text text, repo text, path text, line integer, created_at datetime, headline text, folded_from text); |
| CREATE INDEX chat_entry_task ON chat_task_entries(task_id); |
| @@ -653,3 +653,6 @@ CREATE TABLE chat_task_files (id text PRIMARY KEY, task_id text, step_id text, a |
| CREATE INDEX chat_task_file_task ON chat_task_files(task_id); |
| CREATE INDEX chat_task_file_step ON chat_task_files(step_id); |
| CREATE TABLE chat_task_file_data (file_id text, idx integer, data blob, PRIMARY KEY (file_id, idx)); |
| +CREATE TABLE chat_releases (id text PRIMARY KEY, task_id text, step_id text, step_revision integer, person text, runner_id text, created_at datetime); |
| +CREATE INDEX chat_release_task ON chat_releases(task_id); |
| +CREATE UNIQUE INDEX chat_release_step ON chat_releases(step_id, step_revision); |
diff --git a/internal/equipo/templates/task_card.html b/internal/equipo/templates/task_card.html| index 06f6924c..33d57419 100644 |
| --- a/internal/equipo/templates/task_card.html |
| +++ b/internal/equipo/templates/task_card.html |
| @@ -8,5 +8,6 @@ |
| {{define "trial-label"}}{{if eq .Mode "owner mode"}}<span equipo-isolation>{{copy "isolation.owner_mode"}}</span>{{end}}{{if .ProfileApprovals}}<span equipo-isolation>{{copy "isolation.approved_beyond_profile"}}</span>{{end}}{{with .Trial}}<span equipo-isolation>{{copy "trial.label"}}: {{range .UnverifiedChecks}}<span>{{copy (printf "trial.check.%s" .)}}</span> {{end}}<span>{{copy "trial.observed_locally"}}</span></span>{{end}}{{end}} |
| -{{define "work-task-actions"}}{{if .Merge}}<form method="post" action="/conversation/tasks/{{.ID}}/merge" data-card-form><button equipo-link type="submit" data-task-merge>{{copy "work.merge_now"}}</button></form>{{end}}{{if .Retry}}<form method="post" action="/conversation/tasks/{{.ID}}/retry" data-card-form><button equipo-link type="submit" data-task-retry>{{copy "work.retry"}}</button></form>{{end}}{{if .Recover}}<form method="post" action="/conversation/tasks/{{.ID}}/recover" data-card-form><button equipo-link type="submit" data-task-recover>{{copy "work.recover"}}</button></form>{{end}}{{if .Cancel}}<form method="post" action="/conversation/tasks/{{.ID}}/cancel" data-card-form><button equipo-link type="submit" data-task-cancel>{{copy "work.cancel"}}</button></form>{{end}}{{end}} |
| +{{define "work-task-hold"}}{{with .Hold}}{{if or .RunNow .Budget .Resume}}<p equipo-card-note data-hold>{{if .RunNow}}<form method="post" action="/conversation/tasks/{{$.ID}}/run-now" data-card-form><input type="hidden" name="step" value="{{.Step}}"><input type="hidden" name="revision" value="{{.Revision}}"><button equipo-link type="submit" data-task-run-now>{{copy "work.hold.run_now"}}</button></form>{{end}}{{if .Budget}}<a equipo-link href="/conversation/settings/connections" data-task-raise-budget>{{copy "work.hold.raise_budget"}}</a>{{end}}{{if .Resume}}<a equipo-link href="/conversation/settings/connections" data-task-resume>{{copy "work.hold.resume"}}</a>{{end}}</p>{{end}}{{end}}{{with .Priority}}<p equipo-card-note data-priority>{{with .Line}}<span>{{.}}</span>{{end}}{{if .MarkUrgent}}<form method="post" action="/conversation/tasks/{{$.ID}}/priority" data-card-form><input type="hidden" name="priority" value="urgent"><input type="hidden" name="revision" value="{{.Revision}}"><button equipo-link type="submit" data-task-urgent>{{copy "work.priority.mark_urgent"}}</button></form>{{end}}{{if .MakeNormal}}<form method="post" action="/conversation/tasks/{{$.ID}}/priority" data-card-form><input type="hidden" name="priority" value="normal"><input type="hidden" name="revision" value="{{.Revision}}"><button equipo-link type="submit" data-task-normal>{{copy "work.priority.make_normal"}}</button></form>{{end}}</p>{{end}}{{end}} |
| +{{define "work-task-actions"}}{{template "work-task-hold" .}}{{if .Merge}}<form method="post" action="/conversation/tasks/{{.ID}}/merge" data-card-form><button equipo-link type="submit" data-task-merge>{{copy "work.merge_now"}}</button></form>{{end}}{{if .Retry}}<form method="post" action="/conversation/tasks/{{.ID}}/retry" data-card-form><button equipo-link type="submit" data-task-retry>{{copy "work.retry"}}</button></form>{{end}}{{if .Recover}}<form method="post" action="/conversation/tasks/{{.ID}}/recover" data-card-form><button equipo-link type="submit" data-task-recover>{{copy "work.recover"}}</button></form>{{end}}{{if .Cancel}}<form method="post" action="/conversation/tasks/{{.ID}}/cancel" data-card-form><button equipo-link type="submit" data-task-cancel>{{copy "work.cancel"}}</button></form>{{end}}{{end}} |
| {{define "work-task-row"}}<li equipo-work-task data-task="{{.ID}}" data-stage="{{.Stage}}"><p><a href="/tasks/{{.ID}}">{{.Title}}</a></p><p equipo-card-note><span>{{.Project}}</span><span>{{.StageLine}}</span>{{with .Finding}}{{if .Path}}<span>{{.Path}}:{{.Line}}</span>{{end}}{{end}}<span>{{printf (copy "work.noted_by") .Creator}}</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}}{{if .PreviewURL}}<p equipo-card-note data-preview><a href="{{.PreviewURL}}" rel="noopener" target="_blank">{{.PreviewLine}}</a></p>{{end}}</li>{{end}} |
diff --git a/internal/equipo/templates/work_task.html b/internal/equipo/templates/work_task.html| index a0e78f76..f6e94ace 100644 |
| --- a/internal/equipo/templates/work_task.html |
| +++ b/internal/equipo/templates/work_task.html |
| @@ -10,6 +10,7 @@ |
| </div> |
| {{template "track-full" .}} |
| <p equipo-t-summary data-summary>{{if .Live}}{{template "mark" ""}}{{end}}<span data-stage-line>{{.Summary}}</span></p> |
| +{{template "work-task-hold" .}} |
| {{with .Spend}}<p equipo-quiet data-spend>{{.}}</p>{{end}}{{with .SpendNote}}<p equipo-quiet data-spend-note>{{.}}</p>{{end}} |
| {{with .Dup}}{{if not $.Thin.Task.Decision}}<p equipo-dup>{{icon "alert-triangle"}}<span>{{copy "work.dup"}} <a href="/tasks/{{.ID}}">{{.Title}}</a>{{if not $.Thin.Task.Mine}} {{printf (copy "work.dup_decides") $.Thin.Task.Creator.Name}}{{end}}</span></p>{{end}}{{end}} |
| {{with .Folded}}<div equipo-combined data-folded>{{icon "check-circle"}}<span>{{copy "work.combined_line"}} <a href="/tasks/{{.Into.ID}}">{{.Into.Title}}</a>.</span>{{if $.Thin.Task.Mine}}<form method="post" action="/tasks/{{$.Thin.Task.ID}}/uncombine"><input type="hidden" name="from" value="task"><button equipo-link type="submit" data-uncombine>{{copy "chat.card.undo"}}</button></form>{{end}}</div>{{end}} |
diff --git a/internal/equipo/work_pages.go b/internal/equipo/work_pages.go| index 19394f74..7ad648aa 100644 |
| --- a/internal/equipo/work_pages.go |
| +++ b/internal/equipo/work_pages.go |
| @@ -41,6 +41,11 @@ type taskLine struct { |
| Recover bool |
| // Merge is the creator's quiet Merge on a task left at Ready to merge. |
| Merge bool |
| + // Hold is why the scheduler holds the task's step, with what the |
| + // creator can do about it; Priority the task's priority and deadline, |
| + // with the creator's own change (connectors spec §6, §8). |
| + Hold *holdLine |
| + Priority *priorityLine |
| // The inner screens' pieces (work_views.go). |
| Mono monoLine |
| Creator personLine |
| @@ -220,12 +225,86 @@ func taskLineOf(t wire.Task, viewer string) taskLine { |
| } |
| v.Cancel = !wire.FinalStage(t.Stage) && t.Stage != wire.StageMerging |
| v.Merge = t.MergeOffered |
| + v.Priority = priorityOf(t, t.Creator == viewer) |
| + if v.Step != nil && v.Step.Hold != nil && !wire.FinalStage(t.Stage) { |
| + v.Hold = holdOf(*v.Step, t.Creator == viewer) |
| + v.StageLine = v.Hold.Line |
| + } |
| if t.Creator != viewer { |
| v.Retry, v.Cancel, v.Merge, v.Recover = false, false, false, false |
| } |
| return v |
| } |
| +// holdLine is a held step's line (§8) and its actions: Run it now anyway, |
| +// or for a spending bar Raise the budget or Resume (both on the |
| +// Connections page). |
| +type holdLine struct { |
| + Line string |
| + Step string |
| + Revision int64 |
| + RunNow, Budget, Resume bool |
| +} |
| + |
| +// holdOf is the hold's words and, for the creator, its action. |
| +func holdOf(s wire.Step, mine bool) *holdLine { |
| + h := s.Hold |
| + name := providerName(h.Provider) |
| + l := &holdLine{Step: s.ID, Revision: h.StepRevision} |
| + switch h.Reason { |
| + case wire.HoldHeadroom: |
| + l.Line = fmt.Sprintf(copyText("work.hold.headroom"), name) |
| + if h.ResetsAt != nil { |
| + l.Line = fmt.Sprintf(copyText("work.hold.headroom_reset"), name, resetText(*h.ResetsAt)) |
| + } |
| + case wire.HoldBudget: |
| + l.Line, l.Budget = fmt.Sprintf(copyText("work.hold.budget"), name), mine |
| + case wire.HoldSpendUnknown: |
| + l.Line, l.Resume = fmt.Sprintf(copyText("work.hold.spend_unknown"), name), mine |
| + case wire.HoldBusy: |
| + l.Line = fmt.Sprintf(copyText("work.hold.busy"), name) |
| + default: |
| + l.Line = copyText("work.hold.no_connection") |
| + } |
| + l.RunNow = mine && h.Reason != wire.HoldBudget && h.Reason != wire.HoldSpendUnknown |
| + return l |
| +} |
| + |
| +// priorityLine is a task's priority and deadline in words, and the |
| +// creator's change: Mark urgent, or back to normal. |
| +type priorityLine struct { |
| + Line string |
| + Revision int64 |
| + MarkUrgent, MakeNormal bool |
| +} |
| + |
| +// priorityOf is nil for a normal task with no deadline that nobody set, |
| +// unless its creator may mark it urgent. |
| +func priorityOf(t wire.Task, mine bool) *priorityLine { |
| + if wire.FinalStage(t.Stage) { |
| + return nil |
| + } |
| + p, by, from := wire.PriorityNormal, (*time.Time)(nil), false |
| + if t.Priority != nil { |
| + p, by, from = t.Priority.Priority, t.Priority.By, t.Priority.SetBy == wire.PrioritySetByCoordinator |
| + } |
| + l := &priorityLine{Revision: t.Revision, MarkUrgent: mine && p != wire.PriorityUrgent, MakeNormal: mine && p == wire.PriorityUrgent} |
| + if p != wire.PriorityNormal || by != nil { |
| + parts := []string{copyText("work.priority." + p)} |
| + if by != nil { |
| + parts = append(parts, fmt.Sprintf(copyText("work.priority.by"), by.UTC().Format("Mon 2 Jan"))) |
| + } |
| + if from { |
| + parts = append(parts, copyText("work.priority.from_message")) |
| + } |
| + l.Line = strings.Join(parts, " · ") |
| + } |
| + if l.Line == "" && !l.MarkUrgent { |
| + return nil |
| + } |
| + return l |
| +} |
| + |
| // mergedLine is "Merged into main at abc1234", and says when it went in |
| // without checks. |
| func mergedLine(into, sha string, withoutChecks bool) string { |
| @@ -718,6 +797,44 @@ func (a *application) workTaskAction(retry bool) http.HandlerFunc { |
| } |
| } |
| +// workTaskPriority is the creator's Mark urgent (or back to normal) on |
| +// the task, at the revision the page showed; the deadline stays. |
| +func (a *application) workTaskPriority(w http.ResponseWriter, r *http.Request) { |
| + id := chi.URLParam(r, "id") |
| + priority := r.PostFormValue("priority") |
| + revision, perr := strconv.ParseInt(r.PostFormValue("revision"), 10, 64) |
| + a.chatActionTo(w, r, workBack(r, id), func(ctx context.Context, address string) error { |
| + if perr != nil { |
| + return chat.ErrInvalid |
| + } |
| + k, err := a.store.Chat().Task(ctx, address, id) |
| + if err != nil { |
| + return err |
| + } |
| + var by *time.Time |
| + if k.Priority != nil { |
| + by = k.Priority.By |
| + } |
| + _, err = a.store.Chat().SetPriority(ctx, address, id, wire.SetPriority{Priority: priority, By: by, Revision: revision}) |
| + return err |
| + }) |
| +} |
| + |
| +// workTaskRunNow is the creator's Run it now anyway on a held step, at |
| +// the step revision its hold showed. |
| +func (a *application) workTaskRunNow(w http.ResponseWriter, r *http.Request) { |
| + id := chi.URLParam(r, "id") |
| + step := r.PostFormValue("step") |
| + revision, perr := strconv.ParseInt(r.PostFormValue("revision"), 10, 64) |
| + a.chatActionTo(w, r, workBack(r, id), func(ctx context.Context, address string) error { |
| + if perr != nil || step == "" { |
| + return chat.ErrInvalid |
| + } |
| + _, err := a.store.Chat().RunNow(ctx, address, id, wire.RunNow{Step: step, StepRevision: revision}) |
| + return err |
| + }) |
| +} |
| + |
| // workTaskRound is Try another round from the task's decision. |
| func (a *application) workTaskRound(w http.ResponseWriter, r *http.Request) { |
| id := chi.URLParam(r, "id") |
diff --git a/internal/equipo/work_views.go b/internal/equipo/work_views.go| index 93ad6eca..5edf65ed 100644 |
| --- a/internal/equipo/work_views.go |
| +++ b/internal/equipo/work_views.go |
| @@ -217,7 +217,7 @@ func needsViewer(t wire.Task, viewer string, card *wire.Card) bool { |
| switch t.NeedsYou { |
| case wire.NeedsRetry, wire.NeedsReviewBlocked, wire.NeedsFixRounds, wire.NeedsBranchMoved, wire.NeedsMergeConflict, wire.NeedsMachineRemoved, wire.NeedsMacSandbox, wire.NeedsDirection: |
| return true |
| - case wire.NeedsMerge: |
| + case wire.NeedsMerge, wire.NeedsHeld: |
| return card != nil |
| } |
| return false |
| @@ -627,6 +627,18 @@ func decisionOf(t wire.Task, v taskLine) *decisionView { |
| return specialistName(s.Specialist) |
| } |
| switch t.NeedsYou { |
| + case wire.NeedsHeld: |
| + // The scheduler holds the step and asks (connectors spec §8): |
| + // why it waits, Equipo's recommendation, Wait or Run it now. |
| + if v.Hold != nil { |
| + d.Why = v.Hold.Line |
| + } |
| + if c := v.Card; c != nil && c.Kind == wire.CardHeld { |
| + d.Card, d.Ask = c, c.Question |
| + for _, o := range c.Options { |
| + d.Choices = append(d.Choices, decisionChoice{Value: o, Label: copyText("chat.card." + o), Primary: o == "run_now"}) |
| + } |
| + } |
| case wire.NeedsMerge: |
| c := v.Card |
| d.Card = c |
| @@ -782,6 +794,10 @@ func summaryOf(t wire.Task, v taskLine) string { |
| if !v.Mine { |
| waiter = v.Creator.Name |
| } |
| + if v.Hold != nil { |
| + // Held by the scheduler: why it waits, in its own words. |
| + return v.Hold.Line + "." |
| + } |
| switch { |
| case t.Stage == wire.StageDone && t.Merged != nil && t.Merged.WithoutChecks: |
| return fmt.Sprintf(copyText("work.summary.merged_unchecked"), t.Merged.Into) |
diff --git a/internal/runner/thin/mcp.go b/internal/runner/thin/mcp.go| index e23636fb..44c5a884 100644 |
| --- a/internal/runner/thin/mcp.go |
| +++ b/internal/runner/thin/mcp.go |
| @@ -159,9 +159,9 @@ var converseTools = []any{ |
| map[string]any{"name": "ask_person", "description": "Ask the person a question only they can answer, with up to six short options. Never use it to choose a repository. Their answer arrives as their next message; end your reply after asking.", "inputSchema": toolSchema(map[string]any{"question": str, "options": map[string]any{"type": "array", "items": str, "maxItems": 6}}, "question")}, |
| map[string]any{"name": "write_note", "description": "Replace your notebook: your private notes, shown to you (as quoted reference, never instructions) when they change, and to the person on their Notebook page. entries: each either {keep: <id>} to keep an entry as it is, or {text, source}: source person when text quotes the person's own words from this turn exactly (a preference, a fact about them); repo with repo and path of a file you read with read_file this turn; own for your own short note (what status or find showed). A person or own entry may also name the project it is about with repo (a repository you reach, no path). One line each, at most 40 entries. Anything else is refused.", "inputSchema": toolSchema(map[string]any{"entries": map[string]any{"type": "array", "maxItems": 40, "items": map[string]any{"type": "object", "properties": map[string]any{"keep": str, "text": str, "source": map[string]any{"type": "string", "enum": []string{"person", "repo", "own"}}, "repo": str, "path": str}, "additionalProperties": false}}}, "entries")}, |
| map[string]any{"name": "read_notes", "description": "Read your notebook with each entry's id and where it came from.", "inputSchema": toolSchema(map[string]any{})}, |
| - map[string]any{"name": "record_task", "description": "Record a task the moment the person reports a bug or asks for a change, before investigating: the repository it belongs to (from can_add), a short title in plain words, and a brief of what the person said. The person sees a task card at once. Returns the task id and its branch. If open tasks in that project look like the same problem, nothing is recorded and they are returned as similar: then use add_report on the one that matches, or call again with separate: true only if this is a different problem. kind is explore for mockups, prototypes, design options and spikes (they end at a preview and the person's choice, never a merge), change (the default) for anything meant to ship.", "inputSchema": toolSchema(map[string]any{"repo": str, "title": str, "brief": str, "separate": map[string]string{"type": "boolean"}, "kind": map[string]any{"type": "string", "enum": []string{"change", "explore"}}}, "repo", "title", "brief")}, |
| + map[string]any{"name": "record_task", "description": "Record a task the moment the person reports a bug or asks for a change, before investigating: the repository it belongs to (from can_add), a short title in plain words, and a brief of what the person said. The person sees a task card at once. Returns the task id and its branch. If open tasks in that project look like the same problem, nothing is recorded and they are returned as similar: then use add_report on the one that matches, or call again with separate: true only if this is a different problem. kind is explore for mockups, prototypes, design options and spikes (they end at a preview and the person's choice, never a merge), change (the default) for anything meant to ship.", "inputSchema": toolSchema(map[string]any{"repo": str, "title": str, "brief": str, "separate": map[string]string{"type": "boolean"}, "kind": map[string]any{"type": "string", "enum": []string{"change", "explore"}}, "priority": priorityArg, "by": byArg}, "repo", "title", "brief")}, |
| map[string]any{"name": "add_finding", "description": "Attach what you found while investigating to a task: a headline, one sentence for the person in plain words with no file paths (for example \"Found it: hiding the navigation bar turned off swipe-back.\"); the finding itself in full; and the repository, file path and line it points at when there is one. The task moves to investigated.", "inputSchema": toolSchema(map[string]any{"task": str, "headline": str, "text": str, "repo": str, "path": str, "line": map[string]string{"type": "integer"}}, "task", "headline", "text")}, |
| - map[string]any{"name": "start_task", "description": "Hand a recorded task to Engineering, who changes the code on the task's own branch and pushes it to Amadan. brief is what to change and why, from your findings. Never merges and never opens a pull request. Call it once per task.", "inputSchema": toolSchema(map[string]any{"task": str, "brief": str}, "task", "brief")}, |
| + map[string]any{"name": "start_task", "description": "Hand a recorded task to Engineering, who changes the code on the task's own branch and pushes it to Amadan. brief is what to change and why, from your findings. Never merges and never opens a pull request. Call it once per task.", "inputSchema": toolSchema(map[string]any{"task": str, "brief": str, "priority": priorityArg, "by": byArg}, "task", "brief")}, |
| map[string]any{"name": "read_task", "description": "Read a task: its stage, findings, steps (state, branch, commit, summary) and the person's notes on it.", "inputSchema": toolSchema(map[string]any{"task": str}, "task")}, |
| map[string]any{"name": "cancel_task", "description": "Cancel a task when the person asks; a running step stops.", "inputSchema": toolSchema(map[string]any{"task": str}, "task")}, |
| map[string]any{"name": "add_report", "description": "Add the person's new report of a problem that is already an open task (from record_task's similar list, or one you know) to that task, instead of recording a duplicate. text is what the person said. The person sees the task card.", "inputSchema": toolSchema(map[string]any{"task": str, "text": str}, "task", "text")}, |
| @@ -272,3 +272,12 @@ func permissionText(raw json.RawMessage, tools bool) string { |
| } |
| return text |
| } |
| + |
| +// priorityArg and byArg are record_task's and start_task's scheduler |
| +// fields (connectors spec §6): set only from what the person said, when |
| +// the task is created; the person alone makes a task urgent or changes |
| +// them later. |
| +var ( |
| + priorityArg = map[string]any{"type": "string", "enum": []string{"low", "normal"}, "description": "low when the person said it can wait, normal otherwise (the default). Never urgent: only the person marks a task urgent."} |
| + byArg = map[string]any{"type": "string", "description": "A deadline the person gave, as a date (2026-11-20) or a time (RFC 3339). Leave it out when they gave none."} |
| +) |
diff --git a/internal/thintest/client.go b/internal/thintest/client.go| index b7f8dfe3..cdc22f27 100644 |
| --- a/internal/thintest/client.go |
| +++ b/internal/thintest/client.go |
| @@ -229,6 +229,16 @@ func (c *Client) RetryTask(ctx context.Context, id string) (out wire.TaskAccepte |
| return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/retry", nil, &out) |
| } |
| +// SetPriority is the task creator's priority and deadline. |
| +func (c *Client) SetPriority(ctx context.Context, id string, in wire.SetPriority) (out wire.Task, err error) { |
| + return out, c.do(ctx, "PUT", "/api/v1/tasks/"+id+"/priority", in, &out) |
| +} |
| + |
| +// RunNow is the task creator's Run it now anyway on a held step. |
| +func (c *Client) RunNow(ctx context.Context, id string, in wire.RunNow) (out wire.RunNowAccepted, err error) { |
| + return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/run-now", in, &out) |
| +} |
| + |
| // RoundTask is Try another round on a task the automatic rounds did not |
| // settle. |
| func (c *Client) RoundTask(ctx context.Context, id string) (out wire.TaskAccepted, err error) { |
diff --git a/internal/thintest/scheduler_contract_test.go b/internal/thintest/scheduler_contract_test.go| new file mode 100644 |
| index 00000000..1056a1dd |
| --- /dev/null |
| +++ b/internal/thintest/scheduler_contract_test.go |
| @@ -0,0 +1,219 @@ |
| +package thintest |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/chat" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// held sends a hold for the task's step and returns the task as read. |
| +func (r *toolRig) hold(key string, d *wire.DispatchCommand, h wire.StepHold) wire.Task { |
| + r.t.Helper() |
| + r.step(key, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, Findings: []wire.Finding{}, Hold: &h}) |
| + k, err := r.client.Task(r.ctx, d.TaskID) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return k |
| +} |
| + |
| +// frames counts the commands of kind the instance wrote for runners. |
| +func (r *toolRig) frames(kind string) int { |
| + r.t.Helper() |
| + var n int |
| + if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE kind=?", kind).Scan(&n); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +// TestContractScheduler (connectors spec S3, §6, §8, §10): the |
| +// coordinator sets low or normal and a deadline only at a task's |
| +// creation, never urgent; the dispatch carries them; a held step is |
| +// shown queued with its hold and, where the creator's input changes the |
| +// outcome, Needs you with Equipo's recommendation; the creator's |
| +// priority change is revision-checked and reaches the runner; Run now is |
| +// the creator's alone, bound to the held step revision, one release per |
| +// revision, and never passes a spending bar. |
| +func TestContractScheduler(t *testing.T) { |
| + r := newToolRigAt(t, wire.ProtocolScheduler) |
| + ctx := r.ctx |
| + by := time.Now().Add(5 * 24 * time.Hour).UTC().Format("2006-01-02") |
| + if res := r.call("p0", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Urgent from the model", "brief": "b", "priority": "urgent"}); !res.IsError { |
| + t.Fatalf("the coordinator set urgent: %+v", res) |
| + } |
| + if res := r.call("p0b", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "A past deadline", "brief": "b", "by": "2020-01-01"}); !res.IsError { |
| + t.Fatalf("a past deadline: %+v", res) |
| + } |
| + id := taskID(t, r.call("p1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Tidy the README", "brief": "When you get to it.", "priority": "low", "by": by})) |
| + k, err := r.client.Task(ctx, id) |
| + if err != nil || k.Priority == nil || k.Priority.Priority != wire.PriorityLow || k.Priority.By == nil || k.Priority.SetBy != wire.PrioritySetByCoordinator { |
| + t.Fatalf("priority %+v %v", k.Priority, err) |
| + } |
| + // start_task cannot change what is set. |
| + if res := r.call("p2", wire.ToolStartTask, map[string]string{"task": id, "brief": "go", "priority": "normal"}); res.IsError { |
| + t.Fatalf("start: %+v", res) |
| + } |
| + _, body := r.expect(wire.FrameDispatch) |
| + d := body.(*wire.DispatchCommand) |
| + if d.Priority != wire.PriorityLow || d.By == nil || !d.By.Equal(*k.Priority.By) || d.Release != "" { |
| + t.Fatalf("dispatch %+v", d) |
| + } |
| + if k, _ = r.client.Task(ctx, id); k.Priority.Priority != wire.PriorityLow { |
| + t.Fatalf("start_task changed the priority: %+v", k.Priority) |
| + } |
| + |
| + // Held for headroom with a reset in time: queued, the hold shown, not |
| + // Needs you. |
| + reset := time.Now().Add(3 * time.Hour).UTC().Truncate(time.Second) |
| + k = r.hold("h1", d, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-a", Provider: "claude", ResetsAt: &reset, WakeAt: &reset, StepRevision: 1}) |
| + if s := k.Steps[len(k.Steps)-1]; s.State != wire.StepQueued || s.Hold == nil || s.Hold.Reason != wire.HoldHeadroom || k.NeedsYou != "" { |
| + t.Fatalf("held: %+v %+v needs %q", s, s.Hold, k.NeedsYou) |
| + } |
| + pages := &toolRig{rig: r.rig} |
| + owner := r.inst.Cookie() |
| + if page := pages.get(owner, "/tasks/"+id, 200); !strings.Contains(page, "Waiting for headroom on Claude, resets") || !strings.Contains(page, "data-task-run-now") || !strings.Contains(page, "Low priority") || !strings.Contains(page, "set from your message") || !strings.Contains(page, "data-task-urgent") { |
| + t.Fatal("the task page lacks the hold, Run it now anyway or the priority") |
| + } |
| + // No reset in sight: Needs you, with Equipo's recommendation. |
| + far := time.Now().Add(80 * time.Hour).UTC().Truncate(time.Second) |
| + k = r.hold("h2", d, wire.StepHold{Reason: wire.HoldHeadroom, Connection: "claude-a", Provider: "claude", ResetsAt: &far, WakeAt: &far, NeedsPerson: wire.HoldNeedsNoReset, StepRevision: 1}) |
| + if k.NeedsYou != wire.NeedsHeld { |
| + t.Fatalf("needs %q", k.NeedsYou) |
| + } |
| + shape(t, "api/task-held.json", k) |
| + var card wire.Card |
| + snap, err := r.client.Snapshot(ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, c := range snap.Cards { |
| + if c.Kind == wire.CardHeld && c.TaskID == id && c.State == wire.CardOpen { |
| + card = c |
| + } |
| + } |
| + if card.ID == "" || !strings.Contains(card.Question, "Claude") || len(card.Options) != 2 || card.Options[1] != chat.ChoiceRunNow { |
| + t.Fatalf("held card %+v", card) |
| + } |
| + shape(t, "api/card-held.json", card) |
| + |
| + // The creator's priority: revision-checked, the creator's alone, sent |
| + // to the runner holding the step. |
| + pages.memberCookie() |
| + const Member = "member@example.com" |
| + if _, err := r.client.SetPriority(ctx, id, wire.SetPriority{Priority: wire.PriorityUrgent, Revision: k.Revision - 1}); Status(err) != 409 { |
| + t.Fatalf("a stale revision: %v", err) |
| + } |
| + if _, err := r.client.SetPriority(ctx, id, wire.SetPriority{Priority: "high", Revision: k.Revision}); Status(err) != 422 && Status(err) != 400 { |
| + t.Fatalf("an unknown priority: %v", err) |
| + } |
| + if _, err := r.inst.Store.Chat().SetPriority(ctx, Member, id, wire.SetPriority{Priority: wire.PriorityUrgent, Revision: k.Revision}); err == nil { |
| + t.Fatalf("a teammate's priority: %v", err) |
| + } |
| + // Another owner is not the task's creator. |
| + if err := r.inst.Store.SetMember(ctx, equipo.Actor{Address: Owner}, "second@example.com", equipo.RoleOwner, true, 0); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := r.inst.Store.Chat().SetPriority(ctx, "second@example.com", id, wire.SetPriority{Priority: wire.PriorityUrgent, Revision: k.Revision}); err == nil { |
| + t.Fatal("another owner set the creator's priority") |
| + } |
| + if _, err := r.inst.Store.Chat().RunNow(ctx, "second@example.com", id, wire.RunNow{Step: d.StepID, StepRevision: 1}); err == nil { |
| + t.Fatal("another owner's Run now") |
| + } |
| + k, err = r.client.SetPriority(ctx, id, wire.SetPriority{Priority: wire.PriorityUrgent, Revision: k.Revision}) |
| + if err != nil || k.Priority.Priority != wire.PriorityUrgent || k.Priority.SetBy != wire.PrioritySetByPerson || k.Priority.By != nil { |
| + t.Fatalf("set: %+v %v", k.Priority, err) |
| + } |
| + _, body = r.expect(wire.FramePriority) |
| + shape(t, "frames/priority.json", r.runner.Received[len(r.runner.Received)-1]) |
| + if p := body.(*wire.PriorityCommand); p.TaskID != id || p.Priority != wire.PriorityUrgent || p.Revision != k.Revision || p.Person != Owner { |
| + t.Fatalf("priority frame %+v", p) |
| + } |
| + |
| + // Run now: the creator's alone, bound to the held revision, one |
| + // release per revision. |
| + if _, err := r.inst.Store.Chat().RunNow(ctx, Member, id, wire.RunNow{Step: d.StepID, StepRevision: 1}); err == nil { |
| + t.Fatalf("a teammate's Run now: %v", err) |
| + } |
| + if _, err := r.client.RunNow(ctx, id, wire.RunNow{Step: d.StepID, StepRevision: 2}); Status(err) != 409 { |
| + t.Fatalf("a stale step revision: %v", err) |
| + } |
| + rel, err := r.client.RunNow(ctx, id, wire.RunNow{Step: d.StepID, StepRevision: 1}) |
| + if err != nil || rel.Release == "" { |
| + t.Fatalf("run now %+v %v", rel, err) |
| + } |
| + _, body = r.expect(wire.FrameRelease) |
| + shape(t, "frames/release.json", r.runner.Received[len(r.runner.Received)-1]) |
| + if c := body.(*wire.ReleaseCommand); c.ID != rel.Release || c.StepID != d.StepID || c.StepRevision != 1 || c.TaskID != id || c.Person != Owner { |
| + t.Fatalf("release %+v", c) |
| + } |
| + if again, err := r.client.RunNow(ctx, id, wire.RunNow{Step: d.StepID, StepRevision: 1}); err != nil || again.Release != rel.Release { |
| + t.Fatalf("a second tap: %+v %v", again, err) |
| + } |
| + if n := r.frames(wire.FrameRelease); n != 1 { |
| + t.Fatalf("%d releases written", n) |
| + } |
| + // The card was answered by the tap. |
| + snap, _ = r.client.Snapshot(ctx) |
| + for _, c := range snap.Cards { |
| + if c.ID == card.ID && c.State == wire.CardOpen { |
| + t.Fatal("the held card stayed open after Run now") |
| + } |
| + } |
| + // Admitted: a report without the hold starts the step and ends Needs |
| + // you. |
| + r.step("s1", wire.StepReport{TaskID: id, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, Findings: []wire.Finding{}}) |
| + if k, _ = r.client.Task(ctx, id); k.Steps[len(k.Steps)-1].State != wire.StepRunning || k.Steps[len(k.Steps)-1].Hold != nil || k.NeedsYou != "" { |
| + t.Fatalf("started: %+v needs %q", k.Steps[len(k.Steps)-1], k.NeedsYou) |
| + } |
| + |
| + // A spending bar: Run now never passes it; the card offers Wait only. |
| + other := taskID(t, r.call("q1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Another one", "brief": "b"})) |
| + r.call("q2", wire.ToolStartTask, map[string]string{"task": other, "brief": "go"}) |
| + _, body = r.expect(wire.FrameDispatch) |
| + d2 := body.(*wire.DispatchCommand) |
| + r.hold("h3", d2, wire.StepHold{Reason: wire.HoldSpendUnknown, Connection: "tensorx-1", Provider: "tensorx", NeedsPerson: wire.HoldNeedsNoReset, StepRevision: 1}) |
| + if _, err := r.client.RunNow(ctx, other, wire.RunNow{Step: d2.StepID, StepRevision: 1}); Status(err) != 409 { |
| + t.Fatalf("Run now past spend unknown: %v", err) |
| + } |
| + if page := pages.get(owner, "/tasks/"+other, 200); !strings.Contains(page, "data-task-resume") || strings.Contains(page, "data-task-run-now") { |
| + t.Fatal("spend unknown offers Run now, or no Resume") |
| + } |
| +} |
| + |
| +// An older runner (before the scheduler's protocol) is refused Run now |
| +// and a preference with an end, never handed one; a newer one gets the |
| +// preference with its end, and once it passes it reads Automatic. |
| +func TestContractSchedulerOlderRunner(t *testing.T) { |
| + old := newToolRigAt(t, wire.ProtocolResearch) |
| + id := taskID(t, old.call("o1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Old runner", "brief": "b"})) |
| + old.call("o2", wire.ToolStartTask, map[string]string{"task": id, "brief": "go"}) |
| + _, body := old.expect(wire.FrameDispatch) |
| + d := body.(*wire.DispatchCommand) |
| + old.hold("o3", d, wire.StepHold{Reason: wire.HoldNoConnection, NeedsPerson: wire.HoldNeedsNoConnection, StepRevision: 1}) |
| + if _, err := old.client.RunNow(old.ctx, id, wire.RunNow{Step: d.StepID, StepRevision: 1}); Status(err) != 409 { |
| + t.Fatalf("Run now on a protocol 13 runner: %v", err) |
| + } |
| + if n := old.frames(wire.FrameRelease); n != 0 { |
| + t.Fatalf("%d releases for a protocol 13 runner", n) |
| + } |
| + until := time.Now().Add(time.Hour) |
| + if _, err := old.client.SetPreferences(old.ctx, wire.Preferences{Provider: "codex", Until: &until}); Status(err) != 409 { |
| + t.Fatalf("a preference with an end on a protocol 13 runner: %v", err) |
| + } |
| + |
| + r := newToolRigAt(t, wire.ProtocolScheduler) |
| + p, err := r.client.SetPreferences(r.ctx, wire.Preferences{Provider: "codex", Until: &until}) |
| + if err != nil || p.Until == nil || p.Provider != "codex" { |
| + t.Fatalf("preference %+v %v", p, err) |
| + } |
| + _, body = r.expect(wire.FramePreference) |
| + shape(t, "frames/preference-until.json", r.runner.Received[len(r.runner.Received)-1]) |
| + if c := body.(*wire.PreferenceCommand); c.Until == nil || c.Provider != "codex" { |
| + t.Fatalf("preference frame %+v", c) |
| + } |
| +} |
diff --git a/internal/wire/runners.go b/internal/wire/runners.go| index 0454c2d1..50984525 100644 |
| --- a/internal/wire/runners.go |
| +++ b/internal/wire/runners.go |
| @@ -600,10 +600,34 @@ var schedulerOnly = map[string]bool{FrameRelease: true, FramePriority: true} |
| // runner runs every step as before and never spends). It reports whether |
| // anything changed. |
| func downgradeScheduler(body any) bool { |
| - if d, ok := body.(*DispatchCommand); ok { |
| - set := d.Priority != "" || d.By != nil || d.Release != "" |
| - d.Priority, d.By, d.Release = "", nil, "" |
| + switch v := body.(type) { |
| + case *DispatchCommand: |
| + set := v.Priority != "" || v.By != nil || v.Release != "" |
| + v.Priority, v.By, v.Release = "", nil, "" |
| return set |
| + case *ToolCall: |
| + // record_task's and start_task's priority and deadline: an older |
| + // instance decodes their arguments strictly. |
| + if v.Name != ToolRecordTask && v.Name != ToolStartTask { |
| + return false |
| + } |
| + var args map[string]json.RawMessage |
| + if json.Unmarshal(v.Args, &args) != nil { |
| + return false |
| + } |
| + _, p := args["priority"] |
| + _, b := args["by"] |
| + if !p && !b { |
| + return false |
| + } |
| + delete(args, "priority") |
| + delete(args, "by") |
| + raw, err := json.Marshal(args) |
| + if err != nil { |
| + return false |
| + } |
| + v.Args = raw |
| + return true |
| } |
| return false |
| } |
diff --git a/internal/wire/schedule_test.go b/internal/wire/schedule_test.go| index 98eb3df2..9335a048 100644 |
| --- a/internal/wire/schedule_test.go |
| +++ b/internal/wire/schedule_test.go |
| @@ -67,6 +67,19 @@ func TestEncodeBelowProtocol14DropsScheduler(t *testing.T) { |
| } |
| } |
| +// record_task's priority and deadline never reach an older instance |
| +// (it decodes the arguments strictly); at 14 they go out whole. |
| +func TestEncodeBelowProtocol14DropsToolPriority(t *testing.T) { |
| + call, _ := wire.NewFrame("t", wire.FrameToolCall, wire.ToolCall{CallID: "c", TurnID: "t", Attempt: 1, Name: wire.ToolRecordTask, Args: json.RawMessage(`{"brief":"b","by":"2026-11-20","priority":"low","repo":"r","title":"x"}`)}) |
| + if same, err := wire.Encode(call, wire.Protocol14); err != nil || !bytes.Equal(same.Data, call.Data) { |
| + t.Fatalf("changed at 14: %v", err) |
| + } |
| + got, err := wire.Encode(call, wire.Protocol13) |
| + if err != nil || strings.Contains(string(got.Data), "priority") || strings.Contains(string(got.Data), `\"by\"`) || !strings.Contains(string(got.Data), "brief") { |
| + t.Fatalf("at 13: %v %s", err, got.Data) |
| + } |
| +} |
| + |
| // The scheduler's frames are durable and decode strictly. |
| func TestSchedulerFramesStrict(t *testing.T) { |
| for _, kind := range []string{wire.FrameRelease, wire.FramePriority} { |
diff --git a/internal/wire/wiretest/testdata/api/card-held.json b/internal/wire/wiretest/testdata/api/card-held.json| index 40e48a2b..33122d7b 100644 |
| --- a/internal/wire/wiretest/testdata/api/card-held.json |
| +++ b/internal/wire/wiretest/testdata/api/card-held.json |
| @@ -1 +1 @@ |
| -{"id":"c_0002","revision":1,"kind":"held","state":"open","turn_id":"","project_id":"p_0001","name":"Swipe back on iOS","question":"I’d wait: Claude resets Thu 10:00, before Friday.","options":["wait","run_now"],"choice":"","task_id":"tk0001","created_at":"2026-11-06T10:00:00Z","updated_at":"2026-11-06T10:00:00Z"} |
| +{"id":"c_0002","revision":1,"kind":"held","state":"open","turn_id":"","project_id":"p_0001","name":"Swipe back on iOS","question":"I’d wait: Claude resets Thu 10:00, before Friday.","options":["wait_reset","run_now"],"choice":"","task_id":"tk0001","created_at":"2026-11-06T10:00:00Z","updated_at":"2026-11-06T10:00:00Z"} |
diff --git a/internal/wire/wiretest/testdata/api/task-held.json b/internal/wire/wiretest/testdata/api/task-held.json| index a046469b..3ce8c5e2 100644 |
| --- a/internal/wire/wiretest/testdata/api/task-held.json |
| +++ b/internal/wire/wiretest/testdata/api/task-held.json |
| @@ -1 +1 @@ |
| -{"id":"tk0001","revision":5,"project_id":"p_0001","project":"Sample","repo":"amadan.net/oficina/sample","title":"Swipe back from the edge does nothing","brief":"Swiping from the left edge should go back a pane.","stage":"in_progress","branch":"equipo/tk0001-swipe-back-from-the-edge-does-nothing","base_sha":"1111111111111111111111111111111111111111","url":"https://amadan.net/oficina/sample?branch=equipo/tk0001-swipe-back-from-the-edge-does-nothing","creator":"owner@example.com","turn_id":"t_0001","findings":[{"id":"f_0001","headline":"Found it: the edge swipe never reaches the back handler.","text":"The edge-swipe handler returns false, so back never fires.","repo":"amadan.net/oficina/sample","path":"panes/swipe.go","line":4,"at":"2026-11-07T10:00:02Z"}],"steps":[{"id":"s_0001","revision":3,"task_id":"tk0001","index":1,"specialist":"engineering","state":"done","reason":"","attempt":1,"base_sha":"1111111111111111111111111111111111111111","candidate_sha":"2222222222222222222222222222222222222222","pushed":true,"terminated":true,"summary":"EdgeSwipe now goes back on a swipe from the edge.","headline":"Fixed swipe-back from the edge.","log_tail":"Edit panes/swipe.go\nDone.","started_at":"2026-11-07T10:00:03Z","finished_at":"2026-11-07T10:01:40Z","round":0,"family":"claude","account":"claude-a","verdict":"","review_label":"","findings":[],"checks":"","gate":"","exit_code":null,"askable":true,"rebase":false,"merge_sha":"","into":"","strategy":"","without_checks":false,"switched":null,"activity":[{"kind":"read","subject":"panes/swipe.go","at":"2026-11-07T10:00:20Z"},{"kind":"edit","subject":"panes/swipe.go","at":"2026-11-07T10:01:02Z"},{"kind":"run","subject":"go test ./panes","at":"2026-11-07T10:01:20Z"}],"runner_id":"RUNNER1","runner_label":"","needs":[],"placement":"","publication":"","termination_kind":"namespace"},{"id":"s_0001","revision":3,"task_id":"tk0001","index":1,"specialist":"engineering","state":"queued","reason":"","attempt":1,"base_sha":"1111111111111111111111111111111111111111","candidate_sha":"2222222222222222222222222222222222222222","pushed":true,"terminated":true,"summary":"EdgeSwipe now goes back on a swipe from the edge.","headline":"Fixed swipe-back from the edge.","log_tail":"Edit panes/swipe.go\nDone.","started_at":"2026-11-07T10:00:03Z","finished_at":"2026-11-07T10:01:40Z","round":0,"family":"claude","account":"claude-a","verdict":"","review_label":"","findings":[],"checks":"","gate":"","exit_code":null,"askable":true,"rebase":false,"merge_sha":"","into":"","strategy":"","without_checks":false,"switched":null,"activity":[{"kind":"read","subject":"panes/swipe.go","at":"2026-11-07T10:00:20Z"},{"kind":"edit","subject":"panes/swipe.go","at":"2026-11-07T10:01:02Z"},{"kind":"run","subject":"go test ./panes","at":"2026-11-07T10:01:20Z"}],"runner_id":"RUNNER1","runner_label":"","needs":[],"placement":"","publication":"","termination_kind":"namespace","hold":{"reason":"headroom","connection":"claude-a","provider":"claude","resets_at":"2026-11-13T10:00:00Z","wake_at":"2026-11-13T10:00:00Z","step_revision":1}}],"thread":[{"id":"e_0001","author":"owner@example.com","text":"It happens on the iPhone only.","at":"2026-11-07T10:00:30Z"}],"created_at":"2026-11-07T10:00:01Z","updated_at":"2026-11-07T10:01:40Z","candidate_sha":"2222222222222222222222222222222222222222","checks":"","checks_reason":"","verdict":"","review_label":"","needs_you":"held","fix_rounds":0,"branch_head":"","questions":[{"id":"q_0001","revision":3,"task_id":"tk0001","step_id":"s_0001","specialist":"engineering","asker":"owner@example.com","text":"What did you change and why?","state":"answered","reason":"","attempt":1,"answer":"I made the edge swipe return true, so a swipe from the left edge goes back a pane. Before, the handler always said no.","created_at":"2026-11-07T10:05:00Z","updated_at":"2026-11-07T10:05:09Z","timing":null}],"merged":null,"reports":0,"ask_open":false,"merge_offered":false,"creator_name":"Owner","source_message_id":"m_0001","source_at":"2026-11-07T09:59:58Z","duplicate_of":null,"coordinator":null,"folded":null,"combined":null,"engineering_runner":"RUNNER1","priority":{"priority":"low","by":"2026-11-20T17:00:00Z","set_by":"coordinator"}} |
| +{"id":"tk0001","revision":5,"project_id":"p_0001","project":"Sample","repo":"amadan.net/oficina/sample","title":"Swipe back from the edge does nothing","brief":"Swiping from the left edge should go back a pane.","stage":"in_progress","branch":"equipo/tk0001-swipe-back-from-the-edge-does-nothing","base_sha":"1111111111111111111111111111111111111111","url":"https://amadan.net/oficina/sample?branch=equipo/tk0001-swipe-back-from-the-edge-does-nothing","creator":"owner@example.com","turn_id":"t_0001","findings":[{"id":"f_0001","headline":"Found it: the edge swipe never reaches the back handler.","text":"The edge-swipe handler returns false, so back never fires.","repo":"amadan.net/oficina/sample","path":"panes/swipe.go","line":4,"at":"2026-11-07T10:00:02Z"}],"steps":[{"id":"s_0001","revision":3,"task_id":"tk0001","index":1,"specialist":"engineering","state":"queued","reason":"","attempt":1,"base_sha":"1111111111111111111111111111111111111111","candidate_sha":"2222222222222222222222222222222222222222","pushed":true,"terminated":true,"summary":"EdgeSwipe now goes back on a swipe from the edge.","headline":"Fixed swipe-back from the edge.","log_tail":"Edit panes/swipe.go\nDone.","started_at":"2026-11-07T10:00:03Z","finished_at":"2026-11-07T10:01:40Z","round":0,"family":"claude","account":"claude-a","verdict":"","review_label":"","findings":[],"checks":"","gate":"","exit_code":null,"askable":true,"rebase":false,"merge_sha":"","into":"","strategy":"","without_checks":false,"switched":null,"activity":[{"kind":"read","subject":"panes/swipe.go","at":"2026-11-07T10:00:20Z"},{"kind":"edit","subject":"panes/swipe.go","at":"2026-11-07T10:01:02Z"},{"kind":"run","subject":"go test ./panes","at":"2026-11-07T10:01:20Z"}],"runner_id":"RUNNER1","runner_label":"","needs":[],"placement":"","publication":"","termination_kind":"namespace","hold":{"reason":"headroom","connection":"claude-a","provider":"claude","resets_at":"2026-11-16T10:00:00Z","wake_at":"2026-11-16T10:00:00Z","needs_person":"no_reset","step_revision":1}}],"thread":[{"id":"e_0001","author":"owner@example.com","text":"It happens on the iPhone only.","at":"2026-11-07T10:00:30Z"}],"created_at":"2026-11-07T10:00:01Z","updated_at":"2026-11-07T10:01:40Z","candidate_sha":"2222222222222222222222222222222222222222","checks":"","checks_reason":"","verdict":"","review_label":"","needs_you":"held","fix_rounds":0,"branch_head":"","questions":[{"id":"q_0001","revision":3,"task_id":"tk0001","step_id":"s_0001","specialist":"engineering","asker":"owner@example.com","text":"What did you change and why?","state":"answered","reason":"","attempt":1,"answer":"I made the edge swipe return true, so a swipe from the left edge goes back a pane. Before, the handler always said no.","created_at":"2026-11-07T10:05:00Z","updated_at":"2026-11-07T10:05:09Z","timing":null}],"merged":null,"reports":0,"ask_open":false,"merge_offered":false,"creator_name":"Owner","source_message_id":"m_0001","source_at":"2026-11-07T09:59:58Z","duplicate_of":null,"coordinator":null,"folded":null,"combined":null,"engineering_runner":"RUNNER1","priority":{"priority":"low","by":"2026-11-20T17:00:00Z","set_by":"coordinator"}} |