oficina / equipo Public

Runner destinations: migration 0047, roles, scoped mailbox, protocol 2

Migration 0047 adds runners.role, runner_commands.runner_id and
chat_steps.runner_id (indexed), backfilled in one transaction with each
person's primary (every runner primary, every command and step in every
state bound), plus the placement, transfer and publication columns
slice B uses. Pending, ack, step reports and syncSteps are per runner;
turns and questions stay primary-only. A person's first enrolment is
the primary, later ones workers. hello and welcome negotiate the
protocol; every frame is encoded per connection; a newer runner falls
back to protocol 1 once on a refused hello, a worker never does, and a
worker refuses to enrol with an instance without workers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 0d29c31655c8f9326e759dc5d3f9967f5953b9b8 parent 91c535a
28 files changed, +1,184 −84
  • internal/equipo/app.go +6 −0
  • internal/equipo/chat/models.go +33 −2
  • internal/equipo/chat/review.go +1 −1
  • internal/equipo/chat/runner.go +37 −19
  • internal/equipo/chat/runners.go +64 −0
  • internal/equipo/chat/store.go +21 −1
  • internal/equipo/chat/stream.go +19 −1
  • internal/equipo/chat/tasks.go +43 −18
  • internal/equipo/chat_wiring.go +19 −2
  • internal/equipo/migrations/0047_thin_runners.sql +30 −0
  • internal/equipo/migrations/schema.sql +10 −5
  • internal/equipo/migrations_runners_test.go +122 −0
  • internal/equipo/setup/enrolment.go +10 −0
  • internal/equipo/setup/runner_models.go +8 −0
  • internal/runner/config.go +5 −1
  • internal/runner/diagnostics.go +2 −0
  • internal/runner/enrol.go +39 −0
  • internal/runner/enrol_worker_test.go +63 −0
  • internal/runner/thin/capabilities.go +81 −0
  • internal/runner/thin/contract_test.go +13 −0
  • internal/runner/thin/link.go +127 −25
  • internal/runner/thin/protocol_test.go +132 −0
  • internal/runner/thin/run.go +9 −2
  • internal/thintest/fakerunner.go +15 −2
  • internal/thintest/instance_contract_test.go +4 −4
  • internal/thintest/migration_contract_test.go +102 −0
  • internal/thintest/runners_contract_test.go +156 −0
  • internal/wire/runners.go +13 −1

CI failed — run details

diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index d18ecbc5..36b13290 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -3,6 +3,7 @@ package equipo
import (
"amadan.net/oficina/equipo/internal/equipo/notifications"
"context"
+ "encoding/json"
"errors"
"log/slog"
"net/http"
@@ -168,6 +169,11 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
a.Post("/api/enrolments/token", a.exchangeEnrolment)
a.Mount("/api/runner/v2", runner)
a.Get(wire.StreamPath, a.store.RunnerStreamHandler().ServeHTTP)
+ a.Get(wire.RunnerProtocolPath, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Cache-Control", "no-store")
+ _ = json.NewEncoder(w).Encode(wire.RunnerProtocol{Protocol: wire.ProtocolCurrent})
+ })
a.Get("/signin", a.store.sessionHandler(a.auth).Signin)
a.Post("/auth/begin", a.auth.Begin)
a.Get("/auth/callback", a.rememberSignIn(a.auth.Callback))
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index 4f410749..a88455bc 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{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &questionRecord{}}
+var Models = []any{&turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &questionRecord{}, &transferRecord{}}
type turnRecord struct {
ID string `gorm:"primaryKey"`
@@ -62,7 +62,9 @@ type eventRecord struct {
func (eventRecord) TableName() string { return "chat_events" }
// commandRecord is the instance side of the runner mailbox. A command is
-// delivered to the person's primary runner until acked.
+// delivered to its runner (RunnerID) until that runner acks it: the
+// person's primary for conversation, merge and publication commands, the
+// step's runner for its dispatch and cancel.
type commandRecord struct {
Seq int64 `gorm:"primaryKey"`
Person string `gorm:"index:runner_command_person"`
@@ -70,6 +72,7 @@ type commandRecord struct {
Body string
CreatedAt time.Time
AckedAt *time.Time
+ RunnerID string `gorm:"index:runner_command_runner"`
}
func (commandRecord) TableName() string { return "runner_commands" }
@@ -93,6 +96,8 @@ type runnerSessionRecord struct {
Revision int64
Hello string
SeenAt time.Time
+ // Protocol is what this connection speaks (wire.Spoken).
+ Protocol int
}
func (runnerSessionRecord) TableName() string { return "runner_sessions" }
@@ -109,3 +114,29 @@ type coordinatorRecord struct {
}
func (coordinatorRecord) TableName() string { return "chat_coordinators" }
+
+// transferRecord authorises the chunks of one pack between two runners of
+// a person, for one attempt of one step (Mac runners spec §2). Chunks
+// travel as blob commands to ToRunner; Received and Bytes bound them.
+type transferRecord struct {
+ ID string `gorm:"primaryKey"`
+ Person string
+ FromRunner string
+ ToRunner string
+ Repo string
+ TaskID string
+ StepID string `gorm:"index:runner_transfer_step"`
+ Attempt int64
+ BaseSHA string
+ CandidateSHA string
+ Direction string
+ State string
+ SHA256 string
+ Total int
+ Received int
+ Bytes int64
+ ExpiresAt time.Time
+ CreatedAt time.Time
+}
+
+func (transferRecord) TableName() string { return "runner_transfers" }
diff --git a/internal/equipo/chat/review.go b/internal/equipo/chat/review.go
index bed569a4..9e7f59c1 100644
--- a/internal/equipo/chat/review.go
+++ b/internal/equipo/chat/review.go
@@ -210,7 +210,7 @@ func (t *txn) nextStep(k *taskRecord, steps []stepRecord, s stepRecord) error {
if err := t.db.Create(&s).Error; err != nil {
return err
}
- if err := t.dispatchStep(*k, s); err != nil {
+ if err := t.dispatchStep(*k, &s); err != nil {
return err
}
return t.saveStep(&s, k)
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index 1fc4e479..436ca837 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -11,11 +11,14 @@ import (
"gorm.io/gorm"
)
-// Lease is one runner connection's hold on its generation.
+// Lease is one runner connection's hold on its generation. Protocol is
+// what the connection speaks; Role the runner's role.
type Lease struct {
Runner RunnerPrincipal
Generation int64
Process string
+ Protocol int
+ Role string
}
// Connect grants a generation. A hello with generation 0 is a new runner
@@ -24,12 +27,22 @@ type Lease struct {
func (s *Store) Connect(ctx context.Context, p RunnerPrincipal, process string, hello wire.Hello) (Lease, error) {
// The lease names this one connection, so a replaced connection of the
// same generation (another instance process, a reconnect) is fenced.
- lease := Lease{Runner: p, Process: process + "/" + newID("c")}
- raw, _ := json.Marshal(hello)
+ lease := Lease{Runner: p, Process: process + "/" + newID("c"), Protocol: wire.Spoken(wire.HelloProtocol(hello))}
+ raw, _ := json.Marshal(cleanHello(hello))
err := s.tx(ctx, func(t *txn) error {
if err := s.authority.CurrentRunner(t.db, p); err != nil {
return err
}
+ role, rerr := t.s.authority.RunnerRole(t.db, p.RunnerID)
+ if rerr != nil {
+ return rerr
+ }
+ lease.Role = role
+ // A protocol 1 runner is always a primary: a worker that cannot say
+ // what it is never connects.
+ if role == wire.RoleWorker && lease.Protocol < wire.Protocol2 {
+ return ErrForbidden
+ }
var r runnerSessionRecord
err := t.db.Where("runner_id = ?", p.RunnerID).First(&r).Error
fresh := errors.Is(err, gorm.ErrRecordNotFound)
@@ -44,7 +57,7 @@ func (s *Store) Connect(ctx context.Context, p RunnerPrincipal, process string,
default:
lease.Generation = max(r.Generation, hello.Generation) + 1
}
- r = runnerSessionRecord{RunnerID: p.RunnerID, Generation: lease.Generation, Connected: true, Process: lease.Process, Revision: r.Revision + 1, Hello: string(raw), SeenAt: t.now()}
+ r = runnerSessionRecord{RunnerID: p.RunnerID, Generation: lease.Generation, Connected: true, Process: lease.Process, Revision: r.Revision + 1, Hello: string(raw), SeenAt: t.now(), Protocol: lease.Protocol}
if fresh {
err = t.db.Create(&r).Error
} else {
@@ -53,6 +66,11 @@ func (s *Store) Connect(ctx context.Context, p RunnerPrincipal, process string,
if err != nil {
return err
}
+ if role == wire.RolePrimary {
+ if err := t.rebind(p); err != nil {
+ return err
+ }
+ }
return t.runnerEvent(p.Person, r)
})
return lease, err
@@ -91,7 +109,7 @@ func (s *Store) Confirm(ctx context.Context, l Lease) error {
// Heartbeat records a repeated hello.
func (s *Store) Heartbeat(ctx context.Context, l Lease, hello wire.Hello) error {
- raw, _ := json.Marshal(hello)
+ raw, _ := json.Marshal(cleanHello(hello))
return s.tx(ctx, func(t *txn) error {
r, err := t.current(l)
if err != nil {
@@ -138,8 +156,9 @@ func (s *Store) Disconnect(ctx context.Context, l Lease) error {
})
}
-// Pending returns unacked commands for the lease's person after seq, if
-// this runner is the person's primary runner.
+// Pending returns the unacked commands addressed to this lease's runner
+// after seq, and only those: a worker never sees the primary's work, nor
+// the primary a worker's.
func (s *Store) Pending(ctx context.Context, l Lease, after int64) (out []wire.Frame, last int64, err error) {
last = after
err = s.read(ctx, func(tx *gorm.DB) error {
@@ -150,12 +169,8 @@ func (s *Store) Pending(ctx context.Context, l Lease, after int64) (out []wire.F
if session.Generation != l.Generation || session.Process != l.Process {
return ErrSuperseded
}
- primary, err := s.authority.PrimaryRunner(tx, l.Runner.Person)
- if err != nil || primary != l.Runner.RunnerID {
- return err
- }
var rows []commandRecord
- if err = tx.Where("person = ? AND acked_at IS NULL AND seq > ?", l.Runner.Person, after).Order("seq").Limit(100).Find(&rows).Error; err != nil {
+ if err := tx.Where("runner_id = ? AND person = ? AND acked_at IS NULL AND seq > ?", l.Runner.RunnerID, l.Runner.Person, after).Order("seq").Limit(100).Find(&rows).Error; err != nil {
return err
}
for _, r := range rows {
@@ -247,8 +262,10 @@ func (t *txn) ack(l Lease, id string) error {
if !ok {
return ErrInvalid
}
+ // Only the runner a command was addressed to may ack it (Apply has
+ // checked this connection holds its generation and process).
var c commandRecord
- if err := t.db.Where("person = ? AND acked_at IS NULL AND seq = ?", l.Runner.Person, seq).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ if err := t.db.Where("runner_id = ? AND person = ? AND acked_at IS NULL AND seq = ?", l.Runner.RunnerID, l.Runner.Person, seq).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) {
return nil
} else if err != nil {
return err
@@ -378,13 +395,14 @@ func (t *txn) report(l Lease, v *wire.TurnReport) error {
// sync reconciles after a reconnect: a turn the instance thinks is running
// that the runner no longer holds has failed visibly.
func (t *txn) sync(l Lease, v *wire.Sync) error {
- // Only the person's primary runner holds their turns; another of their
- // runners must not fail the primary's work.
- primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person)
- if err != nil || primary != l.Runner.RunnerID {
+ // Each runner settles only its own steps.
+ if err := t.syncSteps(l, v.Steps); err != nil {
return err
}
- if err := t.syncSteps(l, v.Steps); err != nil {
+ // Only the person's primary runner holds their turns and questions;
+ // another of their runners must not fail the primary's work.
+ primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person)
+ if err != nil || primary != l.Runner.RunnerID {
return err
}
if err := t.syncQuestions(l, v.Asks); err != nil {
@@ -406,7 +424,7 @@ func (t *txn) sync(l Lease, v *wire.Sync) error {
continue
}
var unacked int64
- if err := t.db.Model(&commandRecord{}).Where("person = ? AND kind = ? AND acked_at IS NULL", r.Person, wire.FrameMessage).Count(&unacked).Error; err != nil {
+ if err := t.db.Model(&commandRecord{}).Where("runner_id = ? AND person = ? AND kind = ? AND acked_at IS NULL", l.Runner.RunnerID, r.Person, wire.FrameMessage).Count(&unacked).Error; err != nil {
return err
}
if unacked != 0 {
diff --git a/internal/equipo/chat/runners.go b/internal/equipo/chat/runners.go
new file mode 100644
index 00000000..0eb5991b
--- /dev/null
+++ b/internal/equipo/chat/runners.go
@@ -0,0 +1,64 @@
+package chat
+
+import (
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// Several runners per person (Mac runners spec §1). Every mailbox command
+// and every step attempt names the runner it belongs to: Pending serves a
+// connection only its own commands, an ack counts only from that runner,
+// a step report only from the step's runner, and a sync settles only the
+// syncing runner's steps.
+
+// UnboundSteps counts steps the runner binding missed: no runner, not
+// waiting for one, while the person has a runner. It is the schema check
+// after migration 0047; anything but zero is a bug.
+func UnboundSteps(tx *gorm.DB) (int64, error) {
+ var n int64
+ err := tx.Raw(`SELECT count(*) FROM chat_steps s WHERE coalesce(s.runner_id, '') = ''
+ AND coalesce(s.placement, '') <> 'waiting_runner'
+ AND EXISTS (SELECT 1 FROM runners r WHERE r.person = s.person)`).Scan(&n).Error
+ return n, err
+}
+
+// orphanedBy selects a person's revoked primaries: what was theirs is the
+// current primary's.
+const orphanedBy = `SELECT id FROM runners WHERE person = ? AND revoked_at IS NOT NULL AND coalesce(role, '') IN ('primary', '')`
+
+// rebind gives the person's primary what no runner holds: commands
+// written while the person had no primary, and the unacked commands and
+// unfinished steps of a revoked primary. A worker's are re-placed instead.
+func (t *txn) rebind(p RunnerPrincipal) error {
+ if primary, err := t.s.authority.PrimaryRunner(t.db, p.Person); err != nil || primary != p.RunnerID {
+ return err
+ }
+ if err := t.db.Exec(`UPDATE runner_commands SET runner_id = ? WHERE person = ? AND acked_at IS NULL
+ AND (coalesce(runner_id, '') = '' OR runner_id IN (`+orphanedBy+`))`, p.RunnerID, p.Person, p.Person).Error; err != nil {
+ return err
+ }
+ return t.db.Exec(`UPDATE chat_steps SET runner_id = ? WHERE person = ? AND state IN (?, ?)
+ AND runner_id IN (`+orphanedBy+`)`, p.RunnerID, p.Person, wire.StepQueued, wire.StepRunning, p.Person).Error
+}
+
+// MaxRunnerLabel bounds the machine label a runner reports.
+const MaxRunnerLabel = 80
+
+// cleanHello keeps what the instance stores of a hello within bounds: a
+// capability report out of bounds is dropped (the runner is treated as
+// able to do nothing special), the label is one short line.
+func cleanHello(h wire.Hello) wire.Hello {
+ if h.Capabilities != nil && wire.ValidCapabilities(*h.Capabilities) != nil {
+ h.Capabilities = nil
+ }
+ label, _ := cleanText(strings.ReplaceAll(h.Label, "\n", " "), MaxRunnerLabel)
+ h.Label = label
+ switch h.Sandbox {
+ case "", wire.SandboxBubblewrap, wire.SandboxSeatbelt, wire.SandboxNone:
+ default:
+ h.Sandbox = ""
+ }
+ return h
+}
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index 187334e4..fe19e710 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -26,6 +26,10 @@ var (
ErrExpired = errors.New("chat: cursor expired")
ErrSuperseded = errors.New("chat: runner generation superseded")
ErrUnavailable = errors.New("chat: unavailable")
+ // ErrRefused refuses a runner frame without effect: a report or ack
+ // from a runner that does not own what it names. The frame is acked
+ // (it will never succeed) and logged; the connection stays.
+ ErrRefused = errors.New("chat: refused for this runner")
)
// RunnerPrincipal is an authenticated runner credential.
@@ -46,6 +50,9 @@ type Authority struct {
PrimaryRunner func(tx *gorm.DB, person string) (string, error)
// CurrentRunner re-checks a runner credential and its owner.
CurrentRunner func(tx *gorm.DB, p RunnerPrincipal) error
+ // RunnerRole is the runner's enrolled role, wire.RolePrimary or
+ // wire.RoleWorker.
+ RunnerRole func(tx *gorm.DB, runnerID string) (string, error)
// ActivityLabel is the line a client shows for an activity, in a turn
// of turnKind (wire.TurnPerson, TurnMoveIn or TurnExplore).
ActivityLabel func(a wire.Activity, turnKind string) string
@@ -162,13 +169,26 @@ func (t *txn) saveTurn(r *turnRecord) error {
return t.turnEvent(*r)
}
+// command writes a durable command to the person's primary runner: the
+// conversation, merges, watches and publication live there. With no
+// primary yet it waits unaddressed; the primary's next connection takes
+// it (rebind).
func (t *txn) command(person, kind string, body any) error {
+ primary, err := t.s.authority.PrimaryRunner(t.db, person)
+ if err != nil {
+ return err
+ }
+ return t.commandTo(primary, person, kind, body)
+}
+
+// commandTo writes a durable command to one runner's mailbox.
+func (t *txn) commandTo(runner, person, kind string, body any) error {
raw, err := json.Marshal(body)
if err != nil {
return err
}
t.touched[person] = true
- return t.db.Create(&commandRecord{Person: person, Kind: kind, Body: string(raw), CreatedAt: t.now()}).Error
+ return t.db.Create(&commandRecord{Person: person, RunnerID: runner, Kind: kind, Body: string(raw), CreatedAt: t.now()}).Error
}
// dispatch sends a queued turn to the runner with the person's messages
diff --git a/internal/equipo/chat/stream.go b/internal/equipo/chat/stream.go
index 75532b0c..3895d3ef 100644
--- a/internal/equipo/chat/stream.go
+++ b/internal/equipo/chat/stream.go
@@ -9,6 +9,7 @@ import (
"time"
"amadan.net/oficina/equipo/internal/wire"
+ "amadan.net/rastrillo/rastrillo"
"github.com/coder/websocket"
)
@@ -60,7 +61,18 @@ func (rc *runnerConn) log(msg string, err error) {
}
}
+// send writes one frame as this connection's protocol speaks it. A frame
+// the protocol does not have is never sent (nothing places such work on a
+// protocol 1 runner; this is the last guard).
func (rc *runnerConn) send(ctx context.Context, f wire.Frame) error {
+ f, err := wire.Encode(f, rc.lease.Protocol)
+ if errors.Is(err, wire.ErrProtocol) {
+ rc.log("runner frame not sent at protocol 1", err)
+ return nil
+ }
+ if err != nil {
+ return err
+ }
raw, err := jsonFrame(f)
if err != nil {
return err
@@ -109,7 +121,7 @@ func (rc *runnerConn) serve() {
rc.log("runner disconnect", err)
}
}()
- welcome, _ := wire.NewFrame("w"+newID(""), wire.FrameWelcome, wire.Welcome{Generation: rc.lease.Generation, RunnerID: rc.principal.RunnerID})
+ welcome, _ := wire.NewFrame("w"+newID(""), wire.FrameWelcome, wire.Welcome{Generation: rc.lease.Generation, RunnerID: rc.principal.RunnerID, Protocol: rc.lease.Protocol, Role: rc.lease.Role, Release: rastrillo.BuildVersion})
if rc.send(ctx, welcome) != nil {
return
}
@@ -146,6 +158,10 @@ func (rc *runnerConn) read(ctx context.Context) websocket.StatusCode {
if err != nil {
return websocket.StatusPolicyViolation
}
+ // A protocol 1 runner speaks only the slice 4 frames.
+ if !wire.Speaks(rc.lease.Protocol, f.Type) {
+ return websocket.StatusPolicyViolation
+ }
select {
case rc.seen <- struct{}{}:
default:
@@ -167,6 +183,8 @@ func (rc *runnerConn) read(ctx context.Context) websocket.StatusCode {
return websocket.StatusPolicyViolation
}
switch {
+ case errors.Is(err, ErrRefused):
+ rc.log("runner frame refused", err)
case errors.Is(err, ErrSuperseded):
return wire.CloseSuperseded
case errors.Is(err, ErrInvalid):
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index b13964ae..70f114a2 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -55,6 +55,10 @@ type taskRecord struct {
MergeStrategy string
MergedWithoutChecks bool
MergedAt *time.Time
+ // EngineeringRunner is pinned at the first Engineering step: fix
+ // rounds, retries and republishes go there, so two runners never
+ // touch one branch.
+ EngineeringRunner string
}
func (taskRecord) TableName() string { return "chat_tasks" }
@@ -111,6 +115,21 @@ type stepRecord struct {
MergeInto string
MergeStrategy string
WithoutChecks bool
+ // RunnerID is the runner the current attempt is placed on ("" while
+ // Placement is waiting_runner). Needs is a JSON list of tags.
+ // RefusedBy lists runners that refused it (placement_refused).
+ // Withdrawn: the current attempt was withdrawn after it started; the
+ // next attempt is placed once its termination is proven.
+ RunnerID string `gorm:"index:chat_step_runner"`
+ Needs string
+ Placement string
+ WaitingSince *time.Time
+ RefusedBy string
+ Withdrawn bool
+ TerminationKind string
+ // Publication of a worker's Engineering candidate by the primary.
+ Publication string
+ PublicationID string
}
func (stepRecord) TableName() string { return "chat_steps" }
@@ -342,7 +361,7 @@ func (t *txn) saveTask(k *taskRecord) error {
}
k.Revision++
k.UpdatedAt = t.now()
- if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("stage", "base_sha", "cancel_requested", "revision", "updated_at", "moved_from", "branch_head", "merged_sha", "merged_into", "merge_strategy", "merged_without_checks", "merged_at").Updates(k).Error; err != nil {
+ if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Select("stage", "base_sha", "cancel_requested", "revision", "updated_at", "moved_from", "branch_head", "merged_sha", "merged_into", "merge_strategy", "merged_without_checks", "merged_at", "engineering_runner").Updates(k).Error; err != nil {
return err
}
if wire.FinalStage(k.Stage) && !wire.FinalStage(before) {
@@ -378,7 +397,7 @@ func (t *txn) taskEvent(k taskRecord) error {
func (t *txn) saveStep(s *stepRecord, k *taskRecord) 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", "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").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", "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", "runner_id", "needs", "placement", "waiting_since", "refused_by", "withdrawn", "termination_kind", "publication", "publication_id").Updates(s).Error; err != nil {
return err
}
members, err := t.members()
@@ -573,7 +592,7 @@ func (t *txn) startTask(r turnRecord, id, brief string) (wire.ToolResult, error)
if err := t.db.Create(&s).Error; err != nil {
return wire.ToolResult{}, err
}
- if err := t.dispatchStep(k, s); err != nil {
+ if err := t.dispatchStep(k, &s); err != nil {
return wire.ToolResult{}, err
}
k.Stage = wire.StageInProgress
@@ -584,9 +603,16 @@ func (t *txn) startTask(r turnRecord, id, brief string) (wire.ToolResult, error)
return wire.ToolResult{Code: "started", Text: string(raw)}, nil
}
-// dispatchStep queues the dispatch command for the step's attempt on its
-// person's runner, with the task's findings.
-func (t *txn) dispatchStep(k taskRecord, s stepRecord) error {
+// dispatchStep queues the dispatch command for the step's attempt on the
+// runner it is placed on, with the task's findings. The caller saves s.
+func (t *txn) dispatchStep(k taskRecord, s *stepRecord) error {
+ if s.RunnerID == "" {
+ primary, err := t.s.authority.PrimaryRunner(t.db, s.Person)
+ if err != nil {
+ return err
+ }
+ s.RunnerID = primary
+ }
var p projectRecord
if err := t.db.Where("id = ?", k.ProjectID).First(&p).Error; err != nil {
return err
@@ -599,7 +625,7 @@ func (t *txn) dispatchStep(k taskRecord, s stepRecord) error {
if base == "" && !s.Rebase {
base = k.BaseSHA
}
- brief, err := t.stepBrief(k, s)
+ brief, err := t.stepBrief(k, *s)
if err != nil {
return err
}
@@ -615,7 +641,7 @@ func (t *txn) dispatchStep(k taskRecord, s stepRecord) error {
// (FromBase..FromCandidate) on it.
cmd.Rebase, cmd.FromBase, cmd.CandidateSHA = true, s.FromBase, s.FromCandidate
}
- return t.command(s.Person, wire.FrameDispatch, cmd)
+ return t.commandTo(s.RunnerID, s.Person, wire.FrameDispatch, cmd)
}
// readTask is what the coordinator sees of a task.
@@ -678,7 +704,7 @@ func (t *txn) cancelTask(person, id string) (int64, error) {
if err := t.saveTask(&k); err != nil {
return 0, err
}
- return s.Attempt, t.command(s.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt})
+ return s.Attempt, t.commandTo(s.RunnerID, s.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt})
}
// stepReport applies a runner's step report: only the current attempt,
@@ -707,12 +733,9 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error {
if s.Person != l.Runner.Person {
return ErrNotFound
}
- primary, err := t.s.authority.PrimaryRunner(t.db, s.Person)
- if err != nil {
- return err
- }
- if primary != l.Runner.RunnerID {
- return ErrForbidden
+ // Only the runner the step is placed on reports it.
+ if s.RunnerID != l.Runner.RunnerID {
+ return ErrRefused
}
if v.Attempt != s.Attempt {
return nil
@@ -879,8 +902,10 @@ func (t *txn) syncSteps(l Lease, held []wire.StepRun) error {
for _, h := range held {
have[h.StepID+"/"+itoa64(h.Attempt)] = true
}
+ // Only this runner's own steps: a worker's sync never settles the
+ // primary's work, nor a Linux attempt awaiting its termination proof.
var rows []stepRecord
- if err := t.db.Where("person = ? AND state IN ?", l.Runner.Person, []string{wire.StepQueued, wire.StepRunning}).Find(&rows).Error; err != nil {
+ if err := t.db.Where("runner_id = ? AND person = ? AND state IN ?", l.Runner.RunnerID, l.Runner.Person, []string{wire.StepQueued, wire.StepRunning}).Find(&rows).Error; err != nil {
return err
}
for i := range rows {
@@ -889,7 +914,7 @@ func (t *txn) syncSteps(l Lease, held []wire.StepRun) error {
continue
}
var unacked int64
- if err := t.db.Model(&commandRecord{}).Where("person = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", s.Person, wire.FrameDispatch, `%"step_id":"`+s.ID+`","attempt":`+itoa64(s.Attempt)+`,%`).Count(&unacked).Error; err != nil {
+ if err := t.db.Model(&commandRecord{}).Where("runner_id = ? AND person = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", l.Runner.RunnerID, s.Person, wire.FrameDispatch, `%"step_id":"`+s.ID+`","attempt":`+itoa64(s.Attempt)+`,%`).Count(&unacked).Error; err != nil {
return err
}
if unacked != 0 {
@@ -1044,7 +1069,7 @@ func (s *Store) RetryTask(ctx context.Context, person, id string) (attempt int64
if st.Specialist == wire.SpecialistMerge {
st.MergeSHA, st.MergeInto, st.MergeStrategy = "", "", ""
}
- if err := t.dispatchStep(k, st); err != nil {
+ if err := t.dispatchStep(k, &st); err != nil {
return err
}
k.Stage = wire.StageInProgress
diff --git a/internal/equipo/chat_wiring.go b/internal/equipo/chat_wiring.go
index 90184a9b..16b12ec7 100644
--- a/internal/equipo/chat_wiring.go
+++ b/internal/equipo/chat_wiring.go
@@ -36,6 +36,7 @@ func (s *Store) Chat() *chat.Store {
_, err := runnerPrincipalAt(tx, RunnerPrincipal{RunnerID: p.RunnerID, Person: p.Person, CredentialID: p.CredentialID}, time.Now())
return err
},
+ RunnerRole: runnerRole,
ActivityLabel: activityLabel,
Copy: copyText,
}, nil)
@@ -68,12 +69,15 @@ func chatMe(tx *gorm.DB, address string) (wire.Me, error) {
return wire.Me{ID: m.Address, Address: m.Address, Role: role, Person: wire.Person{Address: m.Address, DisplayIdentity: m.Address, Active: m.Active, Role: role}, TeamID: t.ID, TeamName: t.Name, Revision: m.Revision}, nil
}
-// primaryRunner is the person's newest unrevoked runner, and only for an
-// active owner: teammate execution stays denied in v1.
+// primaryRunner is the person's newest unrevoked primary runner, and only
+// for an active owner: teammate execution stays denied in v1. Workers
+// never serve the coordinator. A row from before roles (no role) counts as
+// a primary, as migration 0047 marked them all.
func primaryRunner(tx *gorm.DB, person string) (string, error) {
var ids []string
err := tx.Raw(`SELECT r.id FROM runners r JOIN members m ON m.address = r.person
WHERE r.person = ? AND r.revoked_at IS NULL AND m.active = 1 AND m.role = ?
+ AND coalesce(r.role, '') IN ('primary', '')
ORDER BY r.rowid DESC LIMIT 1`, normalizeAddress(person), string(RoleOwner)).Scan(&ids).Error
if err != nil {
return "", storeError(err)
@@ -84,6 +88,19 @@ func primaryRunner(tx *gorm.DB, person string) (string, error) {
return ids[0], nil
}
+// runnerRole is the runner's enrolled role; a row from before roles is a
+// primary.
+func runnerRole(tx *gorm.DB, id string) (string, error) {
+ var roles []string
+ if err := tx.Raw(`SELECT coalesce(role, '') FROM runners WHERE id = ?`, id).Scan(&roles).Error; err != nil {
+ return "", storeError(err)
+ }
+ if len(roles) == 1 && roles[0] == wire.RoleWorker {
+ return wire.RoleWorker, nil
+ }
+ return wire.RolePrimary, nil
+}
+
func (s *Store) chatHTTP(authenticate func(*http.Request) (personapi.PersonPrincipal, error), failure func(http.ResponseWriter, *http.Request, error)) *chat.HTTP {
return &chat.HTTP{Store: s.Chat(), Authenticate: authenticate, Failure: failure, AuthenticateRunner: func(ctx context.Context, token string) (chat.RunnerPrincipal, error) {
p, err := s.AuthenticateRunner(ctx, token)
diff --git a/internal/equipo/migrations/0047_thin_runners.sql b/internal/equipo/migrations/0047_thin_runners.sql
new file mode 100644
index 00000000..6092e4c3
--- /dev/null
+++ b/internal/equipo/migrations/0047_thin_runners.sql
@@ -0,0 +1,30 @@
+ALTER TABLE runners ADD COLUMN role text;
+ALTER TABLE runner_commands ADD COLUMN runner_id text;
+ALTER TABLE chat_steps ADD COLUMN runner_id text;
+ALTER TABLE chat_steps ADD COLUMN needs text;
+ALTER TABLE chat_steps ADD COLUMN placement text;
+ALTER TABLE chat_steps ADD COLUMN waiting_since datetime;
+ALTER TABLE chat_steps ADD COLUMN refused_by text;
+ALTER TABLE chat_steps ADD COLUMN withdrawn numeric;
+ALTER TABLE chat_steps ADD COLUMN termination_kind text;
+ALTER TABLE chat_steps ADD COLUMN publication text;
+ALTER TABLE chat_steps ADD COLUMN publication_id text;
+ALTER TABLE chat_tasks ADD COLUMN engineering_runner text;
+ALTER TABLE runner_sessions ADD COLUMN protocol integer;
+CREATE INDEX runner_command_runner ON runner_commands(runner_id);
+CREATE INDEX chat_step_runner ON chat_steps(runner_id);
+CREATE TABLE runner_transfers (id text PRIMARY KEY, person text, from_runner text, to_runner text, repo text, task_id text, step_id text, attempt integer, base_sha text, candidate_sha text, direction text, state text, sha256 text, total integer, received integer, bytes integer, expires_at datetime, created_at datetime);
+CREATE INDEX runner_transfer_step ON runner_transfers(step_id);
+UPDATE runners SET role = 'primary';
+UPDATE runner_commands SET runner_id = coalesce(
+ (SELECT r.id FROM runners r JOIN members m ON m.address = r.person WHERE r.person = runner_commands.person AND r.revoked_at IS NULL AND m.active = 1 AND m.role = 'owner' ORDER BY r.rowid DESC LIMIT 1),
+ (SELECT r.id FROM runners r WHERE r.person = runner_commands.person AND r.revoked_at IS NULL ORDER BY r.rowid DESC LIMIT 1),
+ (SELECT r.id FROM runners r WHERE r.person = runner_commands.person ORDER BY r.rowid DESC LIMIT 1),
+ '');
+UPDATE chat_steps SET runner_id = coalesce(
+ (SELECT r.id FROM runners r JOIN members m ON m.address = r.person WHERE r.person = chat_steps.person AND r.revoked_at IS NULL AND m.active = 1 AND m.role = 'owner' ORDER BY r.rowid DESC LIMIT 1),
+ (SELECT r.id FROM runners r WHERE r.person = chat_steps.person AND r.revoked_at IS NULL ORDER BY r.rowid DESC LIMIT 1),
+ (SELECT r.id FROM runners r WHERE r.person = chat_steps.person ORDER BY r.rowid DESC LIMIT 1),
+ '');
+UPDATE chat_steps SET placement = 'waiting_runner', waiting_since = updated_at WHERE runner_id = '' AND state IN ('queued', 'running');
+UPDATE chat_tasks SET engineering_runner = coalesce((SELECT s.runner_id FROM chat_steps s WHERE s.task_id = chat_tasks.id AND s.specialist = 'engineering' AND s.runner_id <> '' ORDER BY s.idx LIMIT 1), '');
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 1f4dee4b..19c60aac 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -219,7 +219,8 @@ CREATE TABLE runners (
label text,
revision integer,
revoked_at datetime,
- instance_id text
+ instance_id text,
+ role text
);
CREATE INDEX runner_person ON runners(person);
CREATE TABLE runner_enrolments (
@@ -576,10 +577,10 @@ CREATE UNIQUE INDEX chat_message_key ON chat_messages(person,idempotency_key);
CREATE INDEX chat_message_turn ON chat_messages(turn_id);
CREATE TABLE chat_events (id integer PRIMARY KEY, person text, type text, body text, created_at datetime);
CREATE INDEX chat_event_person ON chat_events(person);
-CREATE TABLE runner_commands (seq integer PRIMARY KEY, person text, kind text, body text, created_at datetime, acked_at datetime);
+CREATE TABLE runner_commands (seq integer PRIMARY KEY, person text, kind text, body text, created_at datetime, acked_at datetime, runner_id text);
CREATE INDEX runner_command_person ON runner_commands(person);
CREATE TABLE runner_inbox (runner_id text, frame_id text, seen_at datetime, PRIMARY KEY (runner_id, frame_id));
-CREATE TABLE runner_sessions (runner_id text PRIMARY KEY, generation integer, connected numeric, process text, revision integer, hello text, seen_at datetime);
+CREATE TABLE runner_sessions (runner_id text PRIMARY KEY, generation integer, connected numeric, process text, revision integer, hello text, seen_at datetime, protocol integer);
CREATE TABLE chat_projects (id text PRIMARY KEY, repo text, state text, added_by text, revision integer, created_at datetime, updated_at datetime, title text);
CREATE UNIQUE INDEX chat_project_repo ON chat_projects(repo);
CREATE TABLE chat_cards (id text PRIMARY KEY, person text, kind text, state text, turn_id text, project_id text, question text, options text, choice text, answer_message text, revision integer, created_at datetime, updated_at datetime, undo text, task_id text, name text);
@@ -592,9 +593,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);
+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, engineering_runner 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);
+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, runner_id text, needs text, placement text, waiting_since datetime, refused_by text, withdrawn numeric, termination_kind text, publication text, publication_id 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);
CREATE INDEX chat_entry_task ON chat_task_entries(task_id);
@@ -602,3 +603,7 @@ CREATE UNIQUE INDEX chat_entry_key ON chat_task_entries(task_id, idempotency_key
CREATE TABLE chat_questions (id text PRIMARY KEY, task_id text, asker text, idempotency_key text, step_id text, specialist text, chosen text, text text, state text, reason text, attempt integer, dispatched numeric, answer text, timing text, revision integer, created_at datetime, updated_at datetime);
CREATE INDEX chat_question_task ON chat_questions(task_id);
CREATE UNIQUE INDEX chat_question_key ON chat_questions(task_id, asker, idempotency_key);
+CREATE INDEX runner_command_runner ON runner_commands(runner_id);
+CREATE INDEX chat_step_runner ON chat_steps(runner_id);
+CREATE TABLE runner_transfers (id text PRIMARY KEY, person text, from_runner text, to_runner text, repo text, task_id text, step_id text, attempt integer, base_sha text, candidate_sha text, direction text, state text, sha256 text, total integer, received integer, bytes integer, expires_at datetime, created_at datetime);
+CREATE INDEX runner_transfer_step ON runner_transfers(step_id);
diff --git a/internal/equipo/migrations_runners_test.go b/internal/equipo/migrations_runners_test.go
new file mode 100644
index 00000000..a5979a0d
--- /dev/null
+++ b/internal/equipo/migrations_runners_test.go
@@ -0,0 +1,122 @@
+package equipo
+
+import (
+ "context"
+ "database/sql"
+ "io"
+ "log/slog"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+)
+
+// slice4Schema is every migration before the runners migration: the
+// database a slice 4 instance leaves behind.
+func slice4Schema() *migrate.Set {
+ s := &migrate.Set{}
+ for _, m := range BootSchema.All() {
+ if strings.HasPrefix(m.ID, "equipo/0047_") {
+ break
+ }
+ s.Add(m)
+ }
+ return s
+}
+
+// Migration 0047 over a slice 4 database binds every command and every
+// step, in every state, to the person's primary at migration time (the
+// primaryRunner query), marks every runner primary, and leaves no step
+// without an owner.
+func TestRunnersMigrationBindsSlice4Rows(t *testing.T) {
+ ctx := context.Background()
+ d, err := db.Open(filepath.Join(t.TempDir(), "slice4.db"), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ w := d.Writer()
+ if _, err := migrate.Apply(ctx, d, slice4Schema()); err != nil {
+ t.Fatal(err)
+ }
+ exec := func(q string, args ...any) {
+ t.Helper()
+ if _, err := w.Exec(q, args...); err != nil {
+ t.Fatalf("%s: %v", q, err)
+ }
+ }
+ // The owner had a revoked runner, then an older one, then the newest
+ // (the slice 4 primary). A teammate (not an owner) has a runner; a
+ // third person never had one.
+ exec(`INSERT INTO members(address, role, revision, active, session_epoch) VALUES ('owner@example.com','owner',1,1,1), ('mate@example.com','member',1,1,1), ('new@example.com','owner',1,1,1)`)
+ exec(`INSERT INTO runners(id, person, machine_key_hash, label, revision, revoked_at, instance_id) VALUES
+ ('R0','owner@example.com','k0','old',2,'2026-11-01 00:00:00','i'),
+ ('R1','owner@example.com','k1','older',1,NULL,'i'),
+ ('R2','owner@example.com','k2','docs-t1',1,NULL,'i'),
+ ('M1','mate@example.com','k3','mate',1,NULL,'i')`)
+ exec(`INSERT INTO runner_commands(seq, person, kind, body, created_at, acked_at) VALUES
+ (1,'owner@example.com','message','{}','2026-11-07 10:00:00',NULL),
+ (2,'owner@example.com','dispatch','{}','2026-11-07 10:00:01',NULL),
+ (3,'owner@example.com','watch_merge','{}','2026-11-07 10:00:02','2026-11-07 10:00:03'),
+ (4,'mate@example.com','message','{}','2026-11-07 10:00:04',NULL)`)
+ step := `INSERT INTO chat_steps(id, task_id, idx, specialist, person, state, reason, attempt, terminated, revision, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,1,'2026-11-07 10:00:00','2026-11-07 10:00:00')`
+ exec(step, "s_running", "tk1", 1, "engineering", "owner@example.com", "running", "", 1, 0)
+ exec(step, "s_pending", "tk2", 2, "checks", "owner@example.com", "failed", "provider_failed", 1, 0)
+ exec(step, "s_queued", "tk3", 1, "engineering", "owner@example.com", "queued", "", 2, 0)
+ exec(step, "s_done", "tk4", 1, "review", "owner@example.com", "done", "", 1, 1)
+ exec(step, "s_mate", "tk5", 1, "engineering", "mate@example.com", "running", "", 1, 0)
+ exec(step, "s_nobody", "tk6", 1, "engineering", "new@example.com", "queued", "", 1, 0)
+ exec(`INSERT INTO chat_tasks(id, stage, revision) VALUES ('tk1','in_progress',1), ('tk3','in_progress',1), ('tk6','in_progress',1)`)
+
+ if _, err := migrate.Apply(ctx, d, BootSchema); err != nil {
+ t.Fatal(err)
+ }
+ str := func(q string, args ...any) string {
+ t.Helper()
+ var v sql.NullString
+ if err := w.QueryRow(q, args...).Scan(&v); err != nil {
+ t.Fatalf("%s: %v", q, err)
+ }
+ return v.String
+ }
+ for _, id := range []string{"R0", "R1", "R2", "M1"} {
+ if role := str("SELECT role FROM runners WHERE id=?", id); role != "primary" {
+ t.Fatalf("runner %s role %q", id, role)
+ }
+ }
+ for seq, want := range map[int]string{1: "R2", 2: "R2", 3: "R2", 4: "M1"} {
+ if got := str("SELECT runner_id FROM runner_commands WHERE seq=?", seq); got != want {
+ t.Fatalf("command %d bound to %q, want %q", seq, got, want)
+ }
+ }
+ for id, want := range map[string]string{"s_running": "R2", "s_pending": "R2", "s_queued": "R2", "s_done": "R2", "s_mate": "M1", "s_nobody": ""} {
+ if got := str("SELECT runner_id FROM chat_steps WHERE id=?", id); got != want {
+ t.Fatalf("step %s bound to %q, want %q", id, got, want)
+ }
+ }
+ if p := str("SELECT placement FROM chat_steps WHERE id='s_nobody'"); p != "waiting_runner" {
+ t.Fatalf("runnerless step placement %q", p)
+ }
+ if p := str("SELECT coalesce(placement,'') FROM chat_steps WHERE id='s_running'"); p != "" {
+ t.Fatalf("bound step placement %q", p)
+ }
+ if r := str("SELECT engineering_runner FROM chat_tasks WHERE id='tk1'"); r != "R2" {
+ t.Fatalf("engineering runner %q", r)
+ }
+ // Nothing the migration touched changed state.
+ if st := str("SELECT state || '/' || terminated FROM chat_steps WHERE id='s_pending'"); st != "failed/0" {
+ t.Fatalf("pending termination became %s", st)
+ }
+ n, err := chat.UnboundSteps(d.G)
+ if err != nil || n != 0 {
+ t.Fatalf("unbound steps after migration: %d %v", n, err)
+ }
+ // The check does catch a step with no owner.
+ exec(`UPDATE chat_steps SET runner_id = '' WHERE id = 's_running'`)
+ if n, err := chat.UnboundSteps(d.G); err != nil || n != 1 {
+ t.Fatalf("unbound step not caught: %d %v", n, err)
+ }
+}
diff --git a/internal/equipo/setup/enrolment.go b/internal/equipo/setup/enrolment.go
index 69fb4131..2ebfbdc9 100644
--- a/internal/equipo/setup/enrolment.go
+++ b/internal/equipo/setup/enrolment.go
@@ -143,6 +143,16 @@ func (s *Enrolments) ApproveOrInspect(ctx context.Context, actor Actor, userCode
return s.Conflict
}
result.ID = rand.Text()
+ // A person's first runner is the primary; later ones are workers.
+ // Replacing a primary means revoking it first.
+ var primaries int64
+ if err := tx.Model(&RunnerRecord{}).Where("instance_id=? AND person=? AND revoked_at IS NULL AND coalesce(role,'') IN ('primary','')", instance, member.Address).Count(&primaries).Error; err != nil {
+ return s.Error(err)
+ }
+ result.Role = RolePrimary
+ if primaries != 0 {
+ result.Role = RoleWorker
+ }
if err := tx.Create(&RunnerRecord{Runner: result, InstanceID: instance}).Error; err != nil {
return s.Error(err)
}
diff --git a/internal/equipo/setup/runner_models.go b/internal/equipo/setup/runner_models.go
index 757e0b19..22f4ac79 100644
--- a/internal/equipo/setup/runner_models.go
+++ b/internal/equipo/setup/runner_models.go
@@ -13,8 +13,16 @@ type Runner struct {
Label string
Revision int64
RevokedAt *time.Time
+ // Role is primary (the person's first runner) or worker.
+ Role string
}
+// Runner roles.
+const (
+ RolePrimary = "primary"
+ RoleWorker = "worker"
+)
+
type RunnerRecord struct {
Runner `gorm:"embedded"`
InstanceID string
diff --git a/internal/runner/config.go b/internal/runner/config.go
index cfb76022..143a2e4e 100644
--- a/internal/runner/config.go
+++ b/internal/runner/config.go
@@ -4,6 +4,7 @@ import (
"net/url"
"os"
"path/filepath"
+ "runtime"
"strings"
"amadan.net/oficina/equipo/internal/runner/provider"
@@ -21,10 +22,13 @@ type Config struct {
GoRoot, GoBinary, WorkspaceRoot, ScratchRoot, GitPath, AmadanPath, Executable string
InstanceID string
Copy ToolCopy
+ // WorkerOnly: a runner that can only be a worker (a Mac, or the test
+ // build's fake Mac). It refuses an instance without workers.
+ WorkerOnly bool
}
func LoadConfig(getenv func(string) string) (Config, error) {
- c := Config{ClaudeModel: getenv("EQUIPO_CLAUDE_MODEL"), CodexModel: getenv("EQUIPO_CODEX_MODEL"), MachineLabel: getenv("EQUIPO_MACHINE_LABEL"), ToolProxyPath: getenv("EQUIPO_TOOL_PROXY_PATH"), CodexCodeModeHostPath: getenv("EQUIPO_CODEX_CODE_MODE_HOST_PATH"), BwrapPath: getenv("EQUIPO_BWRAP_PATH"), ModuleCache: getenv("EQUIPO_GO_MODULE_CACHE"), ClaudePath: getenv("EQUIPO_CLAUDE_PATH"), Origin: getenv("EQUIPO_ORIGIN"), StateDir: getenv("EQUIPO_RUNNER_STATE_DIR"), AmadanCredentialPath: getenv("EQUIPO_AMADAN_CREDENTIAL_PATH"), AccountBindingsPath: getenv("EQUIPO_ACCOUNT_BINDINGS_PATH"), CodexPath: getenv("EQUIPO_CODEX_PATH"), GoRoot: getenv("EQUIPO_GO_ROOT"), GoBinary: getenv("EQUIPO_GO_BINARY"), WorkspaceRoot: getenv("EQUIPO_WORKSPACE_ROOT"), ScratchRoot: getenv("EQUIPO_SCRATCH_ROOT"), GitPath: getenv("EQUIPO_GIT_PATH"), AmadanPath: getenv("EQUIPO_AMADAN_PATH"), InstanceID: getenv("EQUIPO_INSTANCE_ID")}
+ c := Config{WorkerOnly: runtime.GOOS == "darwin" || getenv("EQUIPO_FAKE_PLATFORM") != "", ClaudeModel: getenv("EQUIPO_CLAUDE_MODEL"), CodexModel: getenv("EQUIPO_CODEX_MODEL"), MachineLabel: getenv("EQUIPO_MACHINE_LABEL"), ToolProxyPath: getenv("EQUIPO_TOOL_PROXY_PATH"), CodexCodeModeHostPath: getenv("EQUIPO_CODEX_CODE_MODE_HOST_PATH"), BwrapPath: getenv("EQUIPO_BWRAP_PATH"), ModuleCache: getenv("EQUIPO_GO_MODULE_CACHE"), ClaudePath: getenv("EQUIPO_CLAUDE_PATH"), Origin: getenv("EQUIPO_ORIGIN"), StateDir: getenv("EQUIPO_RUNNER_STATE_DIR"), AmadanCredentialPath: getenv("EQUIPO_AMADAN_CREDENTIAL_PATH"), AccountBindingsPath: getenv("EQUIPO_ACCOUNT_BINDINGS_PATH"), CodexPath: getenv("EQUIPO_CODEX_PATH"), GoRoot: getenv("EQUIPO_GO_ROOT"), GoBinary: getenv("EQUIPO_GO_BINARY"), WorkspaceRoot: getenv("EQUIPO_WORKSPACE_ROOT"), ScratchRoot: getenv("EQUIPO_SCRATCH_ROOT"), GitPath: getenv("EQUIPO_GIT_PATH"), AmadanPath: getenv("EQUIPO_AMADAN_PATH"), InstanceID: getenv("EQUIPO_INSTANCE_ID")}
var err error
c.Executable, err = os.Executable()
if err != nil {
diff --git a/internal/runner/diagnostics.go b/internal/runner/diagnostics.go
index e7e1f75d..528d033a 100644
--- a/internal/runner/diagnostics.go
+++ b/internal/runner/diagnostics.go
@@ -65,6 +65,8 @@ func Diagnostic(err error) (string, string) {
code = "runner.contract"
case errors.Is(err, ErrJournal):
code = "runner.reconcile"
+ case errors.Is(err, ErrInstanceOlder):
+ code = "runner.instance_older_than_worker"
}
return code, "-"
}
diff --git a/internal/runner/enrol.go b/internal/runner/enrol.go
index d7313a63..625ce1fc 100644
--- a/internal/runner/enrol.go
+++ b/internal/runner/enrol.go
@@ -17,6 +17,7 @@ import (
"amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/runnerproto"
+ "amadan.net/oficina/equipo/internal/wire"
)
func outboundClient() *http.Client {
@@ -28,6 +29,15 @@ func Enrol(ctx context.Context, c Config, output io.Writer) (resultErr error) {
if err := c.validateEnrolment(); err != nil {
return err
}
+ if c.WorkerOnly {
+ // A worker enrolled with an older instance would be its newest
+ // runner, which that instance takes for the primary. Ask first.
+ variable = "EQUIPO_ORIGIN"
+ if err := workerProtocol(ctx, c.Origin); err != nil {
+ return err
+ }
+ variable = "EQUIPO_RUNNER_STATE_DIR"
+ }
lock, err := lockState(c.StateDir)
if err != nil {
return err
@@ -173,6 +183,35 @@ func Enrol(ctx context.Context, c Config, output io.Writer) (resultErr error) {
}
return provider.ErrIdentity
}
+
+// ErrInstanceOlder refuses to enrol a runner that can only be a worker
+// with an instance that does not speak protocol 2.
+var ErrInstanceOlder = errors.New("the instance is older than this worker")
+
+// workerProtocol asks the instance which runner protocol it speaks; one
+// that does not answer speaks protocol 1, which has no workers.
+func workerProtocol(ctx context.Context, origin string) error {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, origin+wire.RunnerProtocolPath, nil)
+ if err != nil {
+ return err
+ }
+ resp, err := outboundClient().Do(req)
+ if err != nil {
+ return provider.ErrUncertain
+ }
+ defer resp.Body.Close()
+ var v wire.RunnerProtocol
+ if resp.StatusCode != http.StatusOK || wire.Strict(mustRead(resp.Body), &v) != nil || v.Protocol < wire.Protocol2 {
+ return ErrInstanceOlder
+ }
+ return nil
+}
+
+func mustRead(r io.Reader) []byte {
+ raw, _ := io.ReadAll(io.LimitReader(r, 4<<10))
+ return raw
+}
+
func randomBytes(n int) []byte {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
diff --git a/internal/runner/enrol_worker_test.go b/internal/runner/enrol_worker_test.go
new file mode 100644
index 00000000..443f6664
--- /dev/null
+++ b/internal/runner/enrol_worker_test.go
@@ -0,0 +1,63 @@
+package runner
+
+import (
+ "context"
+ "net"
+ "net/http"
+ "path/filepath"
+ "sync"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// A runner that can only be a worker asks the instance which protocol it
+// speaks before it enrols: an older instance (no protocol route) would take
+// the newest runner for the person's primary, so the worker is refused
+// with a fixed diagnostic and nothing is sent to the enrolment routes.
+func TestWorkerEnrolRefusesAnOlderInstance(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ protocol string
+ refused bool
+ }{
+ {"older instance", "", true},
+ {"protocol 1", `{"protocol":1}`, true},
+ {"protocol 2", `{"protocol":2}`, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var mu sync.Mutex
+ var paths []string
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ paths = append(paths, r.Method+" "+r.URL.Path)
+ mu.Unlock()
+ if r.URL.Path == wire.RunnerProtocolPath && tc.protocol != "" {
+ _, _ = w.Write([]byte(tc.protocol))
+ return
+ }
+ http.Error(w, "no", http.StatusNotFound)
+ })}
+ go srv.Serve(l)
+ defer srv.Close()
+ c := Config{Origin: "http://" + l.Addr().String(), InstanceID: "inst", StateDir: filepath.Join(t.TempDir(), "state"), WorkerOnly: true}
+ err = Enrol(context.Background(), c, nil)
+ code, _ := Diagnostic(err)
+ mu.Lock()
+ defer mu.Unlock()
+ if tc.refused {
+ if code != "runner.instance_older_than_worker" || len(paths) != 1 {
+ t.Fatalf("refused %q after %v", code, paths)
+ }
+ return
+ }
+ if code == "runner.instance_older_than_worker" || len(paths) < 2 {
+ t.Fatalf("protocol 2 instance refused: %q %v", code, paths)
+ }
+ })
+ }
+}
diff --git a/internal/runner/thin/capabilities.go b/internal/runner/thin/capabilities.go
new file mode 100644
index 00000000..ebd6e6b4
--- /dev/null
+++ b/internal/runner/thin/capabilities.go
@@ -0,0 +1,81 @@
+package thin
+
+import (
+ "context"
+ "os/exec"
+ "regexp"
+ "runtime"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// capabilityEvery re-probes what the runner can do.
+const capabilityEvery = time.Hour
+
+// Capabilities is the runner's capability report: computed at start,
+// re-probed hourly and when the instance disagrees (a placement this
+// runner had to refuse), sent with every heartbeat.
+type Capabilities struct {
+ Probe func(context.Context) wire.Capabilities
+
+ mu sync.Mutex
+ last wire.Capabilities
+ at time.Time
+}
+
+// Get is the newest report, probing when it is older than an hour.
+func (c *Capabilities) Get(ctx context.Context) wire.Capabilities {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.at.IsZero() || time.Since(c.at) > capabilityEvery {
+ next := c.Probe(ctx)
+ if wire.ValidCapabilities(next) != nil {
+ // Out of bounds: say only the tags, which are always valid.
+ next = wire.Capabilities{Tags: next.Tags}
+ if wire.ValidCapabilities(next) != nil {
+ next = wire.Capabilities{}
+ }
+ }
+ c.last, c.at = next, time.Now()
+ }
+ return c.last
+}
+
+// Stale makes the next Get probe again.
+func (c *Capabilities) Stale() {
+ c.mu.Lock()
+ c.at = time.Time{}
+ c.mu.Unlock()
+}
+
+var goVersion = regexp.MustCompile(`\bgo1\.[0-9]+(?:\.[0-9]+)?\b`)
+
+// linuxCapabilities is what a Linux runner reports: the linux tag, claude
+// when it runs Claude Code, go when checks have the Go toolchain. Never a
+// path or raw output.
+func linuxCapabilities(c runner.Config) func(context.Context) wire.Capabilities {
+ return func(ctx context.Context) wire.Capabilities {
+ out := wire.Capabilities{Simulators: []wire.Simulator{}, Tags: []string{wire.TagLinux}}
+ if c.ClaudePath != "" {
+ out.Harness.Claude = provider.ClaudeVersion
+ out.Tags = append(out.Tags, wire.TagClaude)
+ }
+ if c.GoBinary != "" {
+ pctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ raw, err := exec.CommandContext(pctx, c.GoBinary, "version").Output()
+ cancel()
+ if err == nil {
+ out.Toolchains.Go = goVersion.FindString(string(raw))
+ }
+ out.Tags = append(out.Tags, wire.TagGo)
+ }
+ return out
+ }
+}
+
+// hostPlatform is the platform the runner runs on.
+func hostPlatform() wire.Platform { return wire.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH} }
diff --git a/internal/runner/thin/contract_test.go b/internal/runner/thin/contract_test.go
index 0dee609f..a1aa0af0 100644
--- a/internal/runner/thin/contract_test.go
+++ b/internal/runner/thin/contract_test.go
@@ -93,6 +93,19 @@ func read(t *testing.T, c *websocket.Conn, kind string) (wire.Frame, []byte) {
t.Fatal(err)
}
if f.Type == kind {
+ if kind == wire.FrameHello {
+ // A protocol 2 hello carries the slice 4 hello's fields and
+ // the protocol 2 ones; at protocol 1 it is the slice 4 hello.
+ old, err := wire.Encode(f, wire.Protocol1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ check, _ := json.Marshal(old)
+ if err = wiretest.SameShape(wiretest.Fixture("frames/hello.json"), check); err != nil {
+ t.Fatalf("hello frame: %v\n%s", err, raw)
+ }
+ return f, raw
+ }
if err = wiretest.SameShape(wiretest.Fixture("frames/"+kind+".json"), raw); err != nil {
t.Fatalf("%s frame: %v\n%s", kind, err, raw)
}
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go
index f8d8b399..f379d8ad 100644
--- a/internal/runner/thin/link.go
+++ b/internal/runner/thin/link.go
@@ -21,6 +21,16 @@ var ErrSuperseded = errors.New("runner superseded by a newer generation")
// ErrRevoked means the instance refused this runner's credential.
var ErrRevoked = errors.New("runner credential refused")
+// ErrInstanceTooOld means the instance speaks only protocol 1 and this
+// runner can only be a worker, which protocol 1 cannot place work on. The
+// runner does not connect (nothing is lost: its work waits on the
+// instance) and tries again later.
+var ErrInstanceTooOld = errors.New("the instance speaks only protocol 1, which has no workers: update the instance first")
+
+// olderRetry is how long a worker waits before asking an older instance
+// again.
+var olderRetry = time.Minute
+
// HelloInterval is the heartbeat.
const HelloInterval = 30 * time.Second
@@ -44,6 +54,12 @@ type Link struct {
// Connected is called with true once a generation is granted and false
// when the socket ends. Tests use it to wait.
Connected func(bool)
+ // WorkerOnly: this runner can only be a worker (a Mac), so it never
+ // runs at protocol 1.
+ WorkerOnly bool
+ // Protocol caps what this runner offers (default wire.ProtocolCurrent;
+ // tests set 1 to act as a slice 4 runner).
+ Protocol int
mu sync.Mutex
conn *websocket.Conn
@@ -55,6 +71,21 @@ type Link struct {
tools map[string]chan wire.ToolResult
leaseSeq int64
helloSoon bool
+ // proto is what the current connection speaks; role what the instance
+ // said this runner is (primary at protocol 1).
+ proto int
+ role string
+}
+
+// Spoken is the protocol of the current connection (0 when disconnected)
+// and the role the instance gave this runner.
+func (l *Link) Spoken() (int, string) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ if l.conn == nil {
+ return 0, ""
+ }
+ return l.proto, l.role
}
func (l *Link) waitTool(callID string) chan wire.ToolResult {
@@ -216,7 +247,12 @@ func (l *Link) Run(ctx context.Context) error {
}
return err
}
- if err != nil && l.Logger != nil {
+ if errors.Is(err, ErrInstanceTooOld) {
+ retry = olderRetry
+ if l.Logger != nil {
+ l.Logger.Error("runner refused: this runner is a worker and the instance is an older release", "origin", l.Origin, "err", err)
+ }
+ } else if err != nil && l.Logger != nil {
l.Logger.Warn("runner stream", "err", err)
}
wait := backoff
@@ -234,7 +270,22 @@ func (l *Link) Run(ctx context.Context) error {
}
}
+// send writes one frame as the current connection's protocol speaks it;
+// a frame that protocol does not have is not sent.
func (l *Link) send(ctx context.Context, c *websocket.Conn, f wire.Frame) error {
+ l.mu.Lock()
+ proto := l.proto
+ l.mu.Unlock()
+ f, err := wire.Encode(f, max(proto, wire.Protocol1))
+ if errors.Is(err, wire.ErrProtocol) {
+ if l.Logger != nil {
+ l.Logger.Warn("runner frame not sent at protocol 1", "type", f.Type)
+ }
+ return nil
+ }
+ if err != nil {
+ return err
+ }
raw, err := json.Marshal(f)
if err != nil {
return err
@@ -244,18 +295,88 @@ func (l *Link) send(ctx context.Context, c *websocket.Conn, f wire.Frame) error
return c.Write(wctx, websocket.MessageText, raw)
}
-// session is one connection. It returns a retry delay after drain.
+// session is one connection. It returns a retry delay after drain. It
+// offers protocol 2; an older instance refuses that hello (its strict
+// decoder closes with a policy violation before any welcome), and the
+// runner says hello once more at protocol 1 on a new connection, unless it
+// can only be a worker.
func (l *Link) session(ctx context.Context) (time.Duration, error) {
+ offer := wire.ProtocolCurrent
+ if l.Protocol > 0 {
+ offer = min(l.Protocol, offer)
+ }
+ for {
+ c, welcome, err := l.handshake(ctx, offer)
+ if err == nil {
+ return l.serve(ctx, c, welcome)
+ }
+ if offer < wire.Protocol2 || websocket.CloseStatus(err) != websocket.StatusPolicyViolation {
+ return 0, err
+ }
+ if l.WorkerOnly {
+ return 0, ErrInstanceTooOld
+ }
+ if l.Logger != nil {
+ l.Logger.Warn("the instance is older: speaking protocol 1 on this connection", "origin", l.Origin)
+ }
+ offer = wire.Protocol1
+ }
+}
+
+// handshake dials, says hello at offer and reads the welcome.
+func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire.Welcome, error) {
url := "ws" + strings.TrimPrefix(l.Origin, "http") + wire.StreamPath
dctx, cancel := context.WithTimeout(ctx, 20*time.Second)
c, res, err := websocket.Dial(dctx, url, &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": {"Bearer " + l.Token}}, CompressionMode: websocket.CompressionDisabled})
cancel()
if err != nil {
if res != nil && res.StatusCode == http.StatusForbidden {
- return 0, ErrRevoked
+ return nil, nil, ErrRevoked
}
- return 0, err
+ return nil, nil, err
}
+ c.SetReadLimit(wire.MaxFrameBytes)
+ hello := l.Hello()
+ l.mu.Lock()
+ hello.Generation, hello.Protocol, l.proto = l.generation, offer, offer
+ l.mu.Unlock()
+ f, _ := wire.NewFrame(l.State.prefix+"-hello", wire.FrameHello, hello)
+ if err = l.send(ctx, c, f); err != nil {
+ c.CloseNow()
+ return nil, nil, err
+ }
+ rctx, rcancel := context.WithTimeout(ctx, 15*time.Second)
+ _, raw, err := c.Read(rctx)
+ rcancel()
+ if err != nil {
+ c.CloseNow()
+ if websocket.CloseStatus(err) == websocket.StatusPolicyViolation {
+ return nil, nil, err
+ }
+ return nil, nil, closeError(err)
+ }
+ wf, body, err := wire.ParseFrame(raw)
+ welcome, ok := body.(*wire.Welcome)
+ if err != nil || !ok || wf.Type != wire.FrameWelcome || welcome.Generation < 1 {
+ c.CloseNow()
+ return nil, nil, errors.New("runner stream: no welcome")
+ }
+ spoken, role := wire.Spoken(welcome.Protocol), welcome.Role
+ if welcome.Protocol == 0 {
+ spoken, role = wire.Protocol1, wire.RolePrimary
+ }
+ if spoken < wire.Protocol2 && l.WorkerOnly {
+ c.CloseNow()
+ return nil, nil, ErrInstanceTooOld
+ }
+ l.mu.Lock()
+ l.proto, l.role = min(spoken, offer), role
+ l.mu.Unlock()
+ return c, welcome, nil
+}
+
+// serve runs one connection after its welcome.
+func (l *Link) serve(ctx context.Context, c *websocket.Conn, welcome *wire.Welcome) (time.Duration, error) {
defer c.CloseNow()
c.SetReadLimit(wire.MaxFrameBytes)
parent := ctx
@@ -274,25 +395,6 @@ func (l *Link) session(ctx context.Context) (time.Duration, error) {
}
}()
- hello := l.Hello()
- l.mu.Lock()
- hello.Generation = l.generation
- l.mu.Unlock()
- f, _ := wire.NewFrame(l.State.prefix+"-hello", wire.FrameHello, hello)
- if err = l.send(ctx, c, f); err != nil {
- return 0, err
- }
- rctx, rcancel := context.WithTimeout(ctx, 15*time.Second)
- _, raw, err := c.Read(rctx)
- rcancel()
- if err != nil {
- return 0, closeError(err)
- }
- wf, body, err := wire.ParseFrame(raw)
- welcome, ok := body.(*wire.Welcome)
- if err != nil || !ok || wf.Type != wire.FrameWelcome || welcome.Generation < 1 {
- return 0, errors.New("runner stream: no welcome")
- }
l.mu.Lock()
l.generation, l.conn = welcome.Generation, c
l.mu.Unlock()
@@ -301,14 +403,14 @@ func (l *Link) session(ctx context.Context) (time.Duration, error) {
l.conn = nil
l.mu.Unlock()
}()
- if err = l.State.SaveGeneration(ctx, welcome.Generation); err != nil {
+ if err := l.State.SaveGeneration(ctx, welcome.Generation); err != nil {
return 0, err
}
sync, err := l.State.Sync(ctx)
if err != nil {
return 0, err
}
- f, _ = wire.NewFrame(l.State.prefix+"-sync-"+time.Now().UTC().Format("150405.000000"), wire.FrameSync, sync)
+ f, _ := wire.NewFrame(l.State.prefix+"-sync-"+time.Now().UTC().Format("150405.000000"), wire.FrameSync, sync)
if err = l.send(ctx, c, f); err != nil {
return 0, err
}
diff --git a/internal/runner/thin/protocol_test.go b/internal/runner/thin/protocol_test.go
new file mode 100644
index 00000000..306811ca
--- /dev/null
+++ b/internal/runner/thin/protocol_test.go
@@ -0,0 +1,132 @@
+package thin
+
+import (
+ "bytes"
+ "context"
+ "database/sql"
+ "encoding/json"
+ "log/slog"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "amadan.net/oficina/equipo/internal/wire/wiretest"
+ "github.com/coder/websocket"
+)
+
+// syncBuffer is a log sink tests read while the link writes.
+type syncBuffer struct {
+ mu sync.Mutex
+ b bytes.Buffer
+}
+
+func (s *syncBuffer) Write(p []byte) (int, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.b.Write(p)
+}
+func (s *syncBuffer) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() }
+
+// olderInstance answers like a slice 4 instance: its strict decoder
+// refuses a hello with any field it does not know, closing with a policy
+// violation before any welcome.
+func olderInstance(t *testing.T, c *websocket.Conn) (refused bool, hello []byte) {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ _, raw, err := c.Read(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if wiretest.SameShape(wiretest.Fixture("frames/hello.json"), raw) != nil {
+ c.Close(websocket.StatusPolicyViolation, "hello first")
+ return true, raw
+ }
+ write(t, c, wiretest.Fixture("frames/welcome.json"))
+ return false, raw
+}
+
+// A new runner against an older instance: its protocol 2 hello is refused
+// once, it says hello again at protocol 1 (exactly the slice 4 hello), logs
+// that the instance is older, and runs at protocol 1.
+func TestLinkFallsBackToProtocol1(t *testing.T) {
+ inst := newFakeInstance(t)
+ logs := &syncBuffer{}
+ link, _, _, _ := startLink(t, inst.url, &stubCoordinator{}, func(*State) {})
+ link.Logger = slog.New(slog.NewTextHandler(logs, nil))
+ first := <-inst.conns
+ if refused, raw := olderInstance(t, first); !refused || !strings.Contains(string(raw), `"protocol":2`) {
+ t.Fatalf("first hello was not protocol 2: %s", raw)
+ }
+ second := <-inst.conns
+ if refused, raw := olderInstance(t, second); refused {
+ t.Fatalf("second hello is not the slice 4 hello: %s", raw)
+ }
+ read(t, second, wire.FrameSync)
+ if p, role := link.Spoken(); p != wire.Protocol1 || role != wire.RolePrimary {
+ t.Fatalf("spoken %d %q", p, role)
+ }
+ if !strings.Contains(logs.String(), "the instance is older") {
+ t.Fatalf("no log line: %s", logs.String())
+ }
+ // Everything it sends now is the slice 4 wire: a step report with
+ // protocol 2 fields goes without them.
+ state := link.State
+ if err := state.tx(context.Background(), func(tx *sql.Tx) error {
+ return state.enqueue(tx, wire.FrameStep, "", wire.StepReport{TaskID: "tk1", StepID: "s1", Attempt: 1, State: wire.StepRunning, Findings: []wire.Finding{}, TerminationKind: wire.TerminationProcessGroup, Have: []string{strings.Repeat("2", 40)}})
+ }); err != nil {
+ t.Fatal(err)
+ }
+ link.Notify()
+ _, raw := read(t, second, wire.FrameStep)
+ if strings.Contains(string(raw), "termination_kind") || strings.Contains(string(raw), "have") {
+ t.Fatalf("protocol 2 fields sent at protocol 1: %s", raw)
+ }
+}
+
+// A runner that can only be a worker never runs at protocol 1: refused by
+// an older instance, it does not say hello again, logs why, and waits.
+func TestWorkerRefusesAnOlderInstance(t *testing.T) {
+ defer func(d time.Duration) { olderRetry = d }(olderRetry)
+ olderRetry = time.Hour
+ inst := newFakeInstance(t)
+ logs := &syncBuffer{}
+ link, _, _, _ := startLink(t, inst.url, &stubCoordinator{}, func(*State) {})
+ link.Logger = slog.New(slog.NewTextHandler(logs, nil))
+ link.WorkerOnly = true
+ first := <-inst.conns
+ olderInstance(t, first)
+ select {
+ case c := <-inst.conns:
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ _, raw, _ := c.Read(ctx)
+ t.Fatalf("worker said hello again: %s", raw)
+ case <-time.After(1500 * time.Millisecond):
+ }
+ if !strings.Contains(logs.String(), "this runner is a worker and the instance is an older release") {
+ t.Fatalf("no clear log line: %s", logs.String())
+ }
+}
+
+// Against a protocol 2 instance the runner speaks protocol 2 and learns
+// its role.
+func TestLinkSpeaksProtocol2(t *testing.T) {
+ inst := newFakeInstance(t)
+ link, _, _, _ := startLink(t, inst.url, &stubCoordinator{})
+ c := <-inst.conns
+ _, raw := read(t, c, wire.FrameHello)
+ var f wire.Frame
+ _ = json.Unmarshal(raw, &f)
+ _, body, _ := wire.ParseFrame(raw)
+ if body.(*wire.Hello).Protocol != wire.Protocol2 {
+ t.Fatalf("hello %s", raw)
+ }
+ write(t, c, wiretest.Fixture("frames/welcome-worker.json"))
+ read(t, c, wire.FrameSync)
+ if p, role := link.Spoken(); p != wire.Protocol2 || role != wire.RoleWorker {
+ t.Fatalf("spoken %d %q", p, role)
+ }
+}
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index 25a0f171..c9824685 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -52,6 +52,9 @@ type Options struct {
// MergeEvery spaces the merge checks of watched task branches
// (default: the minute reach check's pace).
MergeEvery time.Duration
+ // Protocol caps the runner stream protocol offered (tests: 1 acts as
+ // a slice 4 runner); 0 is the current one.
+ Protocol int
}
// OptionsFromEnv reads the runner's optional thin settings.
@@ -111,7 +114,9 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
health := &accountHealth{}
- link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected}
+ platform := hostPlatform()
+ caps := &Capabilities{Probe: linuxCapabilities(c)}
+ link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: platform.OS == "darwin"}
fg := o.Forge
if fg == nil {
fg = NewFileForge(c.AmadanCredentialPath, c.StateDir, !o.NoCreate)
@@ -174,7 +179,9 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
if catalog == nil {
catalog = []wire.RepoInfo{}
}
- return wire.Hello{Repos: repos, CreateIn: in, Home: home, Agent: fg.Agent(), Catalog: catalog, Accounts: health.accounts(c), Versions: map[string]string{"runner": o.Version, "claude": provider.ClaudeVersion}}
+ report := caps.Get(ctx)
+ return wire.Hello{Repos: repos, CreateIn: in, Home: home, Agent: fg.Agent(), Catalog: catalog, Accounts: health.accounts(c), Versions: map[string]string{"runner": o.Version, "claude": provider.ClaudeVersion},
+ Platform: &platform, Label: c.MachineLabel, Sandbox: wire.SandboxBubblewrap, Capabilities: &report}
}
if err = engine.Start(ctx); err != nil {
return err
diff --git a/internal/thintest/fakerunner.go b/internal/thintest/fakerunner.go
index c69a727c..2cb09821 100644
--- a/internal/thintest/fakerunner.go
+++ b/internal/thintest/fakerunner.go
@@ -21,8 +21,21 @@ type FakeRunner struct {
Sent [][]byte
}
-// DialRunner connects and says hello with generation.
+// DialRunner connects and says hello with generation (protocol 1, the
+// slice 4 hello).
func DialRunner(ctx context.Context, origin, token string, generation int64) (*FakeRunner, error) {
+ return DialRunnerHello(ctx, origin, token, wire.Hello{Generation: generation, Repos: []string{}, Accounts: []wire.Account{}, Versions: map[string]string{"runner": "test"}})
+}
+
+// WorkerHello is a protocol 2 hello from a Mac worker, with the fixture's
+// capability report.
+func WorkerHello(generation int64) wire.Hello {
+ return wire.Hello{Generation: generation, Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Accounts: []wire.Account{}, Versions: map[string]string{"runner": "test"}, Protocol: wire.Protocol2, Platform: &wire.Platform{OS: "darwin", Arch: "arm64"}, Label: "Tito Studio", Sandbox: wire.SandboxSeatbelt,
+ Capabilities: &wire.Capabilities{Xcode: wire.Xcode{Version: "16.2", Build: "16C5032a"}, Simulators: []wire.Simulator{{Name: "iPhone 16 Pro", Runtime: "iOS 18.2", UDID: "5C0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3", State: "Shutdown"}}, Tags: []string{wire.TagMacOS, wire.TagXcode, wire.TagIOSSimulator}}}
+}
+
+// DialRunnerHello connects and says hello.
+func DialRunnerHello(ctx context.Context, origin, token string, hello wire.Hello) (*FakeRunner, error) {
url := "ws" + strings.TrimPrefix(origin, "http") + wire.StreamPath
c, _, err := websocket.Dial(ctx, url, &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": {"Bearer " + token}}})
if err != nil {
@@ -30,7 +43,7 @@ func DialRunner(ctx context.Context, origin, token string, generation int64) (*F
}
c.SetReadLimit(wire.MaxFrameBytes)
r := &FakeRunner{Conn: c}
- if err = r.Send(ctx, "h0", wire.FrameHello, wire.Hello{Generation: generation, Repos: []string{}, Accounts: []wire.Account{}, Versions: map[string]string{"runner": "test"}}); err != nil {
+ if err = r.Send(ctx, "h0", wire.FrameHello, hello); err != nil {
return nil, err
}
f, body, err := r.Next(ctx)
diff --git a/internal/thintest/instance_contract_test.go b/internal/thintest/instance_contract_test.go
index 3f32e524..9b5c0638 100644
--- a/internal/thintest/instance_contract_test.go
+++ b/internal/thintest/instance_contract_test.go
@@ -605,17 +605,17 @@ func TestReplacedConnectionFenced(t *testing.T) {
shape(t, "frames/lease.json", fr.Sent[len(fr.Sent)-1])
}
-// An older runner of the same person must not fail the primary's turns.
+// Another runner of the same person (a worker: a person's later runners
+// are) must not fail the primary's turns.
func TestSecondaryRunnerSyncIgnored(t *testing.T) {
r := newRig(t)
- older := r.runner
- r.runner = r.inst.EnrolRunner(t).Token
+ worker := r.inst.EnrolRunner(t).Token
primary := r.dial(0)
sent, _ := r.client.Send(r.ctx, "hello", "k1")
f, _, _ := primary.Expect(r.ctx, wire.FrameMessage)
primary.Send(r.ctx, "a1", wire.FrameAck, wire.Ack{ID: f.ID})
r.wait("running", func(c *Conversation) bool { return c.Turns[sent.Turn.ID].State == wire.TurnRunning })
- secondary, err := DialRunner(r.ctx, r.inst.URL, older, 0)
+ secondary, err := DialRunnerHello(r.ctx, r.inst.URL, worker, WorkerHello(0))
if err != nil {
t.Fatal(err)
}
diff --git a/internal/thintest/migration_contract_test.go b/internal/thintest/migration_contract_test.go
new file mode 100644
index 00000000..c0cb46fd
--- /dev/null
+++ b/internal/thintest/migration_contract_test.go
@@ -0,0 +1,102 @@
+package thintest
+
+import (
+ "io"
+ "log/slog"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/oficina/equipo/internal/wire"
+ "amadan.net/rastrillo/rastrillo/db"
+)
+
+// slice4 strips the runners migration from a stopped instance's database,
+// leaving the schema and rows a slice 4 instance would have left.
+func slice4(t *testing.T, path string) {
+ t.Helper()
+ d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ for _, q := range []string{
+ "DROP INDEX runner_command_runner", "DROP INDEX chat_step_runner", "DROP TABLE runner_transfers",
+ "ALTER TABLE runners DROP COLUMN role", "ALTER TABLE runner_commands DROP COLUMN runner_id", "ALTER TABLE runner_sessions DROP COLUMN protocol",
+ "ALTER TABLE chat_tasks DROP COLUMN engineering_runner",
+ "ALTER TABLE chat_steps DROP COLUMN runner_id", "ALTER TABLE chat_steps DROP COLUMN needs", "ALTER TABLE chat_steps DROP COLUMN placement",
+ "ALTER TABLE chat_steps DROP COLUMN waiting_since", "ALTER TABLE chat_steps DROP COLUMN refused_by", "ALTER TABLE chat_steps DROP COLUMN withdrawn",
+ "ALTER TABLE chat_steps DROP COLUMN termination_kind", "ALTER TABLE chat_steps DROP COLUMN publication", "ALTER TABLE chat_steps DROP COLUMN publication_id",
+ "DELETE FROM rastrillo_migrations WHERE id LIKE 'equipo/0047_%'",
+ } {
+ if _, err := d.Writer().Exec(q); err != nil {
+ t.Fatalf("%s: %v", q, err)
+ }
+ }
+}
+
+// Migration 0047 over a slice 4 database with live work (a running step,
+// an attempt awaiting its termination proof, a dispatch the runner never
+// acked, a running turn) binds it all to the primary, and the runner that
+// held it carries on as before: the dispatch is delivered, the reports
+// are accepted, Retry still waits for termination.
+func TestContractMigrationOverSlice4Work(t *testing.T) {
+ r := newToolRig(t)
+ ctx := r.ctx
+ running := taskID(t, r.call("m1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Running when the upgrade lands", "brief": "b"}))
+ r.call("m2", wire.ToolStartTask, map[string]string{"task": running, "brief": "go"})
+ _, body := r.expect(wire.FrameDispatch)
+ d1 := body.(*wire.DispatchCommand)
+ r.step("r-m1", wire.StepReport{TaskID: running, StepID: d1.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40)})
+ pending := taskID(t, r.call("m3", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Awaiting its proof", "brief": "b"}))
+ r.call("m4", wire.ToolStartTask, map[string]string{"task": pending, "brief": "go"})
+ _, body = r.expect(wire.FrameDispatch)
+ d2 := body.(*wire.DispatchCommand)
+ r.step("r-m2", wire.StepReport{TaskID: pending, StepID: d2.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", BaseSHA: strings.Repeat("1", 40)})
+ unacked := taskID(t, r.call("m5", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Never acked", "brief": "b"}))
+ r.call("m6", wire.ToolStartTask, map[string]string{"task": unacked, "brief": "go"})
+
+ r.runner.Close()
+ r.inst.Stop()
+ slice4(t, r.inst.Path)
+ r.inst.Restart(t)
+ n, err := chat.UnboundSteps(r.inst.DB.G)
+ if err != nil || n != 0 {
+ t.Fatalf("unbound steps: %d %v", n, err)
+ }
+
+ // The same runner reconnects: the unacked dispatch is still its own.
+ r.runner = r.dial(r.runner.Welcome.Generation)
+ f, body, err := r.runner.Expect(ctx, wire.FrameDispatch)
+ for err == nil && body.(*wire.DispatchCommand).TaskID != unacked {
+ f, body, err = r.runner.Expect(ctx, wire.FrameDispatch)
+ }
+ if err != nil {
+ t.Fatalf("unacked dispatch lost in the upgrade: %v", err)
+ }
+ shape(t, "frames/dispatch.json", r.runner.Received[len(r.runner.Received)-1])
+ if err := r.runner.Send(ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}); err != nil {
+ t.Fatal(err)
+ }
+ // Its sync holds the running step: nothing is settled.
+ if err := r.runner.Send(ctx, "r-sync-m", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: r.turn, Attempt: 1, State: "running"}}, Steps: []wire.StepRun{{TaskID: running, StepID: d1.StepID, Attempt: 1, State: "running"}, {TaskID: pending, StepID: d2.StepID, Attempt: 1, State: "pending"}, {TaskID: unacked, StepID: body.(*wire.DispatchCommand).StepID, Attempt: 1, State: "running"}}}); err != nil {
+ t.Fatal(err)
+ }
+ // Retry still waits for the termination proof.
+ if _, err := r.client.RetryTask(ctx, pending); Status(err) != 409 {
+ t.Fatalf("retry before termination after the upgrade: %v", err)
+ }
+ r.step("r-m3", wire.StepReport{TaskID: pending, StepID: d2.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true})
+ if acc, err := r.client.RetryTask(ctx, pending); err != nil || acc.Attempt != 2 {
+ t.Fatalf("retry after the proof: %+v %v", acc, err)
+ }
+ // The running step's report is accepted from the runner it was bound to.
+ r.step("r-m4", wire.StepReport{TaskID: running, StepID: d1.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true})
+ if k, err := r.client.Task(ctx, running); err != nil || k.Steps[0].State != wire.StepFailed || !k.Steps[0].Terminated {
+ t.Fatalf("the running step's report after the upgrade: %+v %v", k, err)
+ }
+ // The turn that was running is still the primary's.
+ if k, _ := r.client.Turn(ctx, r.turn); k.State != wire.TurnRunning {
+ t.Fatalf("turn after the upgrade: %+v", k)
+ }
+}
diff --git a/internal/thintest/runners_contract_test.go b/internal/thintest/runners_contract_test.go
new file mode 100644
index 00000000..9f019b66
--- /dev/null
+++ b/internal/thintest/runners_contract_test.go
@@ -0,0 +1,156 @@
+package thintest
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// worker enrols a second runner of the owner (a worker: the first is the
+// primary) and connects it at protocol 2.
+func (r *toolRig) worker() *FakeRunner {
+ r.t.Helper()
+ token := r.inst.EnrolRunner(r.t).Token
+ w, err := DialRunnerHello(r.ctx, r.inst.URL, token, WorkerHello(0))
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ r.t.Cleanup(w.Close)
+ return w
+}
+
+// A person's first runner is the primary and later ones are workers; the
+// welcome says so at protocol 2 and says nothing new at protocol 1; a
+// protocol 1 runner that is a worker is refused.
+func TestContractRunnerRoles(t *testing.T) {
+ r := newToolRig(t)
+ shape(t, "frames/welcome.json", r.runner.Received[0])
+ if r.runner.Welcome.Role != "" || r.runner.Welcome.Protocol != 0 {
+ t.Fatalf("protocol 1 welcome carries protocol 2 fields: %+v", r.runner.Welcome)
+ }
+ token := r.inst.EnrolRunner(t).Token
+ w, err := DialRunnerHello(r.ctx, r.inst.URL, token, WorkerHello(0))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer w.Close()
+ if w.Welcome.Role != wire.RoleWorker || w.Welcome.Protocol != wire.Protocol2 || w.Welcome.Release == "" {
+ t.Fatalf("worker welcome %+v", w.Welcome)
+ }
+ shape(t, "frames/welcome-worker.json", w.Received[0])
+ w.Close()
+ // The same worker at protocol 1 is refused: it could not say what it is.
+ if _, err := DialRunner(r.ctx, r.inst.URL, token, 0); CloseStatus(err) != wire.CloseRevoked {
+ t.Fatalf("protocol 1 worker connected: %v", err)
+ }
+ // The primary at protocol 2 is told it is the primary.
+ hello := WorkerHello(r.runner.Welcome.Generation)
+ hello.Platform, hello.Label, hello.Sandbox = &wire.Platform{OS: "linux", Arch: "amd64"}, "docs-t1", wire.SandboxBubblewrap
+ p, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, hello)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer p.Close()
+ if p.Welcome.Role != wire.RolePrimary || p.Welcome.Protocol != wire.Protocol2 {
+ t.Fatalf("primary welcome %+v", p.Welcome)
+ }
+}
+
+// Mailbox scoping (M6): a worker sees none of the primary's commands; its
+// ack of one is a no-op; its report of the primary's step is refused
+// without effect; its sync settles none of the primary's steps, including
+// an attempt still awaiting its termination proof, which still refuses
+// Retry.
+func TestContractWorkerScoping(t *testing.T) {
+ r := newToolRig(t)
+ ctx := r.ctx
+ running := taskID(t, r.call("w1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Running on the primary", "brief": "b"}))
+ r.call("w2", wire.ToolStartTask, map[string]string{"task": running, "brief": "go"})
+ _, body := r.expect(wire.FrameDispatch)
+ d1 := body.(*wire.DispatchCommand)
+ r.step("r-w1", wire.StepReport{TaskID: running, StepID: d1.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40)})
+
+ pending := taskID(t, r.call("w3", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Awaiting its proof", "brief": "b"}))
+ r.call("w4", wire.ToolStartTask, map[string]string{"task": pending, "brief": "go"})
+ _, body = r.expect(wire.FrameDispatch)
+ d2 := body.(*wire.DispatchCommand)
+ r.step("r-w2", wire.StepReport{TaskID: pending, StepID: d2.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", BaseSHA: strings.Repeat("1", 40)})
+ r.wait("failed, unproven", func(c *Conversation) bool {
+ s := c.Steps[d2.StepID]
+ return s.State == wire.StepFailed && !s.Terminated
+ })
+
+ // A third task's dispatch the primary has not acked yet.
+ unacked := taskID(t, r.call("w5", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Not acked", "brief": "b"}))
+ r.call("w6", wire.ToolStartTask, map[string]string{"task": unacked, "brief": "go"})
+ var held wire.Frame
+ for _, h := range r.held {
+ if h.f.Type == wire.FrameDispatch {
+ held = h.f
+ }
+ }
+ if held.ID == "" {
+ f, _, err := r.runner.Expect(ctx, wire.FrameDispatch)
+ if err != nil {
+ t.Fatal(err)
+ }
+ held = f
+ }
+
+ w := r.worker()
+ // The worker's ack of the primary's command does nothing.
+ if err := w.Send(ctx, "wa-1", wire.FrameAck, wire.Ack{ID: held.ID}); err != nil {
+ t.Fatal(err)
+ }
+ // The worker's report of the primary's step is refused.
+ if err := w.Send(ctx, "w-rep", wire.FrameStep, wire.StepReport{TaskID: running, StepID: d1.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true}); err != nil {
+ t.Fatal(err)
+ }
+ if f, body, err := w.Expect(ctx, wire.FrameAck); err != nil || body.(*wire.Ack).ID != "w-rep" {
+ t.Fatalf("refused report not acked: %v %v", f, err)
+ }
+ // The worker syncs holding nothing.
+ if err := w.Send(ctx, "w-sync", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}}); err != nil {
+ t.Fatal(err)
+ }
+ // A durable frame after the sync: once acked, both were applied.
+ if err := w.Send(ctx, "w-after", wire.FrameStep, wire.StepReport{TaskID: running, StepID: d1.StepID, Attempt: 1, State: wire.StepRunning}); err != nil {
+ t.Fatal(err)
+ }
+ if _, body, err := w.Expect(ctx, wire.FrameAck); err != nil || body.(*wire.Ack).ID != "w-after" {
+ t.Fatalf("no ack after the sync: %v", err)
+ }
+ time.Sleep(100 * time.Millisecond)
+ for id, want := range map[string]string{running: wire.StepRunning, pending: wire.StepFailed, unacked: wire.StepQueued} {
+ k, err := r.client.Task(ctx, id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if s := k.Steps[0]; s.State != want || s.Terminated {
+ t.Fatalf("worker changed the primary's step %s: %+v", id, s)
+ }
+ }
+ // Still awaiting its proof: Retry is refused.
+ if _, err := r.client.RetryTask(ctx, pending); Status(err) != 409 {
+ t.Fatalf("retry before termination: %v", err)
+ }
+ // The worker was never sent the primary's commands, and the primary's
+ // dispatch is still unacked: the primary gets it again on reconnect.
+ for _, raw := range w.Received {
+ f, _, _ := wire.ParseFrame(raw)
+ if f.Type != wire.FrameAck && f.Type != wire.FrameWelcome {
+ t.Fatalf("worker received %s", raw)
+ }
+ }
+ r.runner.Close()
+ again := r.dial(r.runner.Welcome.Generation)
+ f, _, err := again.Expect(ctx, wire.FrameDispatch)
+ for err == nil && f.ID != held.ID {
+ f, _, err = again.Expect(ctx, wire.FrameDispatch)
+ }
+ if err != nil {
+ t.Fatalf("the unacked dispatch was lost: %v", err)
+ }
+}
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index ae12540e..2738f83e 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -283,6 +283,18 @@ type Refused struct {
// or sends.
var protocol2Only = map[string]bool{FrameBlob: true, FrameSendPack: true, FramePublish: true, FramePublished: true, FrameRefused: true}
+// RunnerProtocolPath answers the runner protocol this instance speaks, so
+// a worker can refuse to enrol with an instance that has no workers.
+const RunnerProtocolPath = "/api/runner/protocol"
+
+// RunnerProtocol is GET RunnerProtocolPath.
+type RunnerProtocol struct {
+ Protocol int `json:"protocol"`
+}
+
+// Speaks reports whether a frame type exists at protocol.
+func Speaks(protocol int, kind string) bool { return protocol >= Protocol2 || !protocol2Only[kind] }
+
// ErrProtocol means a frame cannot be spoken at the connection's protocol.
var ErrProtocol = errors.New("wire: frame not in this protocol")
@@ -293,7 +305,7 @@ func Encode(f Frame, protocol int) (Frame, error) {
if protocol >= Protocol2 {
return f, nil
}
- if protocol2Only[f.Type] {
+ if !Speaks(protocol, f.Type) {
return Frame{}, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, f.Type, protocol)
}
body, err := f.Decode()